Skip to content

tknickman/hast-util-from-html

 
 

Repository files navigation

hast-util-from-html

Build Coverage Downloads Size Sponsors Backers Chat

hast utility that turns HTML into a syntax tree.

Contents

What is this?

This package is a utility that takes HTML input and turns it into a hast syntax tree.

When should I use this?

If you want to handle syntax trees manually, use this. Use parse5 instead when you just want to parse HTML and don’t care about hast.

You can also use hast-util-from-parse5 and parse5 yourself manually, or use the rehype plugin rehype-parse, which wraps this utility to also parse HTML at a higher-level (easier) abstraction. xast-util-from-xml can be used if you are dealing with XML instead of HTML.

Finally you can use the utility hast-util-to-html to do the inverse of this utility. It turns hast into HTML.

Install

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

npm install hast-util-from-html

In Deno with esm.sh:

import {fromHtml} from "https://esm.sh/hast-util-from-html@1"

In browsers with esm.sh:

<script type="module">
  import {fromHtml} from "https://esm.sh/hast-util-from-html@1?bundle"
</script>

Use

import {fromHtml} from 'hast-util-from-html'

const tree = fromHtml('<h1>Hello, world!</h1>', {fragment: true})

console.log(tree)

Yields:

{
  type: 'root',
  children: [
    {
      type: 'element',
      tagName: 'h1',
      properties: {},
      children: [Array],
      position: [Object]
    }
  ],
  data: { quirksMode: false },
  position: {
    start: { line: 1, column: 1, offset: 0 },
    end: { line: 1, column: 23, offset: 22 }
  }
}

API

This package exports the identifier fromHtml. There is no default export.

fromHtml(value[, options])

Turn serialized HTML into a hast tree.

Parameters
  • value (Compatible) — serialized HTML to parse
  • options (Options, optional) — configuration
Returns

Tree (Root).

Options

Configuration (TypeScript type).

Fields
options.space

Which space the document is in ('svg' or 'html', default: 'html').

When an <svg> element is found in the HTML space, hast-util-from-html already automatically switches to and from the SVG space when entering and exiting it.

👉 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.

👉 Note: make sure to set fragment: true if space: 'svg'.

options.verbose

Add extra positional info about attributes, start tags, and end tags (boolean, default: false).

options.fragment

Whether to parse as a fragment (boolean, default: false). The default is to expect a whole document. In document mode, unopened html, head, and body elements are opened.

options.onerror

Function called when encountering HTML parse errors (OnError, optional).

options[key in ErrorCode]

Specific parse errors can be configured by setting their identifiers (see ErrorCode) as keys directly in options to an ErrorSeverity as value.

The list of parse errors:

OnError

Function called when encountering HTML parse errors.

Parameters
Returns

Nothing (void).

ErrorCode

Known names of parse errors (TypeScript type).

Types
type ErrorCode =
  | 'abandonedHeadElementChild'
  | 'abruptClosingOfEmptyComment'
  | 'abruptDoctypePublicIdentifier'
  // … see readme on `options[key in ErrorCode]` above.

ErrorSeverity

Error severity (TypeScript type).

Types
export type ErrorSeverity =
  // Turn the parse error off:
  | 0
  | false
  // Turn the parse error into a warning:
  | 1
  | true
  // Turn the parse error into an actual error: processing stops.
  | 2

Examples

Example: fragment versus document

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

import {fromHtml} from 'hast-util-from-html'

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

console.log(fromHtml(doc))

console.log(fromHtml(doc, {fragment: true}))

…yields (positional info and data omitted for brevity):

{
  type: 'root',
  children: [
    {type: 'element', tagName: 'html', properties: {}, children: [Array]}
  ]
}
{
  type: 'root',
  children: [
    {type: 'element', tagName: 'title', properties: {}, children: [Array]},
    {type: 'element', tagName: 'h1', properties: {}, children: [Array]}
  ]
}

👉 Note: observe that when a whole document is expected (first 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 {fromHtml} from 'hast-util-from-html'
import {inspect} from 'unist-util-inspect'

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

console.log(inspect(fromHtml(doc)))

…yields:

root[2] (1:1-9:8, 0-119)
│ data: {"quirksMode":false}
├─0 doctype (1:1-1:16, 0-15)
└─1 element<html>[3] (2:1-9:8, 16-119)
    │ properties: {"lang":"en"}
    ├─0 element<head>[3] (3:3-5:10, 33-72)
    │   │ properties: {}
    │   ├─0 text "\n    " (3:9-4:5, 39-44)
    │   ├─1 element<title>[1] (4:5-4:23, 44-62)
    │   │   │ properties: {}
    │   │   └─0 text "Hi!" (4:12-4:15, 51-54)
    │   └─2 text "\n  " (4:23-5:3, 62-65)
    ├─1 text "\n  " (5:10-6:3, 72-75)
    └─2 element<body>[3] (6:3-9:8, 75-119)
        │ properties: {}
        ├─0 text "\n    " (6:9-7:5, 81-86)
        ├─1 element<h1>[1] (7:5-7:20, 86-101)
        │   │ properties: {}
        │   └─0 text "Hello!" (7:9-7:15, 90-96)
        └─2 text "\n  \n" (7:20-9:1, 101-112)

👉 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 we follow.

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 {fromHtml} from 'hast-util-from-html'

const doc = `<!doctypehtml>
<title class="a" class="b">Hello…</title>
<h1/>World!</h1>`

fromHtml(doc, {
  onerror: console.log,
  missingWhitespaceBeforeDoctypeName: 2, // Mark one as a fatal error.
  nonVoidHtmlElementStartTagWithTrailingSolidus: false // Ignore one.
})

…yields:

[1:10-1:10: Missing whitespace before doctype name] {
  reason: 'Missing whitespace before doctype name',
  line: 1,
  column: 10,
  source: 'parse-error',
  ruleId: 'missing-whitespace-before-doctype-name',
  position: [Object],
  fatal: true,
  note: 'Unexpected `h`. Expected ASCII whitespace instead',
  url: 'https://html.spec.whatwg.org/multipage/parsing.html#parse-error-missing-whitespace-before-doctype-name'
}
[2:23-2:23: Unexpected duplicate attribute] {
  reason: 'Unexpected duplicate attribute',
  line: 2,
  column: 23,
  source: 'parse-error',
  ruleId: 'duplicate-attribute',
  position: [Object],
  fatal: false,
  note: 'Unexpectedly double attribute. Expected attributes to occur only once',
  url: 'https://html.spec.whatwg.org/multipage/parsing.html#parse-error-duplicate-attribute'
}

🧑‍🏫 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 we 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 can continue to do work.

Syntax

HTML is parsed according to WHATWG HTML (the living standard), which is also followed by browsers such as Chrome and Firefox.

Types

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

Compatibility

Projects maintained by the unified collective are compatible with all maintained versions of Node.js. As of now, that is Node.js 14.14+ and 16.0+. Our projects sometimes work with older versions, but this is not guaranteed.

Security

Parsing HTML is safe but using user-provided content can open you up to a cross-site scripting (XSS) attack. Use hast-util-santize to make the hast tree safe.

Related

Contribute

See contributing.md in syntax-tree/.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.

License

MIT © Titus Wormer

About

hast utility to parse from HTML

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • JavaScript 100.0%