@uxfront/site-checks 0.1.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/html.js CHANGED
@@ -11,14 +11,14 @@ const NAMED = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'" };
11
11
  * @param {string} code
12
12
  */
13
13
  const numeric = (code) =>
14
- String.fromCodePoint(
15
- code[1]?.toLowerCase() === "x"
16
- ? Number.parseInt(code.slice(2), 16)
17
- : Number.parseInt(code.slice(1), 10),
18
- );
14
+ String.fromCodePoint(
15
+ code[1]?.toLowerCase() === "x"
16
+ ? Number.parseInt(code.slice(2), 16)
17
+ : Number.parseInt(code.slice(1), 10),
18
+ );
19
19
 
20
20
  /** @param {string} text */
21
- const escapeRegExp = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
21
+ const escapeRegExp = (text) => text.replaceAll(/[.*+?^${}()|[\]\\]/g, String.raw`\$&`);
22
22
 
23
23
  /**
24
24
  * A decoder for the profile's entities. `one-pass` decodes each reference once, so `&amp;lt;`
@@ -28,30 +28,32 @@ const escapeRegExp = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
28
28
  * @returns {(text: string) => string}
29
29
  */
30
30
  export function decoder({ decode: entities, decodeOrder, decodeIgnoreCase }) {
31
- const named = entities.filter((entity) => entity !== "numeric");
32
- const flags = decodeIgnoreCase ? "gi" : "g";
33
- const NUMERIC = "#[xX][\\da-fA-F]+|#\\d+";
34
- /** @param {string} code */
35
- const value = (code) =>
36
- code.startsWith("#") && entities.includes("numeric")
37
- ? numeric(code)
38
- : (NAMED[decodeIgnoreCase ? code.toLowerCase() : code] ??
39
- (code.startsWith("#") ? numeric(code) : `&${code};`));
40
- /** @param {string[]} alternatives */
41
- const replacer = (alternatives) => {
42
- if (!alternatives.length) return (/** @type {string} */ text) => text;
43
- const pattern = new RegExp(`&(${alternatives.join("|")});`, flags);
44
- return (/** @type {string} */ text) =>
45
- text.replace(pattern, (_, /** @type {string} */ code) => value(code));
46
- };
47
- const numerics = entities.includes("numeric") ? [NUMERIC] : [];
48
- const names = named.map(escapeRegExp);
49
- if (decodeOrder === "numeric-first") {
50
- const first = replacer(numerics);
51
- const second = replacer(names);
52
- return (text) => second(first(text));
53
- }
54
- return replacer([...numerics, ...names]);
31
+ const named = entities.filter((entity) => entity !== "numeric");
32
+ const flags = decodeIgnoreCase ? "gi" : "g";
33
+ const NUMERIC = String.raw`#[xX][\da-fA-F]+|#\d+`;
34
+ /** @param {string} code */
35
+ const value = (code) =>
36
+ code.startsWith("#") && entities.includes("numeric")
37
+ ? numeric(code)
38
+ : (NAMED[decodeIgnoreCase ? code.toLowerCase() : code] ??
39
+ (code.startsWith("#") ? numeric(code) : `&${code};`));
40
+ /** @param {string[]} alternatives */
41
+ const replacer = (alternatives) => {
42
+ if (!alternatives.length) {
43
+ return (/** @type {string} */ text) => text;
44
+ }
45
+ const pattern = new RegExp(`&(${alternatives.join("|")});`, flags);
46
+ return (/** @type {string} */ text) =>
47
+ text.replace(pattern, (_, /** @type {string} */ code) => value(code));
48
+ };
49
+ const numerics = entities.includes("numeric") ? [NUMERIC] : [];
50
+ const names = named.map(escapeRegExp);
51
+ if (decodeOrder === "numeric-first") {
52
+ const first = replacer(numerics);
53
+ const second = replacer(names);
54
+ return (text) => second(first(text));
55
+ }
56
+ return replacer([...numerics, ...names]);
55
57
  }
56
58
 
57
59
  /**
@@ -60,11 +62,17 @@ export function decoder({ decode: entities, decodeOrder, decodeIgnoreCase }) {
60
62
  * @param {Scope} scope
61
63
  */
62
64
  export function scoped(html, scope) {
63
- if (scope === "document") return html;
64
- if (scope === "markup") return html.replace(/<script\b[\s\S]*?<\/script>|<!--[\s\S]*?-->/gi, "");
65
- if (scope === "head-element") return html.match(/<head[\s>][\s\S]*?<\/head>/i)?.[0] ?? "";
66
- const end = html.indexOf("</head>");
67
- return end > 0 ? html.slice(0, end) : html;
65
+ if (scope === "document") {
66
+ return html;
67
+ }
68
+ if (scope === "markup") {
69
+ return html.replaceAll(/<script\b[\s\S]*?<\/script>|<!--[\s\S]*?-->/gi, "");
70
+ }
71
+ if (scope === "head-element") {
72
+ return html.match(/<head[\s>][\s\S]*?<\/head>/i)?.[0] ?? "";
73
+ }
74
+ const end = html.indexOf("</head>");
75
+ return end > 0 ? html.slice(0, end) : html;
68
76
  }
69
77
 
70
78
  // A tag's attributes, where a quoted value may hold a `>`, as in `content="<component is>"`.
@@ -77,9 +85,9 @@ const ATTRS = `(?:[^>"']|"[^"]*"|'[^']*')*`;
77
85
  * @param {string} [after] What follows the tag, like its body and end tag.
78
86
  */
79
87
  export function tagPattern(name, { quotes, caseSensitiveTags, tagEnd }, after = "") {
80
- const end = tagEnd === "word" ? "\\b" : "(?=[\\s/>])";
81
- const attributes = quotes === "double" ? "[^>]*" : ATTRS;
82
- return new RegExp(`<${name}${end}(${attributes})>${after}`, caseSensitiveTags ? "g" : "gi");
88
+ const end = tagEnd === "word" ? String.raw`\b` : String.raw`(?=[\s/>])`;
89
+ const attributes = quotes === "double" ? "[^>]*" : ATTRS;
90
+ return new RegExp(`<${name}${end}(${attributes})>${after}`, caseSensitiveTags ? "g" : "gi");
83
91
  }
84
92
 
85
93
  /**
@@ -90,20 +98,20 @@ export function tagPattern(name, { quotes, caseSensitiveTags, tagEnd }, after =
90
98
  * @param {(text: string) => string} decode
91
99
  */
92
100
  export function attributes(source, quotes, decode) {
93
- /** @type {Record<string, string>} */
94
- const found = {};
95
- if (quotes === "double") {
96
- for (const [, key = "", value = ""] of source.matchAll(/([\w:-]+)="([^"]*)"/g)) {
97
- found[key.toLowerCase()] = decode(value);
98
- }
99
- return found;
100
- }
101
- for (const [, key = "", double, single, bare] of source.matchAll(
102
- /([^\s=/>"']+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>"']+)))?/g,
103
- )) {
104
- found[key.toLowerCase()] = decode(double ?? single ?? bare ?? "");
105
- }
106
- return found;
101
+ /** @type {Record<string, string>} */
102
+ const found = {};
103
+ if (quotes === "double") {
104
+ for (const [, key = "", value = ""] of source.matchAll(/([\w:-]+)="([^"]*)"/g)) {
105
+ found[key.toLowerCase()] = decode(value);
106
+ }
107
+ return found;
108
+ }
109
+ for (const [, key = "", double, single, bare] of source.matchAll(
110
+ /([^\s=/>"']+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>"']+)))?/g,
111
+ )) {
112
+ found[key.toLowerCase()] = decode(double ?? single ?? bare ?? "");
113
+ }
114
+ return found;
107
115
  }
108
116
 
109
117
  /**
@@ -115,9 +123,9 @@ export function attributes(source, quotes, decode) {
115
123
  * @returns {Record<string, string>[]}
116
124
  */
117
125
  export function tags(html, name, profile, decode) {
118
- return [...html.matchAll(tagPattern(name, profile))].map(([, source = ""]) =>
119
- attributes(source, profile.quotes, decode),
120
- );
126
+ return [...html.matchAll(tagPattern(name, profile))].map(([, source = ""]) =>
127
+ attributes(source, profile.quotes, decode),
128
+ );
121
129
  }
122
130
 
123
131
  /**
@@ -127,15 +135,15 @@ export function tags(html, name, profile, decode) {
127
135
  * @param {Profile} profile
128
136
  */
129
137
  export function titleTexts(html, { titleTag, caseSensitiveTags }) {
130
- const source =
131
- titleTag === "any"
132
- ? "<title\\b[^>]*>([\\s\\S]*?)</title>"
133
- : titleTag === "plain-text"
134
- ? "<title[^>]*>([^<]*)</title>"
135
- : "<title>([^<]*)</title>";
136
- return [...html.matchAll(new RegExp(source, caseSensitiveTags ? "g" : "gi"))].map(
137
- ([, text = ""]) => text,
138
- );
138
+ const source =
139
+ titleTag === "any"
140
+ ? String.raw`<title\b[^>]*>([\s\S]*?)</title>`
141
+ : titleTag === "plain-text"
142
+ ? "<title[^>]*>([^<]*)</title>"
143
+ : "<title>([^<]*)</title>";
144
+ return [...html.matchAll(new RegExp(source, caseSensitiveTags ? "g" : "gi"))].map(
145
+ ([, text = ""]) => text,
146
+ );
139
147
  }
140
148
 
141
149
  /**
@@ -144,14 +152,14 @@ export function titleTexts(html, { titleTag, caseSensitiveTags }) {
144
152
  * @param {Pick<Profile, "h1" | "caseSensitiveTags">} profile
145
153
  */
146
154
  export function countH1(html, { h1: where, caseSensitiveTags }) {
147
- if (where === "markup") {
148
- return scoped(html, "markup").match(/<h1\b/gi)?.length ?? 0;
149
- }
150
- const text =
151
- where === "rendered"
152
- ? html.replace(/<(script|style|template)\b[\s\S]*?<\/\1>|<!--[\s\S]*?-->/gi, "")
153
- : html;
154
- return text.match(new RegExp("<h1[\\s>]", caseSensitiveTags ? "g" : "gi"))?.length ?? 0;
155
+ if (where === "markup") {
156
+ return scoped(html, "markup").match(/<h1\b/gi)?.length ?? 0;
157
+ }
158
+ const text =
159
+ where === "rendered"
160
+ ? html.replaceAll(/<(script|style|template)\b[\s\S]*?<\/\1>|<!--[\s\S]*?-->/gi, "")
161
+ : html;
162
+ return text.match(new RegExp(String.raw`<h1[\s>]`, caseSensitiveTags ? "g" : "gi"))?.length ?? 0;
155
163
  }
156
164
 
157
165
  /**
@@ -162,21 +170,26 @@ export function countH1(html, { h1: where, caseSensitiveTags }) {
162
170
  * @param {(text: string) => string} decode
163
171
  */
164
172
  export function jsonLdBodies(html, profile, decode) {
165
- if (profile.jsonLdType === "prefix-any-case") {
166
- return [
167
- ...html.matchAll(
168
- /<script\b[^>]*type=["']?application\/ld\+json["']?[^>]*>([\s\S]*?)<\/script>/gi,
169
- ),
170
- ].map(([, body = ""]) => body);
171
- }
172
- return [...html.matchAll(tagPattern("script", profile, "([\\s\\S]*?)</script>"))]
173
- .filter(
174
- ([, source = ""]) =>
175
- attributes(source, profile.quotes, decode).type === "application/ld+json",
176
- )
177
- .map(([, , body = ""]) => body);
173
+ if (profile.jsonLdType === "prefix-any-case") {
174
+ return [
175
+ ...html.matchAll(
176
+ /<script\b[^>]*type=["']?application\/ld\+json["']?[^>]*>([\s\S]*?)<\/script>/gi,
177
+ ),
178
+ ].map(([, body = ""]) => body);
179
+ }
180
+ return [...html.matchAll(tagPattern("script", profile, String.raw`([\s\S]*?)</script>`))].flatMap(
181
+ ([, source = "", body = ""]) =>
182
+ attributes(source, profile.quotes, decode).type === "application/ld+json" ? [body] : [],
183
+ );
178
184
  }
179
185
 
186
+ /**
187
+ * Whether a parsed JSON value is an object or an array, so its keys can be read.
188
+ * @param {unknown} value
189
+ * @returns {value is Record<string, unknown>}
190
+ */
191
+ export const isObject = (value) => Boolean(value) && typeof value === "object";
192
+
180
193
  /**
181
194
  * The nodes of the JSON-LD blocks of a page, as the profile reads them.
182
195
  * @param {unknown[]} blocks
@@ -184,30 +197,44 @@ export function jsonLdBodies(html, profile, decode) {
184
197
  * @returns {Record<string, unknown>[]}
185
198
  */
186
199
  export function jsonLdNodes(blocks, mode) {
187
- /** @param {unknown} value @returns {value is Record<string, unknown>} */
188
- const isObject = (value) => Boolean(value) && typeof value === "object";
189
- /** @param {unknown} value @returns {Record<string, unknown>[]} */
190
- const all = (value) => {
191
- if (Array.isArray(value)) return value.flatMap(all);
192
- if (!isObject(value)) return [];
193
- const graph = value["@graph"];
194
- return [value, ...(Array.isArray(graph) ? graph.flatMap(all) : [])];
195
- };
196
- /** @param {unknown} value @returns {Record<string, unknown>[]} */
197
- const deep = (value) => {
198
- if (Array.isArray(value)) return value.flatMap(deep);
199
- if (!isObject(value)) return [];
200
- return value["@graph"] ? deep(value["@graph"]) : [value];
201
- };
202
- return blocks.flatMap((block) => {
203
- if (mode === "all") return all(block);
204
- if (mode === "graph-deep") return deep(block);
205
- if (!isObject(block)) return [];
206
- const graph = block["@graph"];
207
- const members = Array.isArray(graph) ? graph.filter(isObject) : [];
208
- if (mode === "block-and-graph") return [block, ...members];
209
- return Array.isArray(graph) ? members : [block];
210
- });
200
+ /** @param {unknown} value @returns {Record<string, unknown>[]} */
201
+ const all = (value) => {
202
+ if (Array.isArray(value)) {
203
+ return value.flatMap(all);
204
+ }
205
+ if (!isObject(value)) {
206
+ return [];
207
+ }
208
+ const graph = value["@graph"];
209
+ return [value, ...(Array.isArray(graph) ? graph.flatMap(all) : [])];
210
+ };
211
+ /** @param {unknown} value @returns {Record<string, unknown>[]} */
212
+ const deep = (value) => {
213
+ if (Array.isArray(value)) {
214
+ return value.flatMap(deep);
215
+ }
216
+ if (!isObject(value)) {
217
+ return [];
218
+ }
219
+ return value["@graph"] ? deep(value["@graph"]) : [value];
220
+ };
221
+ return blocks.flatMap((block) => {
222
+ if (mode === "all") {
223
+ return all(block);
224
+ }
225
+ if (mode === "graph-deep") {
226
+ return deep(block);
227
+ }
228
+ if (!isObject(block)) {
229
+ return [];
230
+ }
231
+ const graph = block["@graph"];
232
+ const members = Array.isArray(graph) ? graph.filter(isObject) : [];
233
+ if (mode === "block-and-graph") {
234
+ return [block, ...members];
235
+ }
236
+ return Array.isArray(graph) ? members : [block];
237
+ });
211
238
  }
212
239
 
213
240
  /**
@@ -217,7 +244,7 @@ export function jsonLdNodes(blocks, mode) {
217
244
  * @param {boolean} typeArrays
218
245
  */
219
246
  export const isType = (node, type, typeArrays) =>
220
- typeArrays ? [node["@type"]].flat().includes(type) : node["@type"] === type;
247
+ typeArrays ? [node["@type"]].flat().includes(type) : node["@type"] === type;
221
248
 
222
249
  /**
223
250
  * The width, height and type of a PNG or JPEG, from its header. With `name`, a PNG is any file
@@ -227,33 +254,35 @@ export const isType = (node, type, typeArrays) =>
227
254
  * @returns {{ type: "png" | "jpeg", width: number, height: number } | undefined}
228
255
  */
229
256
  export function imageSize(bytes, png = "signature") {
230
- const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
231
- const SIGNATURE = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a];
232
- const isPng =
233
- png === "name"
234
- ? bytes[1] === 0x50 && bytes[2] === 0x4e && bytes[3] === 0x47
235
- : SIGNATURE.every((byte, index) => bytes[index] === byte);
236
- if (isPng) {
237
- return bytes.length >= 24
238
- ? { type: "png", width: view.getUint32(16), height: view.getUint32(20) }
239
- : undefined;
240
- }
241
- if (bytes[0] === 0xff && bytes[1] === 0xd8) {
242
- for (let offset = 2; offset + 9 < bytes.length;) {
243
- if (bytes[offset] !== 0xff) break;
244
- const marker = bytes[offset + 1] ?? 0;
245
- // Start-of-frame markers hold the size. C4, C8 and CC are other segments.
246
- if (marker >= 0xc0 && marker <= 0xcf && ![0xc4, 0xc8, 0xcc].includes(marker)) {
247
- return {
248
- type: "jpeg",
249
- height: view.getUint16(offset + 5),
250
- width: view.getUint16(offset + 7),
251
- };
252
- }
253
- offset += 2 + view.getUint16(offset + 2);
254
- }
255
- }
256
- return undefined;
257
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
258
+ const SIGNATURE = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a];
259
+ const isPng =
260
+ png === "name"
261
+ ? bytes[1] === 0x50 && bytes[2] === 0x4e && bytes[3] === 0x47
262
+ : SIGNATURE.every((byte, index) => bytes[index] === byte);
263
+ if (isPng) {
264
+ return bytes.length >= 24
265
+ ? { type: "png", width: view.getUint32(16), height: view.getUint32(20) }
266
+ : undefined;
267
+ }
268
+ if (bytes[0] === 0xff && bytes[1] === 0xd8) {
269
+ for (let offset = 2; offset + 9 < bytes.length;) {
270
+ if (bytes[offset] !== 0xff) {
271
+ break;
272
+ }
273
+ const marker = bytes[offset + 1] ?? 0;
274
+ // Start-of-frame markers hold the size. C4, C8 and CC are other segments.
275
+ if (marker >= 0xc0 && marker <= 0xcf && ![0xc4, 0xc8, 0xcc].includes(marker)) {
276
+ return {
277
+ type: "jpeg",
278
+ height: view.getUint16(offset + 5),
279
+ width: view.getUint16(offset + 7),
280
+ };
281
+ }
282
+ offset += 2 + view.getUint16(offset + 2);
283
+ }
284
+ }
285
+ return undefined;
257
286
  }
258
287
 
259
288
  export { escapeRegExp };