This page documents @lanexio/parser-grammar-html, the HTML grammar package implementing the full WHATWG HTML parsing algorithm, including all 23 insertion modes, adoption agency, foster parenting, and foreign content (SVG, MathML).
Version: Stable
Module name: parser-grammar-html
Package: @lanexio/parser-grammar-html
Import path: @lanexio/parser-grammar-html
Layer: 2 (Grammar)
Runtime: Universal (browser, server, edge worker)
Module format: ESM
Stability: Stable
Primary use case: Parse HTML documents and fragments into a flat AST.
Layer 2 dependency rules
This package depends only on Layer 1 core packages. It does not import from query, bridge, devtools, or entry packages. Grammar packs never depend on other grammar packs.
You need to parse HTML documents or fragments (innerHTML) into a traversable AST.
You need to serialize a parsed HTML tree back to HTML source.
You need to sanitize HTML content against a configurable policy.
You need to extract text content or decode HTML entities.
Boundary Description Inputs Uint8Array (source bytes) + optional ParseHtmlOptionsOutputs LexTree (flat AST rooted at HtmlKind.Document or HtmlKind.Fragment)Side effects None Determinism Yes (same bytes + same options produce identical tree) External dependencies @lanexio/parser-coreNever-throw guarantee Yes for all parse entry points Security surface serializeHtml() emits raw HTML (XSS risk if caller passes output to innerHTML). sanitizeHtml() mitigates this.
Install the package.
pnpm add @lanexio/parser-grammar-html
npm install @lanexio/parser-grammar-html
yarn add @lanexio/parser-grammar-html
Import the named export.
import { parseHtml } from ' @lanexio/parser-grammar-html ' ;
Requirement Required Layer Notes @lanexio/parser-coreYes 1 ^1.0.0
import { parseHtml } from ' @lanexio/parser-grammar-html ' ;
const encoder = new TextEncoder ();
const bytes = encoder . encode ( ' <!doctype html><p>Hello <strong>world</strong></p> ' );
const tree = parseHtml (bytes);
console . log (tree . nodeCount ); // total nodes in the flat AST
console . log (tree . root . kind ); // HtmlKind.Document
import { parseHtml, HtmlParseMode } from ' @lanexio/parser-grammar-html ' ;
const encoder = new TextEncoder ();
encoder . encode ( ' <li>Item one</li><li>Item two</li> ' ) ,
{ mode: HtmlParseMode . Fragment , contextElement: ' ul ' }
import { parseHtml, serializeHtml } from ' @lanexio/parser-grammar-html ' ;
const encoder = new TextEncoder ();
const tree = parseHtml (encoder . encode ( ' <p>Hello <b>world</b> ' ));
const html = serializeHtml (tree);
// "<html><head></head><body><p>Hello <b>world</b></p></body></html>"
Export Type Description parseHtml(source: Uint8Array, options?: ParseHtmlOptions) => LexTreeParse HTML. Never throws. serializeHtml(input: LexTree | LexNode, options?: SerializeHtmlOptions) => stringSerialize tree back to HTML string. sanitizeHtml(tree: LexTree, policy?: SanitizePolicy) => LexTreeProduce a safe projection of a parsed HTML tree. sanitizeHtmlToString(tree: LexTree, policy?: SanitizePolicy) => stringSerialize safe content to string via inline AST filtering. HtmlKindconst objectNumeric kind IDs for all HTML node types. HtmlFieldconst objectNumeric field IDs for HTML attributes and slots. HTML_FIELD_NAMES_BY_IDreadonly string[]Field name lookup by numeric field ID. HtmlParseModeconst objectDocument, FragmentHtmlParseErrorCodeconst objectParse error code constants. DEFAULT_POLICYSanitizePolicyDefault sanitization policy (allows most safe HTML). resolvePolicy(policy?: SanitizePolicy) => SanitizePolicyResolve a policy, falling back to DEFAULT_POLICY. isSafeUrl(url: string) => booleanCheck if a URL scheme is considered safe. isSafeSrcset(srcset: string) => booleanCheck if a srcset attribute value is safe. isAttributeSafe(name: string, value: string) => booleanCheck if an attribute name/value pair is safe. isTagAllowed(tag: string) => booleanCheck if a tag is allowed by the default policy. textContent(node: LexNode) => stringExtract plain text from an HTML tree. decodeEntities(text: string) => stringDecode HTML character references. RAWTEXT_ELEMENT_NAMESreadonly string[]Names of raw-text elements (script, style). TokenKindconst objectToken type constants from the tokenizer. tokenize(source: Uint8Array, options?: TokenizeOptions) => Token[]Tokenize HTML source bytes. DEFAULT_CONTENT_MODESobjectDefault tokenizer content modes. htmlGrammarLanexioParserPureGrammarGrammar descriptor for use with parser-pure. htmlRegistrationGrammarRegistrationRegistration for the unified grammar registry.
Field Type Required Default Description modeHtmlParseModeNo HtmlParseMode.DocumentParse as a full document or as a fragment. contextElementstringNo undefinedContext element name for fragment parsing (e.g. "div", "td", "svg"). contextElementLeafstringNo undefinedLeaf element within the foreign-namespace context for fragment parsing. scriptingEnabledbooleanNo falseScripting flag. When true, <noscript> is raw-text content. wasmTokenizer(source: Uint8Array) => Token[]No undefinedOptional WASM-backed tokenizer fast-path.
Field Type Required Default Description outerbooleanNo trueWhen true, serialize the root node and all children (outerHTML). When false, serialize only children (innerHTML).
Property Type Description rootLexNodeRoot node (HtmlKind.Document or HtmlKind.Fragment). nodeCountnumberTotal nodes in the tree. sourceUint8ArrayOriginal parsed bytes.
Type Purpose Notes ParseHtmlOptionsOptions for parseHtml See options table above. HtmlParseModeUnion of parse mode values HtmlParseMode.Document | HtmlParseMode.FragmentSerializeHtmlOptionsOptions for serializeHtml See options table above. SanitizePolicySanitization policy Defines which tags, attributes, and URLs are allowed. HtmlParseErrorParse error descriptor Returned via error codes. WasmScanExportsType for WASM tokenizer exports Internal.
parseHtml supports two modes:
Document mode (default): parses as a full HTML document with implied <html>, <head>, <body>.
Fragment mode : parses as an HTML fragment in the context of a specific element (like innerHTML).
Pass a wasmTokenizer option to use the WASM-backed tokenizer as a fast-path. When the source contains no character references, the WASM tokenizer is used instead of the TypeScript tokenizer.
The HTML parser preserves semantic HTML structure (headings, landmarks, lists, image alt attributes). The serializer outputs raw HTML that can be directly injected into a browser — consuming code is responsible for ensuring semantic output.
Concern Status Generated output semantics Preserves HTML semantics (headings, landmarks, lists, alt text) ARIA attributes in serialized output Preserved Semantic element round-trip Yes
parseHtml never throws on any byte sequence. Malformed input produces LexError nodes.
serializeHtml() emits raw HTML. Callers must not pass the output directly to innerHTML without escaping.
sanitizeHtml() and sanitizeHtmlToString() provide configurable sanitization against XSS.
Threat Mitigation Status Malformed input byte sequence Panic-free guarantee: all inputs accepted, errors produce LexError AST nodes Implemented XSS via serializer output serializeHtml() emits raw HTML — caller is responsible for safe insertion. sanitizeHtml() provides policy-based filteringDocumented
Package Relationship Layer Notes @lanexio/parser-coreRequires 1 Provides LexTree, LexNode, LexCursor @lanexio/parser-pureConsumes 4 Wraps parseHtml in a unified bridge @lanexio/parserConsumes 6 Re-exports parseHtml as an optional grammar
import { parseHtml, HtmlKind } from ' @lanexio/parser-grammar-html ' ;
import { LexQuery } from ' @lanexio/parser-query ' ;
const encoder = new TextEncoder ();
const tree = parseHtml (encoder . encode ( ' <ul><li>one</li><li>two</li></ul> ' ));
const resolver = ( name : string ) => (HtmlKind as Record < string , number | undefined > )[name];
const query = LexQuery . compile ( ' Element ' , resolver);
for ( const node of query . matches (tree)) {
console . log (node . kind , node . range );
Version Date Status Notable changes 1.0.02026-05-29Current Initial stable release. Apache-2.0.
Flat AST How the 16-byte node layout works and how to traverse it efficiently. Parsing HTML Guide: parse HTML documents with full options and serialization.