/
optimized-images.js
171 lines (144 loc) · 6.37 KB
/
optimized-images.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
/**
* @license Copyright 2017 The Lighthouse Authors. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/
/**
* @fileoverview Determines optimized jpeg/webp filesizes for all same-origin and dataURI images by
* running the images through canvas in the browser context.
*/
'use strict';
const log = require('lighthouse-logger');
const Gatherer = require('../gatherer.js');
const URL = require('../../../lib/url-shim.js');
const NetworkRequest = require('../../../lib/network-request.js');
const Sentry = require('../../../lib/sentry.js');
const Driver = require('../../driver.js'); // eslint-disable-line no-unused-vars
// Image encoding can be slow and we don't want to spend forever on it.
// Cap our encoding to 5 seconds, anything after that will be estimated.
const MAX_TIME_TO_SPEND_ENCODING = 5000;
// Cap our image file size at 2MB, anything bigger than that will be estimated.
const MAX_RESOURCE_SIZE_TO_ENCODE = 2000 * 1024;
const JPEG_QUALITY = 0.92;
const WEBP_QUALITY = 0.85;
const MINIMUM_IMAGE_SIZE = 4096; // savings of <4 KiB will be ignored in the audit anyway
const IMAGE_REGEX = /^image\/((x|ms|x-ms)-)?(png|bmp|jpeg)$/;
/** @typedef {{requestId: string, url: string, mimeType: string, resourceSize: number}} SimplifiedNetworkRecord */
class OptimizedImages extends Gatherer {
constructor() {
super();
this._encodingStartAt = 0;
}
/**
* @param {Array<LH.Artifacts.NetworkRequest>} networkRecords
* @return {Array<SimplifiedNetworkRecord>}
*/
static filterImageRequests(networkRecords) {
/** @type {Set<string>} */
const seenUrls = new Set();
return networkRecords.reduce((prev, record) => {
// Skip records that we've seen before, never finished, or came from child targets (OOPIFS).
if (seenUrls.has(record.url) || !record.finished || record.sessionId) {
return prev;
}
seenUrls.add(record.url);
const isOptimizableImage = record.resourceType === NetworkRequest.TYPES.Image &&
IMAGE_REGEX.test(record.mimeType);
const actualResourceSize = Math.min(record.resourceSize || 0, record.transferSize || 0);
if (isOptimizableImage && actualResourceSize > MINIMUM_IMAGE_SIZE) {
prev.push({
requestId: record.requestId,
url: record.url,
mimeType: record.mimeType,
resourceSize: actualResourceSize,
});
}
return prev;
}, /** @type {Array<SimplifiedNetworkRecord>} */ ([]));
}
/**
* @param {Driver} driver
* @param {string} requestId
* @param {'jpeg'|'webp'} encoding Either webp or jpeg.
* @return {Promise<LH.Crdp.Audits.GetEncodedResponseResponse>}
*/
_getEncodedResponse(driver, requestId, encoding) {
requestId = NetworkRequest.getRequestIdForBackend(requestId);
const quality = encoding === 'jpeg' ? JPEG_QUALITY : WEBP_QUALITY;
const params = {requestId, encoding, quality, sizeOnly: true};
return driver.sendCommand('Audits.getEncodedResponse', params);
}
/**
* @param {Driver} driver
* @param {SimplifiedNetworkRecord} networkRecord
* @return {Promise<{originalSize: number, jpegSize?: number, webpSize?: number}>}
*/
async calculateImageStats(driver, networkRecord) {
const originalSize = networkRecord.resourceSize;
// Once we've hit our execution time limit or when the image is too big, don't try to re-encode it.
// Images in this execution path will fallback to byte-per-pixel heuristics on the audit side.
if (Date.now() - this._encodingStartAt > MAX_TIME_TO_SPEND_ENCODING ||
originalSize > MAX_RESOURCE_SIZE_TO_ENCODE) {
return {originalSize, jpegSize: undefined, webpSize: undefined};
}
const jpegData = await this._getEncodedResponse(driver, networkRecord.requestId, 'jpeg');
const webpData = await this._getEncodedResponse(driver, networkRecord.requestId, 'webp');
return {
originalSize,
jpegSize: jpegData.encodedSize,
webpSize: webpData.encodedSize,
};
}
/**
* @param {Driver} driver
* @param {Array<SimplifiedNetworkRecord>} imageRecords
* @return {Promise<LH.Artifacts['OptimizedImages']>}
*/
async computeOptimizedImages(driver, imageRecords) {
this._encodingStartAt = Date.now();
/** @type {LH.Artifacts['OptimizedImages']} */
const results = [];
for (const record of imageRecords) {
try {
const stats = await this.calculateImageStats(driver, record);
/** @type {LH.Artifacts.OptimizedImage} */
const image = {failed: false, ...stats, ...record};
results.push(image);
} catch (err) {
log.warn('optimized-images', err.message);
// Track this with Sentry since these errors aren't surfaced anywhere else, but we don't
// want to tank the entire run due to a single image.
Sentry.captureException(err, {
tags: {gatherer: 'OptimizedImages'},
extra: {imageUrl: URL.elideDataURI(record.url)},
level: 'warning',
});
/** @type {LH.Artifacts.OptimizedImageError} */
const imageError = {failed: true, errMsg: err.message, ...record};
results.push(imageError);
}
}
return results;
}
/**
* @param {LH.Gatherer.PassContext} passContext
* @param {LH.Gatherer.LoadData} loadData
* @return {Promise<LH.Artifacts['OptimizedImages']>}
*/
afterPass(passContext, loadData) {
const networkRecords = loadData.networkRecords;
const imageRecords = OptimizedImages
.filterImageRequests(networkRecords)
.sort((a, b) => b.resourceSize - a.resourceSize);
return Promise.resolve()
.then(_ => this.computeOptimizedImages(passContext.driver, imageRecords))
.then(results => {
const successfulResults = results.filter(result => !result.failed);
if (results.length && !successfulResults.length) {
throw new Error('All image optimizations failed');
}
return results;
});
}
}
module.exports = OptimizedImages;