@uxfront/site-checks 0.0.0 → 0.1.0

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/site.js ADDED
@@ -0,0 +1,568 @@
1
+ import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
2
+ import { join, sep } from "node:path";
3
+
4
+ import {
5
+ countH1,
6
+ decoder,
7
+ escapeRegExp,
8
+ jsonLdBodies,
9
+ jsonLdNodes,
10
+ scoped,
11
+ tags,
12
+ titleTexts,
13
+ } from "./html.js";
14
+
15
+ /** @import { CheckedPage, IndexSource, ParseProfile, PathPattern, Scope, SitemapEntry } from "../index.js" */
16
+
17
+ /** @typedef {Required<ParseProfile>} Profile */
18
+ /** @typedef {"lookup" | "exact" | "exact-slash"} PathMode */
19
+ /** @typedef {{ pattern: string, headers: [name: string, value: string][] }} HeaderRule */
20
+
21
+ /**
22
+ * A `<url>` of the sitemap, with its parsed URL when the `<loc>` is one, and the reason its
23
+ * `<loc>` couldn't be decoded, if it couldn't.
24
+ * @typedef {SitemapEntry & { url: URL | undefined, hasLoc: boolean, error?: string }} Entry
25
+ */
26
+
27
+ /**
28
+ * A sitemap page or a path in `pages`, read lazily.
29
+ * @implements {CheckedPage}
30
+ */
31
+ export class Page {
32
+ /** @type {Map<string, unknown>} */
33
+ #cache = new Map();
34
+
35
+ /**
36
+ * @param {{ loc: string, path: string, file: string, html: string, profile: Profile, decode: (text: string) => string }} input
37
+ */
38
+ constructor({ loc, path, file, html, profile, decode }) {
39
+ this.loc = loc;
40
+ this.path = path;
41
+ this.file = file;
42
+ this.html = html;
43
+ this.profile = profile;
44
+ this.decode = decode;
45
+ }
46
+
47
+ /**
48
+ * @template T
49
+ * @param {string} key
50
+ * @param {() => T} read
51
+ * @returns {T}
52
+ */
53
+ #once(key, read) {
54
+ if (!this.#cache.has(key)) this.#cache.set(key, read());
55
+ return /** @type {T} */ (this.#cache.get(key));
56
+ }
57
+
58
+ /** Every tag of this name in a scope, the profile's by default. @param {string} name @param {Scope} [scope] */
59
+ tags(name, scope = this.profile.scope) {
60
+ return this.#once(`tags:${scope}:${name}`, () =>
61
+ tags(scoped(this.html, scope), name, this.profile, this.decode),
62
+ );
63
+ }
64
+
65
+ /** Every tag of this name in the whole document. @param {string} name */
66
+ documentTags(name) {
67
+ return this.tags(name, "document");
68
+ }
69
+
70
+ /** A value as the profile reads it, trimmed when `trimValues` says so. @param {string} value */
71
+ #value(value) {
72
+ return this.profile.trimValues ? value.trim() : value;
73
+ }
74
+
75
+ /**
76
+ * The `content` of every `<meta>` whose key is `key`. With `property-first`, a tag's key is its
77
+ * `property`, or else its `name`, and a tag with no `content` is left out.
78
+ * @param {string} key
79
+ * @param {Scope} [scope]
80
+ */
81
+ meta(key, scope) {
82
+ const metas = this.tags("meta", scope);
83
+ const found =
84
+ this.profile.metaKey === "property-first"
85
+ ? metas.filter((tag) => (tag.property ?? tag.name) === key && tag.content !== undefined)
86
+ : metas.filter((tag) => tag.name === key || tag.property === key);
87
+ return found.map((tag) => this.#value(tag.content ?? ""));
88
+ }
89
+
90
+ /** The first value of a `<meta>`, or `undefined`. @param {string} key */
91
+ first(key) {
92
+ return this.meta(key)[0];
93
+ }
94
+
95
+ /** Whether a `<meta>` is set, to something other than spaces. @param {string} key */
96
+ has(key) {
97
+ return Boolean(this.first(key)?.trim());
98
+ }
99
+
100
+ get titles() {
101
+ return this.#once("titles", () => {
102
+ const { titleScope, trimTitle } = this.profile;
103
+ return titleTexts(scoped(this.html, titleScope), this.profile).map((title) =>
104
+ trimTitle === "none"
105
+ ? this.decode(title)
106
+ : trimTitle === "before-decode"
107
+ ? this.decode(title.trim())
108
+ : this.decode(title).trim(),
109
+ );
110
+ });
111
+ }
112
+
113
+ get lang() {
114
+ const lang = this.documentTags("html")[0]?.lang;
115
+ return lang === undefined ? undefined : this.#value(lang);
116
+ }
117
+
118
+ get h1() {
119
+ return this.#once("h1", () => countH1(this.html, this.profile));
120
+ }
121
+
122
+ /**
123
+ * The `href` of each canonical link: `exact` takes `rel="canonical"`, `exact-any-case` the same
124
+ * in any case, and `token` a `rel` with `canonical` among its words. With `requireHref`, a link
125
+ * with no `href` doesn't count.
126
+ * @param {"token" | "exact" | "exact-any-case"} rel
127
+ * @param {boolean} [requireHref]
128
+ */
129
+ canonicals(rel, requireHref = false) {
130
+ return this.tags("link")
131
+ .filter((tag) =>
132
+ rel === "token"
133
+ ? (tag.rel ?? "").toLowerCase().split(/\s+/).includes("canonical")
134
+ : rel === "exact-any-case"
135
+ ? tag.rel?.toLowerCase() === "canonical"
136
+ : tag.rel === "canonical",
137
+ )
138
+ .filter((tag) => !requireHref || tag.href !== undefined)
139
+ .map((tag) => tag.href ?? "");
140
+ }
141
+
142
+ /** Each JSON-LD block, parsed, or the reason it doesn't parse. */
143
+ get blocks() {
144
+ return this.#once("blocks", () =>
145
+ jsonLdBodies(this.html, this.profile, this.decode).map((body) => {
146
+ try {
147
+ return { ok: true, value: /** @type {unknown} */ (JSON.parse(body)) };
148
+ } catch (error) {
149
+ return { ok: false, error: error instanceof Error ? error.message : String(error) };
150
+ }
151
+ }),
152
+ );
153
+ }
154
+
155
+ get nodes() {
156
+ return this.#once("nodes", () =>
157
+ jsonLdNodes(
158
+ this.blocks.flatMap((block) => (block.ok ? [block.value] : [])),
159
+ this.profile.nodes,
160
+ ),
161
+ );
162
+ }
163
+ }
164
+
165
+ /**
166
+ * Whether a path is in a set of patterns: `*`, a prefix ending in `*`, or an exact path.
167
+ * @param {string} path
168
+ * @param {readonly PathPattern[]} patterns
169
+ */
170
+ export const inScope = (path, patterns) =>
171
+ patterns.some((pattern) =>
172
+ pattern.endsWith("*") ? path.startsWith(pattern.slice(0, -1)) : path === pattern,
173
+ );
174
+
175
+ /**
176
+ * Everything the rules read about a built site, each file read once.
177
+ */
178
+ export class Site {
179
+ /** @type {Map<string, string | undefined>} */
180
+ #files = new Map();
181
+ /** @type {string[] | undefined} */
182
+ #html;
183
+
184
+ /**
185
+ * @param {{ site: string, dist: string, profile: Profile, paths: PathMode, now: Date }} input
186
+ */
187
+ constructor({ site, dist, profile, paths, now }) {
188
+ this.site = site.replace(/\/+$/, "");
189
+ this.host = new URL(this.site).host;
190
+ this.dist = dist;
191
+ this.profile = profile;
192
+ this.paths = paths;
193
+ this.now = now;
194
+ this.decode = decoder(profile);
195
+ }
196
+
197
+ /** A file in `dist` as text, or `undefined`. @param {string} file */
198
+ read(file) {
199
+ if (!this.#files.has(file)) {
200
+ const path = join(this.dist, file);
201
+ let text;
202
+ try {
203
+ text = statSync(path).isFile() ? readFileSync(path, "utf8") : undefined;
204
+ } catch {
205
+ text = undefined;
206
+ }
207
+ this.#files.set(file, text);
208
+ }
209
+ return this.#files.get(file);
210
+ }
211
+
212
+ /** @param {string} file */
213
+ exists(file) {
214
+ return existsSync(join(this.dist, file));
215
+ }
216
+
217
+ /** The length of a text in the profile's units. @param {string} text */
218
+ length(text) {
219
+ if (this.profile.count === "utf-16") return text.length;
220
+ // A surrogate pair is one code point in two UTF-16 units.
221
+ return text.length - (text.match(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g)?.length ?? 0);
222
+ }
223
+
224
+ /** Every HTML file in `dist`, with `/` between folders, in order. */
225
+ get htmlFiles() {
226
+ this.#html ??= readdirSync(this.dist, { recursive: true, encoding: "utf8" })
227
+ .map((file) => file.split(sep).join("/"))
228
+ .filter((file) => file.endsWith(".html") && isFile(join(this.dist, file)))
229
+ .toSorted();
230
+ return this.#html;
231
+ }
232
+
233
+ /** The path a file is served at, as the `paths` mode says. @param {string} file */
234
+ served(file) {
235
+ if (this.paths === "exact-slash") {
236
+ if (file === "index.html") return "/";
237
+ if (file.endsWith("/index.html")) return `/${file.slice(0, -"index.html".length)}`;
238
+ return `/${file.slice(0, -".html".length)}`;
239
+ }
240
+ return `/${file}`.replace(/(?:\/index)?\.html$/, "") || "/";
241
+ }
242
+
243
+ get #byPath() {
244
+ /** @type {Map<string, string>} */
245
+ const map = new Map();
246
+ for (const file of this.htmlFiles) {
247
+ const path = this.served(file);
248
+ // A `.html` file wins over a folder's `index.html` at the same path.
249
+ if (!map.has(path) || !file.endsWith("/index.html")) map.set(path, file);
250
+ }
251
+ return map;
252
+ }
253
+
254
+ /** @type {Map<string, string> | undefined} */
255
+ #paths;
256
+
257
+ /** The file a site path is served from, or `undefined`. @param {string} path */
258
+ resolve(path) {
259
+ if (this.paths === "lookup") {
260
+ const trimmed = path.replace(/^\/+|\/+$/g, "");
261
+ const file = !trimmed
262
+ ? "index.html"
263
+ : path.endsWith("/") || this.read(`${trimmed}.html`) === undefined
264
+ ? `${trimmed}/index.html`
265
+ : `${trimmed}.html`;
266
+ return this.read(file) === undefined ? undefined : file;
267
+ }
268
+ this.#paths ??= this.#byPath;
269
+ return this.#paths.get(path);
270
+ }
271
+
272
+ /** @type {{ exists: boolean, entries: Entry[] } | undefined} */
273
+ #sitemap;
274
+
275
+ get sitemap() {
276
+ if (!this.#sitemap) {
277
+ const xml = this.read("sitemap.xml");
278
+ /** @param {string | undefined} text */
279
+ const trim = (text) => (this.profile.trimSitemap ? text?.trim() : text);
280
+ const entries = [...(xml ?? "").matchAll(/<url>([\s\S]*?)<\/url>/g)].map(([, body = ""]) => {
281
+ const raw = body.match(/<loc>([^<]*)<\/loc>/)?.[1];
282
+ let loc = trim(raw) ?? "";
283
+ let error;
284
+ try {
285
+ loc = this.decode(loc);
286
+ } catch (thrown) {
287
+ error = thrown instanceof Error ? thrown.message : String(thrown);
288
+ }
289
+ let url;
290
+ try {
291
+ url = loc ? new URL(loc) : undefined;
292
+ } catch {
293
+ url = undefined;
294
+ }
295
+ return {
296
+ loc,
297
+ lastmod: trim(body.match(/<lastmod>([^<]*)<\/lastmod>/)?.[1]),
298
+ url,
299
+ hasLoc: raw !== undefined && Boolean(loc),
300
+ ...(error === undefined ? {} : { error }),
301
+ };
302
+ });
303
+ this.#sitemap = { exists: xml !== undefined, entries };
304
+ }
305
+ return this.#sitemap;
306
+ }
307
+
308
+ /** The decoded `<loc>` values. */
309
+ get locs() {
310
+ return new Set(this.sitemap.entries.map((entry) => entry.loc));
311
+ }
312
+
313
+ /**
314
+ * A page read through the profile.
315
+ * @param {string} loc @param {string} path @param {string} file
316
+ */
317
+ page(loc, path, file) {
318
+ return new Page({
319
+ loc,
320
+ path,
321
+ file,
322
+ html: this.read(file) ?? "",
323
+ profile: this.profile,
324
+ decode: this.decode,
325
+ });
326
+ }
327
+
328
+ /** @type {HeaderRule[] | undefined} */
329
+ #headers;
330
+
331
+ /** The rules of `_headers`, each a pattern and its headers, with lower-case names. */
332
+ get headers() {
333
+ if (!this.#headers) {
334
+ const text = this.read("_headers") ?? "";
335
+ /** @type {HeaderRule[]} */
336
+ const rules = [];
337
+ if (this.profile.headersParser === "blocks") {
338
+ // A rule is everything from one unindented line to the next, trimmed. A `#` line is a
339
+ // rule of its own, and a line that still ends in `\r` doesn't read as a header.
340
+ for (const block of text.split(/\n(?=\S)/)) {
341
+ const [pattern = "", ...lines] = block.trim().split("\n");
342
+ rules.push({
343
+ pattern,
344
+ headers: lines.flatMap((line) => {
345
+ const [, name, value = ""] = line.match(/^\s+([^:]+):\s*(.*)$/) ?? [];
346
+ return name ? [/** @type {[string, string]} */ ([name.toLowerCase(), value])] : [];
347
+ }),
348
+ });
349
+ }
350
+ this.#headers = rules;
351
+ return rules;
352
+ }
353
+ for (const line of text.split("\n")) {
354
+ if (!line.trim() || line.trim().startsWith("#")) continue;
355
+ if (!/^\s/.test(line)) {
356
+ rules.push({ pattern: line.trim(), headers: [] });
357
+ continue;
358
+ }
359
+ const at = line.indexOf(":");
360
+ if (at > 0 && line.slice(0, at).trim()) {
361
+ rules
362
+ .at(-1)
363
+ ?.headers.push([line.slice(0, at).trim().toLowerCase(), line.slice(at + 1).trim()]);
364
+ }
365
+ }
366
+ this.#headers = rules;
367
+ }
368
+ return this.#headers;
369
+ }
370
+
371
+ /**
372
+ * The headers `_headers` gives a URL, as Cloudflare matches it: a rule's pattern is a path, or
373
+ * a URL with a host, where `*` matches anything and a `:placeholder` anything but `.` in a host
374
+ * or `/` in a path. A request gets the headers of every rule it matches.
375
+ * @param {string} url
376
+ * @returns {[name: string, value: string][]}
377
+ */
378
+ headersFor(url) {
379
+ let host, pathname;
380
+ try {
381
+ ({ host, pathname } = new URL(url, this.site));
382
+ } catch {
383
+ return [];
384
+ }
385
+ return this.headers.flatMap(({ pattern, headers }) => {
386
+ const match = cloudflarePattern(pattern).exec(
387
+ pattern.startsWith("https://") ? `${host}${pathname}` : pathname,
388
+ );
389
+ if (!match) return [];
390
+ /** @param {string} value */
391
+ const fill = (value) =>
392
+ value.replace(
393
+ /:([A-Za-z]\w*)/g,
394
+ (placeholder, /** @type {string} */ name) => match.groups?.[name] ?? placeholder,
395
+ );
396
+ return headers.map(([name, value]) => /** @type {[string, string]} */ ([name, fill(value)]));
397
+ });
398
+ }
399
+
400
+ /** The sources of `_redirects` rules. */
401
+ get redirected() {
402
+ return new Set(
403
+ (this.read("_redirects") ?? "")
404
+ .split("\n")
405
+ .map((line) => line.trim().split(/\s+/)[0] ?? "")
406
+ .filter((source) => source && !source.startsWith("#")),
407
+ );
408
+ }
409
+
410
+ /**
411
+ * The first source that takes a page out of the index, or `undefined`.
412
+ * @param {readonly IndexSource[]} sources
413
+ * @param {{ file: string, path: string, host: string }} at
414
+ */
415
+ outOfIndex(sources, { file, path, host }) {
416
+ for (const source of sources) {
417
+ const found = this.#outBy(source, file, path, host);
418
+ if (found) return found;
419
+ }
420
+ return undefined;
421
+ }
422
+
423
+ /**
424
+ * @param {IndexSource} source @param {string} file @param {string} path @param {string} host
425
+ * @returns {string | undefined}
426
+ */
427
+ #outBy(source, file, path, host) {
428
+ switch (source.type) {
429
+ case "files":
430
+ return source.files.includes(file) ? `it's ${file}` : undefined;
431
+ case "under": {
432
+ const folder = source.paths.find((prefix) => file.startsWith(prefix));
433
+ return folder ? `it's under ${folder}` : undefined;
434
+ }
435
+ case "redirects":
436
+ return this.redirected.has(path) ? "_redirects sends it elsewhere" : undefined;
437
+ case "refresh": {
438
+ const page = this.page("", path, file);
439
+ return page
440
+ .documentTags("meta")
441
+ .some((tag) => tag["http-equiv"]?.toLowerCase() === "refresh")
442
+ ? "it's a meta refresh"
443
+ : undefined;
444
+ }
445
+ case "meta": {
446
+ const page = this.page("", path, file);
447
+ const test = valueTest(source.values, source.word, source.caseSensitive);
448
+ const scope = source.scope ?? this.profile.scope;
449
+ // With `property`, a tag is found as the profile finds any `<meta>`, by its `name` or its
450
+ // `property`. Without, by its `name` alone.
451
+ const contents = source.property
452
+ ? source.names.flatMap((name) => page.meta(name, scope))
453
+ : page
454
+ .tags("meta", scope)
455
+ .filter((meta) => {
456
+ const name = source.anyCaseNames ? meta.name?.toLowerCase() : meta.name;
457
+ return name !== undefined && source.names.includes(name);
458
+ })
459
+ .map((meta) => meta.content ?? "");
460
+ const hit = contents.find((content) => test(content));
461
+ return hit === undefined ? undefined : `a robots <meta> says "${hit}"`;
462
+ }
463
+ case "headers": {
464
+ const test = valueTest(source.values, source.word, false);
465
+ for (const { pattern, headers } of this.headers) {
466
+ // Host rules end in `/*` and would match every path, so `ignore` reads path rules alone.
467
+ if (source.hosts === "ignore" && !pattern.startsWith("/")) continue;
468
+ const target =
469
+ source.hosts === "match" && pattern.startsWith("https://") ? `${host}${path}` : path;
470
+ const regexp =
471
+ source.hosts === "drop" ? droppedHostPattern(pattern) : cloudflarePattern(pattern);
472
+ if (!regexp.test(target)) continue;
473
+ const values = headers
474
+ .filter(([name]) => name === "x-robots-tag")
475
+ .map(([, value]) => value);
476
+ // A parser that keeps one value per header name keeps the last.
477
+ const read = source.hosts === "drop" ? values.slice(-1) : values;
478
+ const tag = read.find((value) => test(value));
479
+ if (tag !== undefined) return `_headers ${pattern} sends X-Robots-Tag: ${tag}`;
480
+ }
481
+ return undefined;
482
+ }
483
+ }
484
+ return undefined;
485
+ }
486
+ }
487
+
488
+ /**
489
+ * @param {readonly string[] | undefined} values
490
+ * @param {boolean | undefined} word
491
+ * @param {boolean | undefined} caseSensitive
492
+ */
493
+ function valueTest(values = ["noindex"], word = false, caseSensitive = false) {
494
+ const alternatives = values.map(escapeRegExp).join("|");
495
+ const regexp = new RegExp(
496
+ word ? `\\b(?:${alternatives})\\b` : alternatives,
497
+ caseSensitive ? "" : "i",
498
+ );
499
+ return (/** @type {string} */ value) => regexp.test(value);
500
+ }
501
+
502
+ /** @type {Map<string, RegExp>} */
503
+ const patterns = new Map();
504
+
505
+ /**
506
+ * A `_headers` pattern as Cloudflare matches it: `https://host/path` against `host/path`, a path
507
+ * against the path. `*` is a splat, and `:name` a placeholder that stops at `.` in a host or `/`.
508
+ * @param {string} pattern
509
+ */
510
+ function cloudflarePattern(pattern) {
511
+ let regexp = patterns.get(pattern);
512
+ if (!regexp) {
513
+ /** @param {string} text @param {string} delimiters */
514
+ const segment = (text, delimiters) =>
515
+ text
516
+ .split(/(\*|:[A-Za-z]\w*)/)
517
+ .map((part, index) =>
518
+ part === "*"
519
+ ? "(?<splat>.*)"
520
+ : index % 2
521
+ ? `(?<${part.slice(1)}>[^${delimiters}]+)`
522
+ : escapeRegExp(part),
523
+ )
524
+ .join("");
525
+ const [, host, path] = pattern.match(/^https:\/\/([^/]+)(\/.*)$/) ?? [];
526
+ let source;
527
+ try {
528
+ source =
529
+ host !== undefined && path !== undefined
530
+ ? `^${segment(host, "./")}${segment(path, "/")}$`
531
+ : `^${segment(pattern, "/")}$`;
532
+ regexp = new RegExp(source);
533
+ } catch {
534
+ // Two placeholders with one name can't both be groups: match them without names.
535
+ regexp = new RegExp(
536
+ `^${pattern
537
+ .replace(/^https:\/\//, "")
538
+ .split(/(\*|:[A-Za-z]\w*)/)
539
+ .map((part, index) => (part === "*" ? ".*" : index % 2 ? "[^/]+" : escapeRegExp(part)))
540
+ .join("")}$`,
541
+ );
542
+ }
543
+ patterns.set(pattern, regexp);
544
+ }
545
+ return regexp;
546
+ }
547
+
548
+ /**
549
+ * A `_headers` pattern with its host dropped, matched against the path alone.
550
+ * @param {string} pattern
551
+ */
552
+ function droppedHostPattern(pattern) {
553
+ const source = pattern
554
+ .replace(/^https?:\/\/[^/]+/, "")
555
+ .replace(/[.+?^${}()|[\]\\]/g, "\\$&")
556
+ .replace(/\*/g, ".*")
557
+ .replace(/:\w+/g, "[^/]+");
558
+ return new RegExp(`^${source}$`);
559
+ }
560
+
561
+ /** Whether a path is a file, and not a folder or a link to nothing. @param {string} path */
562
+ export function isFile(path) {
563
+ try {
564
+ return statSync(path).isFile();
565
+ } catch {
566
+ return false;
567
+ }
568
+ }