-
-
Notifications
You must be signed in to change notification settings - Fork 135
/
index.js
379 lines (341 loc) · 10.1 KB
/
index.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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
import { createRequire } from 'node:module';
import merge from 'lodash.merge';
import pick from 'lodash.pick';
import isEmpty from 'lodash.isempty';
import get from 'lodash.get';
import dayjs from 'dayjs';
import { pathToFolder } from '../pathToFolder.js';
import intel from 'intel';
const log = intel.getLogger('browsertime');
const require = createRequire(import.meta.url);
const version = require('../../../package.json').version;
function generateUniquePageId(baseId, existingIdMap) {
let newId = baseId;
while (existingIdMap.has(newId)) {
newId = newId + '-1';
}
return newId;
}
function getDocumentRequests(entries, pageId) {
let pageEntries = [...entries];
if (pageId) {
pageEntries = entries.filter(entry => entry.pageref === pageId);
}
const requests = [];
let entry;
do {
entry = pageEntries.shift();
requests.push(entry);
} while (entry.response.redirectURL);
return requests;
}
function getFinalURL(entries, pageref) {
const requests = getDocumentRequests(entries, pageref);
const finalEntry = requests.pop();
return finalEntry.request.url;
}
function addExtrasToHAR(
harPage,
visualMetricsData,
timings,
cpu,
googleWebVitals
) {
const harPageTimings = harPage.pageTimings;
const _visualMetrics = (harPage._visualMetrics = {});
harPage._cpu = cpu;
if (googleWebVitals) {
harPage._googleWebVitals = googleWebVitals;
}
// We add the timings both as a hidden field and add
// in pageTimings so we can easily show them in PerfCascade
if (visualMetricsData) {
const DO_NOT_INCLUDE_IN_HAR_TIMINGS = new Set([
'VisualReadiness',
'videoRecordingStart',
'SpeedIndex',
'PerceptualSpeedIndex',
'ContentfulSpeedIndex',
'VisualProgress',
'ContentfulSpeedIndexProgress',
'PerceptualSpeedIndexProgress'
]);
for (let key of Object.keys(visualMetricsData)) {
if (!DO_NOT_INCLUDE_IN_HAR_TIMINGS.has(key)) {
harPageTimings['_' + key.charAt(0).toLowerCase() + key.slice(1)] =
visualMetricsData[key];
_visualMetrics[key] = visualMetricsData[key];
} else if (!key.endsWith('Progress')) {
_visualMetrics[key] = visualMetricsData[key];
}
}
// Make the visual progress structure more JSON
_visualMetrics.VisualProgress = jsonifyVisualProgress(
visualMetricsData.VisualProgress
);
} else if (timings && timings.firstPaint) {
// only add first paint if we don't have visual metrics
harPageTimings._firstPaint = timings.firstPaint;
}
/*
if (cpu && cpu.longTasks && cpu.longTasks.lastLongTask) {
harPageTimings._lastCPULongTask = cpu.longTasks.lastLongTask;
}
*/
if (timings && timings.largestContentfulPaint) {
harPageTimings._largestContentfulPaint =
timings.largestContentfulPaint.renderTime;
}
if (
timings &&
timings.paintTiming &&
timings.paintTiming['first-contentful-paint']
) {
harPageTimings._firstContentfulPaint =
timings.paintTiming['first-contentful-paint'];
}
if (timings && timings.pageTimings) {
harPageTimings._domInteractiveTime = timings.pageTimings.domInteractiveTime;
harPageTimings._domContentLoadedTime =
timings.pageTimings.domContentLoadedTime;
}
}
function addMetaToHAR(index, harPage, url, browserScript, options) {
const _meta = (harPage._meta = {});
_meta.connectivity = get(options, 'connectivity.profile', 'native');
_meta.connectivity = get(options, 'connectivity.alias', _meta.connectivity);
if (options.resultURL) {
const base = options.resultURL.endsWith('/')
? options.resultURL
: options.resultURL + '/';
if (options.screenshot) {
_meta.screenshot = `${base}${pathToFolder(url, options)}screenshots/${
index + 1
}/afterPageCompleteCheck.${options.screenshotParams.type}`;
}
if (options.video) {
_meta.video = `${base}${pathToFolder(url, options)}video/${
index + 1
}.mp4`;
}
if (options.chrome && options.chrome.timeline) {
_meta.timeline = `${base}${pathToFolder(url, options)}trace-${
index + 1
}.json.gz`;
}
}
if (browserScript && browserScript.pageinfo) {
_meta.generator = browserScript.pageinfo.generator;
}
}
function jsonifyVisualProgress(visualProgress) {
// Original data looks like
// "0=0%, 1500=81%, 1516=81%, 1533=84%, 1550=84%, 1566=84%, 1600=95%, 1683=95%, 1833=100%"
const visualProgressJSON = {};
for (let value of visualProgress) {
visualProgressJSON[value.timestamp] = value.percent;
}
return visualProgressJSON;
}
export function addBrowser(har, name, version, comment) {
merge(har.log, {
browser: {
name,
version,
comment
}
});
if (!comment) {
delete har.log.browser.comment;
}
return har;
}
export function addCreator(har, comment) {
merge(har.log, {
creator: {
name: 'Browsertime',
version: version,
comment: comment
}
});
if (!comment) {
delete har.log.creator.comment;
}
return har;
}
export function getMainDocumentTimings(har) {
const timings = [];
const entries = [...har.log.entries];
for (let page of har.log.pages) {
const pageId = page.id;
const url = page._url;
let pageEntries = [...entries];
const finalURL = getFinalURL(pageEntries, pageId);
pageEntries = pageEntries.filter(
entry => entry.pageref === pageId && entry.request.url === finalURL
);
timings.push({ url, timings: pageEntries[0].timings });
}
return timings;
}
export function getFullyLoaded(har) {
const fullyLoaded = [];
const entries = [...har.log.entries];
for (let page of har.log.pages) {
const pageStartDateTime = new Date(page.startedDateTime).getTime();
const pageId = page.id;
const url = page._url;
let pageEntries = [...entries];
pageEntries = pageEntries.filter(entry => entry.pageref === pageId);
let pageEnd = 0;
for (let entry of pageEntries) {
let entryEnd =
new Date(entry.startedDateTime).getTime() +
entry.time -
new Date(pageStartDateTime).getTime();
if (entryEnd > pageEnd) {
pageEnd = entryEnd;
}
}
fullyLoaded.push({ url, fullyLoaded: Number(pageEnd.toFixed(0)) });
}
return fullyLoaded;
}
export function mergeHars(hars) {
if (isEmpty(hars)) {
return;
}
if (hars.length === 1) {
return hars[0];
}
let firstLog = hars[0].log;
let combinedHar = {
log: pick(firstLog, ['version', 'creator', 'browser', 'comment'])
};
let pagesById = new Map();
let allEntries = [];
for (const har of hars) {
let pages = har.log.pages;
let entries = har.log.entries;
for (const page of pages) {
let pageId = page.id;
if (pagesById.has(pageId)) {
const oldPageId = pageId;
pageId = generateUniquePageId(oldPageId, pagesById);
page.id = pageId;
entries = entries.map(entry => {
if (entry.pageref === oldPageId) {
entry.pageref = pageId;
}
return entry;
});
}
pagesById.set(pageId, page);
}
allEntries = [...allEntries, ...entries];
}
combinedHar.log.pages = [...pagesById.values()];
combinedHar.log.entries = allEntries;
return combinedHar;
}
export function getEmptyHAR(url, browser) {
return {
log: {
version: '1.2',
creator: {
name: 'Browsertime',
version: version,
comment: ''
},
browser: {
name: browser,
version: ''
},
pages: [
{
startedDateTime: dayjs().format(),
id: 'failing_page',
title: url,
pageTimings: {},
comment: ''
}
],
entries: [],
comment: ''
}
};
}
export function addExtraFieldsToHar(totalResults, har, options) {
if (har) {
let harPageNumber = 0;
// We test one page
// Let's do a better fix for this later on
// right now this fixes https://github.com/sitespeedio/browsertime/issues/754
if (har.log.pages.length === options.iterations) {
for (let harPage of har.log.pages) {
let pageNumber = harPageNumber % totalResults.length;
const visualMetric =
totalResults[pageNumber].visualMetrics[harPageNumber];
const browserScript =
totalResults[pageNumber].browserScripts[harPageNumber];
const cpu = totalResults[pageNumber].cpu[harPageNumber];
const googleWebVitals =
totalResults[pageNumber].googleWebVitals[harPageNumber];
addMetaToHAR(
harPageNumber,
harPage,
totalResults[pageNumber].info.url,
browserScript,
options
);
if (browserScript) {
addExtrasToHAR(
harPage,
visualMetric,
browserScript.timings,
cpu,
googleWebVitals
);
}
harPageNumber++;
}
} else {
const numberOfPages = totalResults.length;
for (let page = 0; page < numberOfPages; page++) {
for (let iteration = 0; iteration < options.iterations; iteration++) {
let harIndex = iteration * totalResults.length;
harIndex += page;
const visualMetric = totalResults[page].visualMetrics[iteration];
const browserScript = totalResults[page].browserScripts[iteration];
const cpu = totalResults[page].cpu[iteration];
const googleWebVitals = totalResults[page].googleWebVitals[iteration];
const harPage = har.log.pages[harIndex];
// Only add meta if we have a HAR
if (harPage) {
addMetaToHAR(
iteration,
harPage,
totalResults[page].info.url,
browserScript,
options
);
} else {
log.error(
'Could not add meta data to the HAR, miss page ' + harIndex
);
}
// Only add the metrics if we was able to collect the metrics and have a HAR
if (browserScript && harPage) {
addExtrasToHAR(
harPage,
visualMetric,
browserScript.timings,
cpu,
googleWebVitals
);
}
}
}
}
}
}