ketting
Version:
Opinionated HATEOAS / Rest client.
73 lines • 1.91 kB
JavaScript
import sax from 'sax';
import { resolve } from './uri.js';
export function parseHtml(contextUri, body) {
const parser = sax.parser(false, {});
const links = [];
const forms = [];
parser.onopentag = node => {
switch (node.name) {
case 'LINK':
case 'A':
links.push(...parseLink(contextUri, node));
break;
case 'FORM':
forms.push(...parseForm(contextUri, node));
break;
}
};
parser.write(body).close();
return {
forms,
links,
};
}
function parseLink(contextUri, node) {
if (!node.attributes.REL) {
return [];
}
if (!node.attributes.HREF) {
return [];
}
const rels = node.attributes.REL;
const links = [];
for (const rel of rels.split(' ')) {
const type = node.attributes.TYPE;
const link = {
rel,
context: contextUri,
href: node.attributes.HREF,
};
if (type)
link.type = type;
links.push(link);
}
return links;
}
function parseForm(contextUri, node) {
const rels = node.attributes.REL || null;
const id = node.attributes.ID || null;
const action = node.attributes.ACTION || '';
const method = node.attributes.METHOD || 'GET';
const enctype = node.attributes.ENCTYPE || 'application/x-www-form-urlencoded';
if (!rels) {
return [{
rel: null,
id,
action: resolve(contextUri, action),
method,
enctype,
}];
}
const result = [];
for (const rel of rels.split(' ')) {
result.push({
rel,
id,
action: resolve(contextUri, action),
method,
enctype,
});
}
return result;
}
//# sourceMappingURL=html.js.map