// The WHATWG HTML grammar is shared mechanics; what a pack keeps of a document is the pack's own policy.
// The exact optional dependency belongs to this kernel, so Node and browser bundles resolve one parser.
// Source: parse5 7.3.0 (parseFragment, serialize, defaultTreeAdapter).
//
// A fragment is parsed in an HTML `
` context. Elements keep their namespace (HTML, SVG or MathML) and attributes
// their prefix and namespace, and serialization reproduces what the tree holds: a foreign subtree survives parsing, and
// a pack's policy may drop it.
export type HtmlAttribute = { name: string; value: string; prefix?: string; namespace?: string };
export type HtmlElement = { type: 'element'; name: string; namespace: string; attributes: HtmlAttribute[]; children: HtmlNode[] };
export type HtmlText = { type: 'text'; value: string };
export type HtmlNode = HtmlElement | HtmlText;
export class HtmlError extends Error {
constructor(readonly code: 'parser-unavailable') {
super('HTML parser parse5 7.3.0 is unavailable');
this.name = 'HtmlError';
}
}
type Grammar = typeof import('parse5');
type Tree = import('parse5').DefaultTreeAdapterMap;
let grammar: Promise | undefined;
function loadGrammar(): Promise {
return grammar ??= import('parse5').catch(() => { grammar = undefined; throw new HtmlError('parser-unavailable'); });
}
/**
* A fragment parsed as WHATWG fragment parsing does in an HTML `` context: elements and text, comments dropped,
* an HTML ``'s content carried as that element's children. Importing this module does not load the grammar.
*/
export async function parseFragment(source: string): Promise {
const { parseFragment: parse, defaultTreeAdapter: tree, html } = await loadGrammar();
const convert = (nodes: Tree['node'][]): HtmlNode[] => {
const out: HtmlNode[] = [];
for (const node of nodes) {
if (node.nodeName === '#text') out.push({ type: 'text', value: (node as Tree['textNode']).value });
else if ('tagName' in node) {
const element = node as Tree['element'];
// only an HTML template has content; an SVG or MathML `template` is a foreign element with children
const children = element.tagName === 'template' && element.namespaceURI === html.NS.HTML
? (element as Tree['template']).content.childNodes
: element.childNodes;
out.push({
type: 'element', name: element.tagName, namespace: element.namespaceURI,
attributes: element.attrs.map(attr => ({ name: attr.name, value: attr.value, ...(attr.prefix ? { prefix: attr.prefix } : {}), ...(attr.namespace ? { namespace: attr.namespace } : {}) })),
children: convert(children),
});
}
}
return out;
};
return convert(parse(tree.createElement('body', html.NS.HTML, []), source, {}).childNodes);
}
/** Nodes serialized by the WHATWG HTML fragment serialization: its escaping, its void elements, its foreign names. */
export async function serialize(nodes: HtmlNode[]): Promise {
const { serialize: write, defaultTreeAdapter: tree, html } = await loadGrammar();
const append = (parent: Tree['parentNode'], list: HtmlNode[]): void => {
for (const node of list) {
if (node.type === 'text') { tree.insertText(parent, node.value); continue; }
const element = tree.createElement(node.name, node.namespace as import('parse5').html.NS,
node.attributes.map(({ name, value, prefix, namespace }) => ({ name, value, ...(prefix ? { prefix } : {}), ...(namespace ? { namespace } : {}) })));
tree.appendChild(parent, element);
if (node.name === 'template' && node.namespace === html.NS.HTML) {
const content = tree.createDocumentFragment();
tree.setTemplateContent(element as Tree['template'], content);
append(content, node.children);
} else append(element, node.children);
}
};
const fragment = tree.createDocumentFragment();
append(fragment, nodes);
return write(fragment);
}