forked from GoogleChrome/lighthouse
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlink-elements.js
194 lines (168 loc) · 5.89 KB
/
link-elements.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
/**
* @license
* Copyright 2018 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import LinkHeader from 'http-link-header';
import BaseGatherer from '../base-gatherer.js';
import {pageFunctions} from '../../lib/page-functions.js';
import DevtoolsLog from './devtools-log.js';
import {MainResource} from '../../computed/main-resource.js';
import {Util} from '../../../shared/util.js';
import * as i18n from '../../lib/i18n/i18n.js';
/* globals HTMLLinkElement getNodeDetails */
/**
* @fileoverview
* This gatherer collects all the effect `link` elements, both in the page and declared in the
* headers of the main resource.
*/
const UIStrings = {
/**
* @description Warning message explaining that there was an error parsing a link header in an HTTP response. `error` will be an english string with more details on the error. `header` will be the value of the header that caused the error. `link` is a type of HTTP header and should not be translated.
* @example {Expected attribute delimiter at offset 94} error
* @example {<https://assets.calendly.com/assets/booking/css/booking-d0ac32b1.css>; rel=preload; as=style; nopush} error
*/
headerParseWarning: 'Error parsing `link` header ({error}): `{header}`',
};
const str_ = i18n.createIcuMessageFn(import.meta.url, UIStrings);
/**
*
* @param {string} url
* @param {string} finalDisplayedUrl
* @return {string|null}
*/
function normalizeUrlOrNull(url, finalDisplayedUrl) {
try {
return new URL(url, finalDisplayedUrl).href;
} catch (_) {
return null;
}
}
/**
* @param {string|undefined} value
* @return {LH.Artifacts.LinkElement['crossOrigin']}
*/
function getCrossoriginFromHeader(value) {
if (value === 'anonymous') return 'anonymous';
if (value === 'use-credentials') return 'use-credentials';
return null;
}
/**
* @return {LH.Artifacts['LinkElements']}
*/
/* c8 ignore start */
function getLinkElementsInDOM() {
/** @type {Array<HTMLOrSVGElement>} */
// @ts-expect-error - getElementsInDocument put into scope via stringification
const browserElements = getElementsInDocument('link'); // eslint-disable-line no-undef
/** @type {LH.Artifacts['LinkElements']} */
const linkElements = [];
for (const link of browserElements) {
// We're only interested in actual LinkElements, not `<link>` tagName elements inside SVGs.
// https://github.com/GoogleChrome/lighthouse/issues/9764
if (!(link instanceof HTMLLinkElement)) continue;
const hrefRaw = link.getAttribute('href') || '';
const source = link.closest('head') ? 'head' : 'body';
linkElements.push({
rel: link.rel,
href: link.href,
hreflang: link.hreflang,
as: link.as,
crossOrigin: link.crossOrigin,
hrefRaw,
source,
fetchPriority: link.fetchPriority,
// @ts-expect-error - put into scope via stringification
node: getNodeDetails(link),
});
}
return linkElements;
}
/* c8 ignore stop */
class LinkElements extends BaseGatherer {
constructor() {
super();
/**
* This needs to be in the constructor.
* https://github.com/GoogleChrome/lighthouse/issues/12134
* @type {LH.Gatherer.GathererMeta<'DevtoolsLog'>}
*/
this.meta = {
supportedModes: ['timespan', 'navigation'],
dependencies: {DevtoolsLog: DevtoolsLog.symbol},
};
}
/**
* @param {LH.Gatherer.Context} context
* @return {Promise<LH.Artifacts['LinkElements']>}
*/
static getLinkElementsInDOM(context) {
// We'll use evaluateAsync because the `node.getAttribute` method doesn't actually normalize
// the values like access from JavaScript does.
return context.driver.executionContext.evaluate(getLinkElementsInDOM, {
args: [],
useIsolation: true,
deps: [
pageFunctions.getNodeDetails,
pageFunctions.getElementsInDocument,
],
});
}
/**
* @param {LH.Gatherer.Context} context
* @param {LH.Artifacts['DevtoolsLog']} devtoolsLog
* @return {Promise<LH.Artifacts['LinkElements']>}
*/
static async getLinkElementsInHeaders(context, devtoolsLog) {
const mainDocument =
await MainResource.request({devtoolsLog, URL: context.baseArtifacts.URL}, context);
/** @type {LH.Artifacts['LinkElements']} */
const linkElements = [];
for (const header of mainDocument.responseHeaders) {
if (header.name.toLowerCase() !== 'link') continue;
/** @type {LinkHeader.Reference[]} */
let parsedRefs = [];
try {
parsedRefs = LinkHeader.parse(header.value).refs;
} catch (err) {
const truncatedHeader = Util.truncate(header.value, 100);
const warning = str_(UIStrings.headerParseWarning, {
error: err.message,
header: truncatedHeader,
});
context.baseArtifacts.LighthouseRunWarnings.push(warning);
}
for (const link of parsedRefs) {
linkElements.push({
rel: link.rel || '',
href: normalizeUrlOrNull(link.uri, context.baseArtifacts.URL.finalDisplayedUrl),
hrefRaw: link.uri || '',
hreflang: link.hreflang || '',
as: link.as || '',
crossOrigin: getCrossoriginFromHeader(link.crossorigin),
source: 'headers',
fetchPriority: link.fetchpriority,
node: null,
});
}
}
return linkElements;
}
/**
* @param {LH.Gatherer.Context<'DevtoolsLog'>} context
* @return {Promise<LH.Artifacts['LinkElements']>}
*/
async getArtifact(context) {
const devtoolsLog = context.dependencies.DevtoolsLog;
const fromDOM = await LinkElements.getLinkElementsInDOM(context);
const fromHeaders = await LinkElements.getLinkElementsInHeaders(context, devtoolsLog);
const linkElements = fromDOM.concat(fromHeaders);
for (const link of linkElements) {
// Normalize the rel for easy consumption/filtering
link.rel = link.rel.toLowerCase();
}
return linkElements;
}
}
export default LinkElements;
export {UIStrings};