@metamask/snaps-utils
Version:
A collection of utilities for MetaMask Snaps
49 lines • 1.35 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.isSvg = exports.parseSvg = void 0;
const utils_1 = require("@metamask/utils");
const fast_xml_parser_1 = require("fast-xml-parser");
/**
* Parse and validate a string as an SVG.
*
* @param svg - An SVG string.
* @returns The SVG, its attributes and children in an object format.
*/
function parseSvg(svg) {
try {
const trimmed = svg.trim();
(0, utils_1.assert)(trimmed.length > 0);
const parser = new fast_xml_parser_1.XMLParser({
ignoreAttributes: false,
parseAttributeValue: true,
});
const parsed = parser.parse(trimmed, true);
(0, utils_1.assert)((0, utils_1.hasProperty)(parsed, 'svg'));
// Empty SVGs are not returned as objects
if (!(0, utils_1.isObject)(parsed.svg)) {
return {};
}
return parsed.svg;
}
catch {
throw new Error('Snap icon must be a valid SVG.');
}
}
exports.parseSvg = parseSvg;
/**
* Validate that a string is a valid SVG.
*
* @param svg - An SVG string.
* @returns True if the SVG is valid otherwise false.
*/
function isSvg(svg) {
try {
parseSvg(svg);
return true;
}
catch {
return false;
}
}
exports.isSvg = isSvg;
//# sourceMappingURL=svg.cjs.map