@metamask/snaps-utils
Version:
A collection of utilities for MetaMask Snaps
58 lines • 2.43 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.getSvgDimensions = exports.assertIsSnapIcon = exports.SVG_MAX_BYTE_SIZE_TEXT = exports.SVG_MAX_BYTE_SIZE = void 0;
const utils_1 = require("@metamask/utils");
const svg_1 = require("./svg.cjs");
exports.SVG_MAX_BYTE_SIZE = 100000;
exports.SVG_MAX_BYTE_SIZE_TEXT = `${Math.floor(exports.SVG_MAX_BYTE_SIZE / 1000)}kb`;
/**
* Assert that a virtual file containing a Snap icon is valid.
*
* @param icon - A virtual file containing a Snap icon.
*/
function assertIsSnapIcon(icon) {
(0, utils_1.assert)(icon.path.endsWith('.svg'), 'Expected snap icon to end in ".svg".');
const byteLength = typeof icon.value === 'string'
? (0, utils_1.stringToBytes)(icon.value).byteLength
: icon.value.byteLength;
(0, utils_1.assert)(byteLength <= exports.SVG_MAX_BYTE_SIZE, `The specified SVG icon exceeds the maximum size of ${exports.SVG_MAX_BYTE_SIZE_TEXT}.`);
(0, utils_1.assert)((0, svg_1.isSvg)(icon.toString()), 'Snap icon must be a valid SVG.');
}
exports.assertIsSnapIcon = assertIsSnapIcon;
/**
* Extract the dimensions of an image from an SVG string if possible.
*
* @param svg - An SVG string.
* @returns The height and width of the SVG or null.
*/
function getSvgDimensions(svg) {
try {
const parsed = (0, svg_1.parseSvg)(svg);
const height = parsed['@_height'];
const width = parsed['@_width'];
if (height && width) {
return { height, width };
}
const viewBox = parsed['@_viewBox'];
if (viewBox) {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const [_minX, _minY, viewBoxWidth, viewBoxHeight] = viewBox.split(' ');
if (viewBoxWidth && viewBoxHeight) {
const parsedWidth = parseInt(viewBoxWidth, 10);
const parsedHeight = parseInt(viewBoxHeight, 10);
(0, utils_1.assert)(Number.isInteger(parsedWidth) && parsedWidth > 0);
(0, utils_1.assert)(Number.isInteger(parsedHeight) && parsedHeight > 0);
return {
width: parsedWidth,
height: parsedHeight,
};
}
}
}
catch {
throw new Error('Snap icon must be a valid SVG.');
}
return null;
}
exports.getSvgDimensions = getSvgDimensions;
//# sourceMappingURL=icon.cjs.map