UNPKG

1.05 kBJavaScriptView Raw
1"use strict";
2
3var format = require("util").format,
4 MAX_LENGTH = 4 * 1024;
5
6/**
7 * @param { import("../lib/css-analyzer") } analyzer
8 */
9function rule(analyzer) {
10 // @see http://stackoverflow.com/a/11335500
11 var re = /data:.+\/(.+);base64,(.*)\)/;
12 analyzer.setMetric("base64Length");
13
14 analyzer.on("declaration", function (rule, property, value) {
15 var base64, buf, matches;
16
17 if (re.test(value)) {
18 // parse data URI
19 matches = value.match(re);
20 base64 = matches[2];
21 buf = Buffer.from(base64, "base64");
22
23 analyzer.incrMetric("base64Length", base64.length);
24
25 if (base64.length > MAX_LENGTH) {
26 analyzer.addOffender(
27 "base64Length",
28 format(
29 "%s { %s: ... } // base64: %s kB, raw: %s kB",
30 rule.selectors.join(", "),
31 property,
32 (base64.length / 1024).toFixed(2),
33 (buf.length / 1024).toFixed(2)
34 )
35 );
36 }
37 }
38 });
39}
40
41rule.description = "Reports on base64-encoded images";
42module.exports = rule;