9.0.1 • Published 3 months ago

rehype-parse v9.0.1

Weekly downloads
341,846
License
MIT
Repository
github
Last release
3 months ago

rehype-parse

Build Coverage Downloads Size Sponsors Backers Chat

rehype plugin to add support for parsing from HTML.

Contents

What is this?

This package is a unified (rehype) plugin that defines how to take HTML as input and turn it into a syntax tree. When it’s used, HTML can be parsed and other rehype plugins can be used after it.

See the monorepo readme for info on what the rehype ecosystem is.

When should I use this?

This plugin adds support to unified for parsing HTML. If you also need to serialize HTML, you can alternatively use rehype, which combines unified, this plugin, and rehype-stringify.

When you are in a browser, trust your content, don’t need positional info, and value a smaller bundle size, you can use rehype-dom-parse instead.

If you don’t use plugins and want to access the syntax tree, you can directly use hast-util-from-html, which is used inside this plugin. rehype focusses on making it easier to transform content by abstracting such internals away.

Install

This package is ESM only. In Node.js (version 16+), install with npm:

npm install rehype-parse

In Deno with esm.sh:

import rehypeParse from 'https://esm.sh/rehype-parse@9'

In browsers with esm.sh:

<script type="module">
  import rehypeParse from 'https://esm.sh/rehype-parse@9?bundle'
</script>

Use

Say we have the following module example.js:

import rehypeParse from 'rehype-parse'
import rehypeRemark from 'rehype-remark'
import remarkStringify from 'remark-stringify'
import {unified} from 'unified'

const file = await unified()
  .use(rehypeParse)
  .use(rehypeRemark)
  .use(remarkStringify)
  .process('<h1>Hello, world!</h1>')

console.log(String(file))

…running that with node example.js yields:

# Hello, world!

API

This package exports no identifiers. The default export is rehypeParse.

unified().use(rehypeParse[, options])

Plugin to add support for parsing from HTML.

Parameters
  • options (Options, optional) — configuration
Returns

Nothing (undefined).

ErrorCode

Known names of parse errors (TypeScript type).

For a bit more info on each error, see hast-util-from-html.

Type
type ErrorCode =
  | 'abandonedHeadElementChild'
  | 'abruptClosingOfEmptyComment'
  | 'abruptDoctypePublicIdentifier'
  | 'abruptDoctypeSystemIdentifier'
  | 'absenceOfDigitsInNumericCharacterReference'
  | 'cdataInHtmlContent'
  | 'characterReferenceOutsideUnicodeRange'
  | 'closingOfElementWithOpenChildElements'
  | 'controlCharacterInInputStream'
  | 'controlCharacterReference'
  | 'disallowedContentInNoscriptInHead'
  | 'duplicateAttribute'
  | 'endTagWithAttributes'
  | 'endTagWithTrailingSolidus'
  | 'endTagWithoutMatchingOpenElement'
  | 'eofBeforeTagName'
  | 'eofInCdata'
  | 'eofInComment'
  | 'eofInDoctype'
  | 'eofInElementThatCanContainOnlyText'
  | 'eofInScriptHtmlCommentLikeText'
  | 'eofInTag'
  | 'incorrectlyClosedComment'
  | 'incorrectlyOpenedComment'
  | 'invalidCharacterSequenceAfterDoctypeName'
  | 'invalidFirstCharacterOfTagName'
  | 'misplacedDoctype'
  | 'misplacedStartTagForHeadElement'
  | 'missingAttributeValue'
  | 'missingDoctype'
  | 'missingDoctypeName'
  | 'missingDoctypePublicIdentifier'
  | 'missingDoctypeSystemIdentifier'
  | 'missingEndTagName'
  | 'missingQuoteBeforeDoctypePublicIdentifier'
  | 'missingQuoteBeforeDoctypeSystemIdentifier'
  | 'missingSemicolonAfterCharacterReference'
  | 'missingWhitespaceAfterDoctypePublicKeyword'
  | 'missingWhitespaceAfterDoctypeSystemKeyword'
  | 'missingWhitespaceBeforeDoctypeName'
  | 'missingWhitespaceBetweenAttributes'
  | 'missingWhitespaceBetweenDoctypePublicAndSystemIdentifiers'
  | 'nestedComment'
  | 'nestedNoscriptInHead'
  | 'nonConformingDoctype'
  | 'nonVoidHtmlElementStartTagWithTrailingSolidus'
  | 'noncharacterCharacterReference'
  | 'noncharacterInInputStream'
  | 'nullCharacterReference'
  | 'openElementsLeftAfterEof'
  | 'surrogateCharacterReference'
  | 'surrogateInInputStream'
  | 'unexpectedCharacterAfterDoctypeSystemIdentifier'
  | 'unexpectedCharacterInAttributeName'
  | 'unexpectedCharacterInUnquotedAttributeValue'
  | 'unexpectedEqualsSignBeforeAttributeName'
  | 'unexpectedNullCharacter'
  | 'unexpectedQuestionMarkInsteadOfTagName'
  | 'unexpectedSolidusInTag'
  | 'unknownNamedCharacterReference'

ErrorSeverity

Error severity (TypeScript type).

  • 0 or false — turn the parse error off
  • 1 or true — turn the parse error into a warning
  • 2 — turn the parse error into an actual error: processing stops
Type
type ErrorSeverity = boolean | 0 | 1 | 2

Options

Configuration (TypeScript type).

👉 Note: this is not an XML parser. It supports SVG as embedded in HTML. It does not support the features available in XML. Passing SVG files might break but fragments of modern SVG should be fine. Use xast-util-from-xml to parse XML.

Fields
  • fragment (boolean, default: false) — whether to parse as a fragment; by default unopened html, head, and body elements are opened
  • emitParseErrors (boolean, default: false) — whether to emit parse errors while parsing
  • space ('html' or 'svg', default: 'html') — which space the document is in
  • verbose (boolean, default: false) — add extra positional info about attributes, start tags, and end tags
  • [key in ErrorCode] (ErrorSeverity, default: 1 if options.emitParseErrors, otherwise 0) — configure specific parse errors

Examples

Example: fragment versus document

The following example shows the difference between parsing as a document and parsing as a fragment:

import rehypeParse from 'rehype-parse'
import rehypeStringify from 'rehype-stringify'
import {unified} from 'unified'

const doc = '<title>Hi!</title><h1>Hello!</h1>'

console.log(
  String(
    await unified()
      .use(rehypeParse, {fragment: true})
      .use(rehypeStringify)
      .process(doc)
  )
)

console.log(
  String(
    await unified()
      .use(rehypeParse, {fragment: false})
      .use(rehypeStringify)
      .process(doc)
  )
)

…yields:

<title>Hi!</title><h1>Hello!</h1>
<html><head><title>Hi!</title></head><body><h1>Hello!</h1></body></html>

👉 Note: observe that when a whole document is expected (second example), missing elements are opened and closed.

Example: whitespace around and inside <html>

The following example shows how whitespace is handled when around and directly inside the <html> element:

import rehypeParse from 'rehype-parse'
import rehypeStringify from 'rehype-stringify'
import {unified} from 'unified'

const doc = `<!doctype html>
<html lang=en>
  <head>
    <title>Hi!</title>
  </head>
  <body>
    <h1>Hello!</h1>
  </body>
</html>`

console.log(
  String(await unified().use(rehypeParse).use(rehypeStringify).process(doc))
)

…yields (where represents a space character):

<!doctype html><html lang="en"><head>
    <title>Hi!</title>
  </head>
  <body>
    <h1>Hello!</h1>
␠␠
</body></html>

👉 Note: observe that the line ending before <html> is ignored, the line ending and two spaces before <head> is moved inside it, and the line ending after </body> is moved before it.

This behavior is described by the HTML standard (see the section 13.2.6.4.1 “The ‘initial’ insertion mode” and adjacent states) which rehype follows.

The changes to this meaningless whitespace should not matter, except when formatting markup, in which case rehype-format can be used to improve the source code.

Example: parse errors

The following example shows how HTML parse errors can be enabled and configured:

import rehypeParse from 'rehype-parse'
import rehypeStringify from 'rehype-stringify'
import {unified} from 'unified'
import {reporter} from 'vfile-reporter'

const file = await unified()
  .use(rehypeParse, {
    emitParseErrors: true, // Emit all.
    missingWhitespaceBeforeDoctypeName: 2, // Mark one as a fatal error.
    nonVoidHtmlElementStartTagWithTrailingSolidus: false // Ignore one.
  })
  .use(rehypeStringify).process(`<!doctypehtml>
<title class="a" class="b">Hello…</title>
<h1/>World!</h1>`)

console.log(reporter(file))

…yields:

1:10-1:10 error   Missing whitespace before doctype name missing-whitespace-before-doctype-name hast-util-from-html
2:23-2:23 warning Unexpected duplicate attribute         duplicate-attribute                    hast-util-from-html

2 messages (✖ 1 error, ⚠ 1 warning)

🧑‍🏫 Info: messages in unified are warnings instead of errors. Other linters (such as ESLint) almost always use errors. Why? Those tools only check code style. They don’t generate, transform, and format code, which is what rehype and unified focus on, too. Errors in unified mean the same as an exception in your JavaScript code: a crash. That’s why we use warnings instead, because we continue checking more HTML and continue running more plugins.

Syntax

HTML is parsed according to WHATWG HTML (the living standard), which is also followed by all browsers.

Syntax tree

The syntax tree format used in rehype is hast.

Types

This package is fully typed with TypeScript. It exports the additional types ErrorCode, ErrorSeverity, and Options.

Compatibility

Projects maintained by the unified collective are compatible with maintained versions of Node.js.

When we cut a new major release, we drop support for unmaintained versions of Node. This means we try to keep the current release line, rehype-parse@^9, compatible with Node.js 16.

Security

As rehype works on HTML and improper use of HTML can open you up to a cross-site scripting (XSS) attack, use of rehype can also be unsafe. Use rehype-sanitize to make the tree safe.

Use of rehype plugins could also open you up to other attacks. Carefully assess each plugin and the risks involved in using them.

For info on how to submit a report, see our security policy.

Contribute

See contributing.md in rehypejs/.github for ways to get started. See support.md for ways to get help.

This project has a code of conduct. By interacting with this repository, organization, or community you agree to abide by its terms.

Sponsor

Support this effort and give back by sponsoring on OpenCollective!

License

MIT © Titus Wormer

brbytes-editor@bytemd/plugin-html2md@dxos/document@dxos/editor@dxos/editor-core@unified-doc/processorbasework-core@mapbox/copyeditor@infinitebrahmanuniverse/nolb-reh@everything-registry/sub-chunk-2644design-library-test@vanillahill99/blockswilsonx-feed-parserxfpshiki-rehypesandpaperseiteschema-dts-genrehype-pretty-coderehype-prismrehype-prism-plusrehype-pseudoremark-graphviz-svgremark-hpcc-graphviz-svgrehyperehype-docsearchrehype-inlinerehype-modrehype-lo-mathrehype-katex-cocalcrehype-image-grouprehype-smilesrehype-partialsrehype-remnoterehype-parse-isomorphicremark-admonitionstextlint-plugin-htmltextlint-plugin-mjmltextlint-util-to-stringvremark-parsevite-plugin-markdown-pagesvite-plugin-rehype@jiakun-zhao/vite-minifier@princesse-xyz/zkn@contentedjs/contented-pipeline-mdmilo-md2docxmilo-parse-markdownloft-editorlegigridsome-plugin-remark-containerjetblogjmas-blocknote-corehuid-reference-cliintuitahtml-to-compiled-mdxhtml-relative-pathshtml-to-notion-blocksidocilib-loctool-ghfmheadsup-serverhokusaighedevmark-cellmarkdown-serializermark-smithmarkdownchatmarkdown-translatemarkdown-doc-loadermarkdown-code-example-insertermarktionmd-card-climd-doc-loadermdx-unified-bundlermdx-prismmdx-prism-2page-spy-web-wsyp-page-spy-webpowerthesaurus-apipos-tagpile-raycastplugins-mdxpoststorenextprops-docusaurus-lunr-searchmyst-to-htmlmyst-transformsn-references-climystjspatternplate-clientreact-code-markdown-loadernetlify-plugin-search-indexnextein-plugin-reading-timenetlify-plugin-corgis-not-pluginsnetlify-plugin-csp-hashnetlify-plugin-csp-headersnetlify-cms-widget-markdownnetlify-cms-widget-markdown-papandreounetlify-cms-widget-markdown-with-underlinenetlify-plugin-algolia-exportnetlify-plugin-algolia-index
9.0.1

3 months ago

8.0.5

1 year ago

9.0.0

1 year ago

8.0.4

3 years ago

8.0.3

3 years ago

8.0.2

3 years ago

8.0.1

3 years ago

8.0.0

3 years ago

7.0.1

5 years ago

7.0.0

5 years ago

6.0.2

5 years ago

6.0.1

5 years ago

6.0.0

6 years ago

5.0.0

6 years ago

4.1.0

7 years ago

4.0.0

8 years ago

3.1.0

8 years ago

3.0.0

8 years ago

2.0.1

8 years ago

2.0.0

8 years ago

1.0.0

9 years ago

0.0.0

9 years ago