@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/rules.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { readFileSync, readdirSync } from "node:fs";
2
2
  import { join, sep } from "node:path";
3
3
 
4
- import { escapeRegExp, imageSize, isType } from "./html.js";
4
+ import { escapeRegExp, imageSize, isObject, isType } from "./html.js";
5
5
  import { inScope, isFile } from "./site.js";
6
6
  import { bool, count, list, oneOf, pattern, source, text, typesByPath, url } from "./validate.js";
7
7
 
@@ -28,35 +28,35 @@ import { bool, count, list, oneOf, pattern, source, text, typesByPath, url } fro
28
28
 
29
29
  /** The crawlers that read pages for AI search and assistants, each allowed by name. */
30
30
  export const AI_CRAWLERS = Object.freeze([
31
- "OAI-SearchBot",
32
- "ChatGPT-User",
33
- "PerplexityBot",
34
- "Claude-SearchBot",
35
- "Claude-User",
36
- "GPTBot",
37
- "ClaudeBot",
38
- "Google-Extended",
39
- "CCBot",
31
+ "OAI-SearchBot",
32
+ "ChatGPT-User",
33
+ "PerplexityBot",
34
+ "Claude-SearchBot",
35
+ "Claude-User",
36
+ "GPTBot",
37
+ "ClaudeBot",
38
+ "Google-Extended",
39
+ "CCBot",
40
40
  ]);
41
41
 
42
42
  /** The directives Lighthouse's robots.txt audit knows. Any other fails it. */
43
43
  const ROBOTS_DIRECTIVES = new Set([
44
- "user-agent",
45
- "disallow",
46
- "allow",
47
- "sitemap",
48
- "crawl-delay",
49
- "clean-param",
50
- "host",
51
- "request-rate",
52
- "visit-time",
53
- "noindex",
44
+ "user-agent",
45
+ "disallow",
46
+ "allow",
47
+ "sitemap",
48
+ "crawl-delay",
49
+ "clean-param",
50
+ "host",
51
+ "request-rate",
52
+ "visit-time",
53
+ "noindex",
54
54
  ]);
55
55
 
56
56
  const LASTMOD_FORMATS = {
57
- loose: /^\d{4}-\d{2}-\d{2}(T[\d:.]+(Z|[+-]\d{2}:\d{2}))?$/,
58
- date: /^\d{4}-\d{2}-\d{2}$/,
59
- w3c: /^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2}))?$/,
57
+ loose: /^\d{4}-\d{2}-\d{2}(T[\d:.]+(Z|[+-]\d{2}:\d{2}))?$/,
58
+ date: /^\d{4}-\d{2}-\d{2}$/,
59
+ w3c: /^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2}))?$/,
60
60
  };
61
61
 
62
62
  /** @param {string} value */
@@ -64,13 +64,13 @@ const dateOnly = (value) => /^\d{4}-\d{2}-\d{2}$/.test(value);
64
64
 
65
65
  /** Whether a `YYYY-MM-DD` value is a day on the calendar, not February 30 or month 13. @param {string} value */
66
66
  function isCalendarDay(value) {
67
- const time = Date.parse(`${value}T00:00:00Z`);
68
- return !Number.isNaN(time) && new Date(time).toISOString().slice(0, 10) === value;
67
+ const time = Date.parse(`${value}T00:00:00Z`);
68
+ return !Number.isNaN(time) && new Date(time).toISOString().slice(0, 10) === value;
69
69
  }
70
70
 
71
71
  /** The time a `<lastmod>` stands for, or `NaN`. @param {string} value */
72
72
  const lastmodTime = (value) =>
73
- dateOnly(value) ? Date.parse(`${value}T00:00:00Z`) : Date.parse(value);
73
+ dateOnly(value) ? Date.parse(`${value}T00:00:00Z`) : Date.parse(value);
74
74
 
75
75
  /**
76
76
  * Whether a line is blank: with `whitespace`, when it holds only spaces, and with `empty`, only when
@@ -88,11 +88,11 @@ const field = (node, key) => node[key];
88
88
  * @returns {{ path: string, url: URL, loc: string }[]}
89
89
  */
90
90
  const listed = ({ site }) =>
91
- site.sitemap.entries.flatMap(({ loc, url }) => (url ? [{ loc, url, path: url.pathname }] : []));
91
+ site.sitemap.entries.flatMap(({ loc, url }) => (url ? [{ loc, url, path: url.pathname }] : []));
92
92
 
93
93
  /** The `<lastmod>` of a `<loc>`: the last one, when the `<loc>` is listed twice. @param {Site} site @param {string} loc */
94
94
  const lastmodOf = (site, loc) =>
95
- site.sitemap.entries.findLast((entry) => entry.loc === loc)?.lastmod;
95
+ site.sitemap.entries.findLast((entry) => entry.loc === loc)?.lastmod;
96
96
 
97
97
  /**
98
98
  * The groups of a robots.txt, each a run of `User-agent` lines and the rules after them. A new
@@ -103,50 +103,59 @@ const lastmodOf = (site, loc) =>
103
103
  * @param {"all" | "directives" | "allow-disallow"} [groupRules]
104
104
  */
105
105
  function robotsGroups(text, groupRules = "all") {
106
- /** @type {{ agents: string[], rules: { field: string, value: string }[] }[]} */
107
- const groups = [];
108
- /** @type {{ field: string, value: string }[]} */
109
- const lines = [];
110
- for (const raw of text.split("\n")) {
111
- const line = raw.replace(/#.*/, "").trim();
112
- const at = line.indexOf(":");
113
- if (at < 0) continue;
114
- const name = line.slice(0, at).trim().toLowerCase();
115
- const value = line.slice(at + 1).trim();
116
- lines.push({ field: name, value });
117
- if (groupRules === "directives" && !/^[\w-]+$/.test(name)) continue;
118
- if (name === "user-agent") {
119
- const last = groups.at(-1);
120
- if (!last || last.rules.length) groups.push({ agents: [value], rules: [] });
121
- else last.agents.push(value);
122
- } else if (name !== "sitemap") {
123
- if (groupRules === "allow-disallow" && name !== "allow" && name !== "disallow") continue;
124
- groups.at(-1)?.rules.push({ field: name, value });
125
- }
126
- }
127
- return { groups, lines };
106
+ /** @type {{ agents: string[], rules: { field: string, value: string }[] }[]} */
107
+ const groups = [];
108
+ /** @type {{ field: string, value: string }[]} */
109
+ const lines = [];
110
+ for (const raw of text.split("\n")) {
111
+ const line = raw.replace(/#.*/, "").trim();
112
+ const at = line.indexOf(":");
113
+ if (at < 0) {
114
+ continue;
115
+ }
116
+ const name = line.slice(0, at).trim().toLowerCase();
117
+ const value = line.slice(at + 1).trim();
118
+ lines.push({ field: name, value });
119
+ if (groupRules === "directives" && !/^[\w-]+$/.test(name)) {
120
+ continue;
121
+ }
122
+ if (name === "user-agent") {
123
+ const last = groups.at(-1);
124
+ if (!last || last.rules.length) {
125
+ groups.push({ agents: [value], rules: [] });
126
+ } else {
127
+ last.agents.push(value);
128
+ }
129
+ } else if (name !== "sitemap") {
130
+ if (groupRules === "allow-disallow" && name !== "allow" && name !== "disallow") {
131
+ continue;
132
+ }
133
+ groups.at(-1)?.rules.push({ field: name, value });
134
+ }
135
+ }
136
+ return { groups, lines };
128
137
  }
129
138
 
130
139
  /** @param {{ field: string, value: string }[]} rules @param {string} name @param {string} value */
131
140
  const hasRule = (rules, name, value) =>
132
- rules.some((entry) => entry.field === name && entry.value === value);
141
+ rules.some((entry) => entry.field === name && entry.value === value);
133
142
 
134
143
  /** Every file in `dist`, with `/` between folders. @param {string} dist */
135
144
  function allFiles(dist) {
136
- return readdirSync(dist, { recursive: true, encoding: "utf8" })
137
- .map((file) => file.split(sep).join("/"))
138
- .filter((file) => isFile(join(dist, file)))
139
- .toSorted();
145
+ return readdirSync(dist, { recursive: true, encoding: "utf8" })
146
+ .map((file) => file.split(sep).join("/"))
147
+ .filter((file) => isFile(join(dist, file)))
148
+ .toSorted();
140
149
  }
141
150
 
142
151
  /** A file pattern, where `**` matches any folders and `*` anything but `/`. @param {string} glob */
143
152
  const globRegExp = (glob) =>
144
- new RegExp(
145
- `^${glob
146
- .split(/(\*\*\/|\*)/)
147
- .map((part) => (part === "**/" ? "(?:.*/)?" : part === "*" ? "[^/]*" : escapeRegExp(part)))
148
- .join("")}$`,
149
- );
153
+ new RegExp(
154
+ `^${glob
155
+ .split(/(\*\*\/|\*)/)
156
+ .map((part) => (part === "**/" ? "(?:.*/)?" : part === "*" ? "[^/]*" : escapeRegExp(part)))
157
+ .join("")}$`,
158
+ );
150
159
 
151
160
  /**
152
161
  * @template {RuleId} Id
@@ -156,927 +165,1062 @@ const globRegExp = (glob) =>
156
165
  const rule = (definition) => definition;
157
166
 
158
167
  export const RULES = [
159
- rule({
160
- id: "sitemap",
161
- core: true,
162
- defaults: {},
163
- run({ site, report }) {
164
- const { exists, entries } = site.sitemap;
165
- if (!exists) return report("sitemap.xml", "missing");
166
- if (!entries.length) report("sitemap.xml", "no <url>");
167
- for (const entry of entries) {
168
- if (entry.error) report("sitemap.xml", `${entry.loc} can't be decoded: ${entry.error}`);
169
- else if (!entry.hasLoc) report("sitemap.xml", "a <url> has no <loc>");
170
- }
171
- },
172
- }),
173
- rule({
174
- id: "sitemap-host",
175
- core: true,
176
- defaults: {},
177
- run({ site, report }) {
178
- for (const { loc, hasLoc } of site.sitemap.entries) {
179
- if (hasLoc && !loc.startsWith(`${site.site}/`)) {
180
- report("sitemap.xml", `${loc} isn't on ${site.site}`);
181
- }
182
- }
183
- },
184
- }),
185
- rule({
186
- id: "sitemap-duplicates",
187
- core: false,
188
- defaults: {},
189
- run({ site, report }) {
190
- const seen = new Set();
191
- for (const { loc, hasLoc } of site.sitemap.entries) {
192
- if (hasLoc && seen.has(loc)) report("sitemap.xml", `${loc} is listed twice`);
193
- seen.add(loc);
194
- }
195
- },
196
- }),
197
- rule({
198
- id: "lastmod",
199
- core: true,
200
- defaults: { format: "loose", realDate: "none" },
201
- run({ site, report }, { format, realDate }) {
202
- for (const { loc, lastmod } of site.sitemap.entries) {
203
- if (!lastmod) report("sitemap.xml", `${loc} has no <lastmod>`);
204
- else if (!LASTMOD_FORMATS[format].test(lastmod)) {
205
- report("sitemap.xml", `${loc} has a <lastmod> that isn't a ${format} date: ${lastmod}`);
206
- } else if (
207
- (realDate === "date-only" &&
208
- (dateOnly(lastmod) ? !isCalendarDay(lastmod) : Number.isNaN(Date.parse(lastmod)))) ||
209
- (realDate === "parseable" && Number.isNaN(Date.parse(lastmod)))
210
- ) {
211
- report("sitemap.xml", `${loc} has a <lastmod> that isn't a real date: ${lastmod}`);
212
- }
213
- }
214
- },
215
- }),
216
- rule({
217
- id: "lastmod-future",
218
- core: false,
219
- defaults: { skewHours: 0 },
220
- run({ site, report }, { skewHours }) {
221
- const latest = site.now.getTime() + skewHours * 60 * 60 * 1000;
222
- for (const { loc, lastmod } of site.sitemap.entries) {
223
- if (lastmod && lastmodTime(lastmod) > latest) {
224
- report("sitemap.xml", `${loc} has a <lastmod> in the future: ${lastmod}`);
225
- }
226
- }
227
- },
228
- }),
229
- rule({
230
- id: "sitemap-pages",
231
- core: true,
232
- defaults: { paths: "exact", notFoundCopy: false },
233
- run({ site, report }, { notFoundCopy }) {
234
- const notFound = site.read("404.html");
235
- for (const { loc, url, hasLoc } of site.sitemap.entries) {
236
- if (!hasLoc) continue;
237
- if (!url) {
238
- report("sitemap.xml", `${loc} isn't a URL`);
239
- continue;
240
- }
241
- const file = site.resolve(url.pathname);
242
- if (!file) report(url.pathname, `no HTML file in dist is served at ${loc}`);
243
- else if (notFoundCopy && notFound !== undefined && site.read(file) === notFound) {
244
- report(url.pathname, `${file} is the 404 page`);
245
- }
246
- }
247
- },
248
- }),
249
- rule({
250
- id: "sitemap-indexable",
251
- core: true,
252
- defaults: { sources: [{ type: "meta", names: ["robots", "googlebot"] }] },
253
- run(context, { sources }) {
254
- for (const { path, url } of listed(context)) {
255
- const file = context.site.resolve(path);
256
- if (!file) continue;
257
- const why = context.site.outOfIndex(sources, { file, path, host: url.host });
258
- if (why) context.report(path, `it's in the sitemap, but out of the index: ${why}`);
259
- }
260
- },
261
- }),
262
- rule({
263
- id: "sitemap-coverage",
264
- core: false,
265
- defaults: { exclude: /** @type {readonly IndexSource[]} */ ([]) },
266
- run({ site, report }, { exclude }) {
267
- const locs = site.locs;
268
- for (const file of site.htmlFiles) {
269
- const path = site.served(file);
270
- if (site.outOfIndex(exclude, { file, path, host: site.host })) continue;
271
- if (!locs.has(`${site.site}${path}`)) report(path, `${file} isn't in the sitemap`);
272
- }
273
- },
274
- }),
275
- rule({
276
- id: "title",
277
- core: true,
278
- defaults: { max: 60, exactlyOne: false, nonEmpty: true },
279
- run({ site, pages, report }, { max, exactlyOne, nonEmpty }) {
280
- for (const page of pages) {
281
- const { titles } = page;
282
- if (exactlyOne && titles.length !== 1) {
283
- report(page.path, `${titles.length} <title> elements, not exactly one`);
284
- continue;
285
- }
286
- const title = titles[0] ?? "";
287
- if (nonEmpty && !title) report(page.path, "no <title>");
288
- else if (site.length(title) > max) {
289
- report(page.path, `<title> is ${site.length(title)} characters, over ${max}: "${title}"`);
290
- }
291
- }
292
- },
293
- }),
294
- rule({
295
- id: "title-unique",
296
- core: true,
297
- defaults: {},
298
- run({ pages, report }) {
299
- const seen = new Map();
300
- for (const page of pages) {
301
- const title = page.titles[0];
302
- if (!title) continue;
303
- if (seen.has(title)) report(page.path, `<title> is the same as ${seen.get(title)}'s`);
304
- else seen.set(title, page.path);
305
- }
306
- },
307
- }),
308
- rule({
309
- id: "description",
310
- core: true,
311
- defaults: { min: 70, max: 160, exactlyOne: false },
312
- run({ site, pages, report }, { min, max, exactlyOne }) {
313
- for (const page of pages) {
314
- const values = page.meta("description");
315
- if (exactlyOne && values.length !== 1) {
316
- report(page.path, `${values.length} meta descriptions, not exactly one`);
317
- continue;
318
- }
319
- const description = values[0] ?? "";
320
- const length = site.length(description);
321
- if (!exactlyOne && !description) report(page.path, "no meta description");
322
- else if (length < min || length > max) {
323
- report(page.path, `meta description is ${length} characters, outside ${min} to ${max}`);
324
- }
325
- }
326
- },
327
- }),
328
- rule({
329
- id: "description-unique",
330
- core: true,
331
- defaults: {},
332
- run({ pages, report }) {
333
- const seen = new Map();
334
- for (const page of pages) {
335
- const description = page.meta("description")[0];
336
- if (!description) continue;
337
- if (seen.has(description)) {
338
- report(page.path, `meta description is the same as ${seen.get(description)}'s`);
339
- } else seen.set(description, page.path);
340
- }
341
- },
342
- }),
343
- rule({
344
- id: "h1",
345
- core: true,
346
- defaults: {},
347
- run({ pages, report }) {
348
- for (const page of pages) {
349
- if (page.h1 !== 1) report(page.path, `${page.h1} <h1> elements, not exactly one`);
350
- }
351
- },
352
- }),
353
- rule({
354
- id: "canonical",
355
- core: true,
356
- defaults: { exactlyOne: true, rel: "exact", requireHref: false },
357
- run({ pages, report }, { exactlyOne, rel, requireHref }) {
358
- for (const page of pages) {
359
- const hrefs = page.canonicals(rel, requireHref);
360
- if (exactlyOne && hrefs.length !== 1) {
361
- report(page.path, `${hrefs.length} canonical links, not exactly one`);
362
- } else if (!hrefs[0]) report(page.path, "no canonical link");
363
- else if (hrefs[0] !== page.loc) {
364
- report(page.path, `canonical link ${hrefs[0]} isn't its URL, ${page.loc}`);
365
- }
366
- }
367
- },
368
- }),
369
- rule({
370
- id: "lang",
371
- core: true,
372
- defaults: { lang: "en" },
373
- run({ pages, report }, { lang }) {
374
- for (const page of pages) {
375
- if (lang === false ? !page.lang : page.lang !== lang) {
376
- report(page.path, `<html lang="${page.lang ?? ""}">, needs ${lang || "a language"}`);
377
- }
378
- }
379
- },
380
- }),
381
- rule({
382
- id: "open-graph",
383
- core: true,
384
- defaults: { url: "loc" },
385
- run({ pages, report, optionsOf }, { url }) {
386
- const { rel, requireHref } = optionsOf("canonical");
387
- for (const page of pages) {
388
- for (const key of ["og:title", "og:description", "og:type", "og:image", "og:url"]) {
389
- if (!page.has(key)) report(page.path, `no ${key}`);
390
- }
391
- const ogUrl = page.first("og:url");
392
- const expected = url === "loc" ? page.loc : page.canonicals(rel, requireHref)[0];
393
- if (ogUrl?.trim() && ogUrl !== expected) {
394
- report(
395
- page.path,
396
- `og:url ${ogUrl} isn't the ${url === "loc" ? "page's URL" : "canonical link"}`,
397
- );
398
- }
399
- }
400
- },
401
- }),
402
- rule({
403
- id: "og-image-alt",
404
- core: false,
405
- defaults: {},
406
- run({ pages, report }) {
407
- for (const page of pages) if (!page.has("og:image:alt")) report(page.path, "no og:image:alt");
408
- },
409
- }),
410
- rule({
411
- id: "meta-conflicts",
412
- core: false,
413
- defaults: {
414
- keys: [
415
- "og:title",
416
- "og:description",
417
- "og:url",
418
- "og:type",
419
- "og:image",
420
- "og:image:alt",
421
- "twitter:title",
422
- "twitter:description",
423
- "twitter:image",
424
- ],
425
- },
426
- run({ pages, report }, { keys }) {
427
- for (const page of pages) {
428
- for (const key of keys) {
429
- const values = new Set(page.meta(key));
430
- if (values.size > 1) report(page.path, `${values.size} different values of ${key}`);
431
- }
432
- }
433
- },
434
- }),
435
- rule({
436
- id: "og-image-host",
437
- core: true,
438
- defaults: {},
439
- run({ site, pages, report }) {
440
- for (const page of pages) {
441
- const image = page.first("og:image");
442
- if (image?.trim() && !image.startsWith(`${site.site}/`)) {
443
- report(page.path, `og:image ${image} isn't on ${site.site}`);
444
- }
445
- }
446
- },
447
- }),
448
- rule({
449
- id: "og-image-size-tags",
450
- core: false,
451
- defaults: { onHostOnly: false },
452
- run({ site, pages, report }, { onHostOnly }) {
453
- for (const page of pages) {
454
- if (onHostOnly && !page.first("og:image")?.startsWith(`${site.site}/`)) continue;
455
- const width = page.first("og:image:width");
456
- const height = page.first("og:image:height");
457
- if (width !== "1200") report(page.path, `og:image:width is ${width ?? "(none)"}, not 1200`);
458
- if (height !== "630")
459
- report(page.path, `og:image:height is ${height ?? "(none)"}, not 630`);
460
- }
461
- },
462
- }),
463
- rule({
464
- id: "og-image-file",
465
- core: true,
466
- defaults: { types: ["png", "jpeg"], png: "name" },
467
- run({ site, pages, report }, { types, png }) {
468
- for (const page of pages) {
469
- const image = page.first("og:image");
470
- if (!image?.startsWith(`${site.site}/`)) continue;
471
- let pathname = "";
472
- try {
473
- pathname = new URL(image).pathname;
474
- } catch {
475
- // Reported as off the site, if anywhere.
476
- }
477
- let decoded = pathname;
478
- try {
479
- decoded = decodeURIComponent(pathname);
480
- } catch {
481
- // Keep the path as it is.
482
- }
483
- const file = [decoded, pathname]
484
- .map((path) => join(site.dist, path))
485
- .find((path) => isFile(path));
486
- if (!file) {
487
- report(page.path, `og:image ${image} isn't in dist`);
488
- continue;
489
- }
490
- const size = imageSize(readFileSync(file), png);
491
- if (!size || !types.includes(size.type)) {
492
- report(page.path, `og:image ${image} isn't a ${types.join(" or ").toUpperCase()}`);
493
- } else if (size.width !== 1200 || size.height !== 630) {
494
- report(page.path, `og:image ${image} is ${size.width} × ${size.height}, not 1200 × 630`);
495
- }
496
- }
497
- },
498
- }),
499
- rule({
500
- id: "twitter",
501
- core: true,
502
- defaults: { card: "summary_large_image" },
503
- run({ pages, report }, { card }) {
504
- for (const page of pages) {
505
- const value = page.first("twitter:card");
506
- if (card === "any" ? !page.has("twitter:card") : value !== card) {
507
- report(page.path, `twitter:card is ${value || "(none)"}`);
508
- }
509
- if (!page.has("twitter:image")) report(page.path, "no twitter:image");
510
- }
511
- },
512
- }),
513
- rule({
514
- id: "twitter-text",
515
- core: false,
516
- defaults: {},
517
- run({ pages, report }) {
518
- for (const page of pages) {
519
- for (const key of ["twitter:title", "twitter:description"]) {
520
- if (!page.has(key)) report(page.path, `no ${key}`);
521
- }
522
- }
523
- },
524
- }),
525
- rule({
526
- id: "json-ld-parse",
527
- core: true,
528
- defaults: {},
529
- run({ pages, report }) {
530
- for (const page of pages) {
531
- for (const [index, block] of page.blocks.entries()) {
532
- if (!block.ok)
533
- report(page.path, `JSON-LD block ${index + 1} doesn't parse: ${block.error}`);
534
- }
535
- }
536
- },
537
- }),
538
- rule({
539
- id: "json-ld-present",
540
- core: false,
541
- defaults: {},
542
- run({ pages, report }) {
543
- for (const page of pages) if (!page.blocks.length) report(page.path, "no JSON-LD");
544
- },
545
- }),
546
- rule({
547
- id: "json-ld-context",
548
- core: false,
549
- defaults: {},
550
- run({ pages, report }) {
551
- for (const page of pages) {
552
- for (const block of page.blocks) {
553
- if (!block.ok) continue;
554
- const context =
555
- block.value && typeof block.value === "object"
556
- ? /** @type {Record<string, unknown>} */ (block.value)["@context"]
557
- : undefined;
558
- if (context !== "https://schema.org") {
559
- report(page.path, "a JSON-LD block's @context isn't https://schema.org");
560
- }
561
- }
562
- }
563
- },
564
- }),
565
- rule({
566
- id: "json-ld-ids",
567
- core: false,
568
- defaults: {},
569
- run({ pages, report }) {
570
- for (const page of pages) {
571
- const ids = new Set();
572
- for (const node of page.nodes) {
573
- const id = node["@id"];
574
- if (typeof id !== "string") continue;
575
- if (ids.has(id)) report(page.path, `two JSON-LD nodes with the @id ${id}`);
576
- ids.add(id);
577
- }
578
- }
579
- },
580
- }),
581
- rule({
582
- id: "json-ld-types",
583
- core: false,
584
- defaults: {
585
- types: {
586
- "/": ["WebSite", "SoftwareSourceCode", "Organization"],
587
- "/docs/*": ["TechArticle", "BreadcrumbList"],
588
- },
589
- },
590
- run({ site, pages, report }, { types }) {
591
- for (const page of pages) {
592
- for (const [pattern, required] of Object.entries(types)) {
593
- if (!inScope(page.path, [pattern])) continue;
594
- for (const type of required) {
595
- if (!page.nodes.some((node) => isType(node, type, site.profile.typeArrays))) {
596
- report(page.path, `no ${type} in the JSON-LD`);
597
- }
598
- }
599
- }
600
- }
601
- },
602
- }),
603
- rule({
604
- id: "json-ld-breadcrumbs",
605
- core: false,
606
- defaults: {
607
- scope: ["/docs/*"],
608
- nodes: "first",
609
- item: ["url"],
610
- exactType: false,
611
- nonArray: "skip",
612
- },
613
- run({ site, pages, report }, { scope, nodes, item: forms, exactType, nonArray }) {
614
- const locs = site.locs;
615
- for (const page of pages) {
616
- if (!inScope(page.path, scope)) continue;
617
- const lists = page.nodes.filter((node) =>
618
- isType(node, "BreadcrumbList", !exactType && site.profile.typeArrays),
619
- );
620
- for (const breadcrumbs of nodes === "first" ? lists.slice(0, 1) : lists) {
621
- const items = field(breadcrumbs, "itemListElement");
622
- // With `iterate`, a value that isn't a list is read as one, and one that can't be read
623
- // as one fails the rule, as a checker that loops over it does.
624
- const entries =
625
- nonArray === "iterate"
626
- ? [.../** @type {Iterable<unknown>} */ (items ?? [])]
627
- : Array.isArray(items)
628
- ? items
629
- : [];
630
- for (const entry of entries) {
631
- const item = entry && typeof entry === "object" ? entry.item : undefined;
632
- const target =
633
- typeof item === "string"
634
- ? forms.includes("url")
635
- ? item
636
- : undefined
637
- : forms.includes("id") && item && typeof item === "object"
638
- ? /** @type {Record<string, unknown>} */ (item)["@id"]
639
- : undefined;
640
- if (typeof target !== "string" || !locs.has(target)) {
641
- report(
642
- page.path,
643
- `a breadcrumb links ${typeof target === "string" ? target : (JSON.stringify(target) ?? "nothing")}, which isn't in the sitemap`,
644
- );
645
- }
646
- }
647
- }
648
- }
649
- },
650
- }),
651
- rule({
652
- id: "json-ld-article",
653
- core: false,
654
- defaults: { scope: ["/docs/*"] },
655
- run({ site, pages, report }, { scope }) {
656
- for (const page of pages) {
657
- if (!inScope(page.path, scope)) continue;
658
- const article = page.nodes.find((node) =>
659
- isType(node, "TechArticle", site.profile.typeArrays),
660
- );
661
- if (!article) continue;
662
- const lastmod = lastmodOf(site, page.loc);
663
- if (lastmod && article.dateModified !== lastmod) {
664
- report(
665
- page.path,
666
- `the TechArticle's dateModified ${String(article.dateModified)} isn't the sitemap's ${lastmod}`,
667
- );
668
- }
669
- const image = page.first("og:image");
670
- if (image && article.image !== image) {
671
- report(page.path, `the TechArticle's image isn't the og:image, ${image}`);
672
- }
673
- }
674
- },
675
- }),
676
- rule({
677
- id: "json-ld-posting",
678
- core: false,
679
- defaults: { scope: ["/blog/*"] },
680
- run({ site, pages, report }, { scope }) {
681
- const { typeArrays } = site.profile;
682
- for (const page of pages) {
683
- if (!inScope(page.path, scope)) continue;
684
- const postings = page.nodes.filter((node) => isType(node, "BlogPosting", typeArrays));
685
- if (postings.length !== 1)
686
- report(page.path, `${postings.length} BlogPosting nodes, not one`);
687
- for (const posting of postings) {
688
- const missing = ["headline", "description", "datePublished", "image", "url"].filter(
689
- (key) => !posting[key],
690
- );
691
- const author = posting.author;
692
- if (
693
- !author ||
694
- typeof author !== "object" ||
695
- !field(/** @type {Record<string, unknown>} */ (author), "name")
696
- ) {
697
- missing.push("author.name");
698
- }
699
- if (missing.length) report(page.path, `a BlogPosting without ${missing.join(", ")}`);
700
- }
701
- if (page.nodes.some((node) => isType(node, "Article", typeArrays))) {
702
- report(page.path, "an Article node beside the BlogPosting");
703
- }
704
- }
705
- },
706
- }),
707
- rule({
708
- id: "json-ld-organization",
709
- core: false,
710
- defaults: { name: "", scope: ["*"] },
711
- run({ site, pages, report }, { name, scope }) {
712
- for (const page of pages) {
713
- if (!inScope(page.path, scope)) continue;
714
- const named = page.nodes.some(
715
- (node) => isType(node, "Organization", site.profile.typeArrays) && node.name === name,
716
- );
717
- if (named) report(page.path, `an Organization named ${name}, which isn't an organisation`);
718
- }
719
- },
720
- }),
721
- rule({
722
- id: "robots-sitemap",
723
- core: true,
724
- defaults: { match: "exact" },
725
- run({ site, report }, { match }) {
726
- const text = site.read("robots.txt");
727
- if (text === undefined) return report("robots.txt", "missing");
728
- const url = `${site.site}/sitemap.xml`;
729
- const line = `Sitemap: ${url}`;
730
- const found =
731
- match === "loose"
732
- ? new RegExp(`^Sitemap:\\s*${escapeRegExp(url)}\\s*$`, "im").test(text)
733
- : match === "trimmed"
734
- ? text
735
- .split("\n")
736
- .map((raw) => raw.replace(/#.*/, "").trim())
737
- .includes(line)
738
- : match === "exact"
739
- ? text.split("\n").includes(line)
740
- : match === "anchored"
741
- ? new RegExp(`^${escapeRegExp(line)}$`, "m").test(text)
742
- : robotsGroups(text).lines.some(
743
- (entry) => entry.field === "sitemap" && entry.value === url,
744
- );
745
- if (!found) report("robots.txt", `no "${line}" line`);
746
- },
747
- }),
748
- rule({
749
- id: "robots-crawlers",
750
- core: false,
751
- defaults: {
752
- crawlers: AI_CRAWLERS,
753
- allow: false,
754
- case: "exact",
755
- agents: "groups",
756
- groupRules: "all",
757
- },
758
- run({ site, report }, { crawlers, allow, case: letterCase, agents, groupRules }) {
759
- const text = site.read("robots.txt");
760
- if (text === undefined) return;
761
- // With `lines`, every `User-agent` line counts, read as it is, comments and all.
762
- const groups =
763
- agents === "lines"
764
- ? [...text.matchAll(/^user-agent:\s*(.+?)\s*$/gim)].map(([, agent = ""]) => ({
765
- agents: [agent],
766
- rules: /** @type {{ field: string, value: string }[]} */ ([]),
767
- }))
768
- : robotsGroups(text, groupRules).groups;
769
- /** @param {string} agent */
770
- const key = (agent) => (letterCase === "insensitive" ? agent.toLowerCase() : agent);
771
- for (const crawler of crawlers) {
772
- const own = groups.filter((group) =>
773
- group.agents.some((agent) => key(agent) === key(crawler)),
774
- );
775
- if (!own.length) {
776
- report("robots.txt", `no group for User-agent: ${crawler}`);
777
- continue;
778
- }
779
- const checked = allow === "first" ? own.slice(0, 1) : own;
780
- if (
781
- allow &&
782
- (!checked.some((group) => hasRule(group.rules, "allow", "/")) ||
783
- checked.some((group) => hasRule(group.rules, "disallow", "/")))
784
- ) {
785
- report("robots.txt", `User-agent: ${crawler} isn't allowed everywhere`);
786
- }
787
- }
788
- },
789
- }),
790
- rule({
791
- id: "robots-no-disallow",
792
- core: false,
793
- defaults: { match: "lines" },
794
- run({ site, report }, { match }) {
795
- const text = site.read("robots.txt");
796
- if (text === undefined) return;
797
- const found =
798
- match === "lines"
799
- ? /^disallow:\s*\/\s*$/im.test(text)
800
- : robotsGroups(text).groups.some((group) => hasRule(group.rules, "disallow", "/"));
801
- if (found) report("robots.txt", '"Disallow: /" blocks crawlers from the site');
802
- },
803
- }),
804
- rule({
805
- id: "robots-wildcard",
806
- core: false,
807
- defaults: {},
808
- run({ site, report }) {
809
- const text = site.read("robots.txt");
810
- if (text === undefined) return;
811
- const wildcards = [...text.matchAll(/^user-agent:\s*(.+?)\s*$/gim)].filter(
812
- ([, agent]) => agent === "*",
813
- ).length;
814
- if (wildcards !== 1) report("robots.txt", `${wildcards} "User-agent: *" lines, not one`);
815
- },
816
- }),
817
- rule({
818
- id: "robots-directives",
819
- core: false,
820
- defaults: {},
821
- run({ site, report }) {
822
- const text = site.read("robots.txt");
823
- if (text === undefined) return;
824
- for (const raw of text.split("\n")) {
825
- const line = raw.replace(/#.*/, "").trim();
826
- const name = line.match(/^([\w-]+):\s*(.*)$/)?.[1];
827
- if (name && !ROBOTS_DIRECTIVES.has(name.toLowerCase())) {
828
- report("robots.txt", `"${line}": Lighthouse doesn't know ${name}`);
829
- }
830
- }
831
- },
832
- }),
833
- rule({
834
- id: "llms",
835
- core: true,
836
- defaults: { first: "non-empty", title: "", nonEmpty: false },
837
- run({ site, report }, { first, title, nonEmpty }) {
838
- const text = site.read("llms.txt");
839
- if (text === undefined) return report("llms.txt", "missing");
840
- const line =
841
- first === "line"
842
- ? text.split("\n")[0]
843
- : text.split("\n").find((entry) => !isBlank(entry, site.profile.blankLines));
844
- const ok = title
845
- ? first === "line"
846
- ? text.startsWith(`# ${title}\n`)
847
- : line === `# ${title}`
848
- : nonEmpty
849
- ? /^# \S/.test(line ?? "")
850
- : Boolean(line?.startsWith("# "));
851
- if (!ok) report("llms.txt", `doesn't start with "# ${title || "<title>"}"`);
852
- },
853
- }),
854
- rule({
855
- id: "llms-summary",
856
- core: true,
857
- defaults: { position: "second", nonEmpty: false },
858
- run({ site, report }, { position, nonEmpty }) {
859
- const text = site.read("llms.txt");
860
- if (text === undefined) return;
861
- const lines = text.split("\n").filter((line) => !isBlank(line, site.profile.blankLines));
862
- /** @param {string | undefined} line */
863
- const summary = (line) =>
864
- nonEmpty ? /^> \S/.test(line ?? "") : Boolean(line?.startsWith("> "));
865
- const found = position === "second" ? summary(lines[1]) : lines.some(summary);
866
- if (!found)
867
- report(
868
- "llms.txt",
869
- `no "> " summary line${position === "second" ? " under the heading" : ""}`,
870
- );
871
- },
872
- }),
873
- rule({
874
- id: "llms-links",
875
- core: false,
876
- defaults: { scope: ["/docs/*"], links: [], form: "parens", minPages: 0 },
877
- run(context, { scope, links, form, minPages }) {
878
- const { site, report } = context;
879
- const text = site.read("llms.txt");
880
- if (text === undefined) return;
881
- /** @param {string} url */
882
- const linked = (url) => text.includes(form === "markdown" ? `](${url})` : `(${url})`);
883
- const paths = listed(context)
884
- .filter(({ loc, path }) => loc.startsWith(`${site.site}/`) && inScope(path, scope))
885
- .map(({ path }) => path);
886
- if (paths.length < minPages) {
887
- report("llms.txt", `${paths.length} pages in ${scope.join(", ")}, needs ${minPages}`);
888
- }
889
- for (const url of [...paths.map((path) => `${site.site}/raw${path}.md`), ...links]) {
890
- if (!linked(url)) report("llms.txt", `no link to ${url}`);
891
- }
892
- },
893
- }),
894
- rule({
895
- id: "llms-docs-section",
896
- core: false,
897
- defaults: {},
898
- run({ site, report }) {
899
- const text = site.read("llms.txt");
900
- if (text === undefined) return;
901
- const section = text.split(/^## Docs$/m)[1]?.split(/^## /m)[0] ?? "";
902
- const titles = [...section.matchAll(/^- \[([^\]]+)\]\(([^)]+)\)/gm)].map(
903
- ([, title]) => title,
904
- );
905
- if (!titles.length) report("llms.txt", "no ## Docs section with links");
906
- for (const [title, same] of Map.groupBy(titles, (entry) => entry)) {
907
- if (same.length > 1)
908
- report("llms.txt", `${same.length} links in ## Docs share the title "${title}"`);
909
- }
910
- },
911
- }),
912
- rule({
913
- id: "llms-full",
914
- core: false,
915
- defaults: {},
916
- run({ site, report }) {
917
- if (site.read("llms-full.txt") === undefined) report("llms-full.txt", "missing");
918
- },
919
- }),
920
- rule({
921
- id: "markdown-clean",
922
- core: false,
923
- defaults: { files: ["llms-full.txt"], tables: "line-start" },
924
- run({ site, report }, { files, tables }) {
925
- const globs = files.map(globRegExp);
926
- const names = files.every((file) => !file.includes("*"))
927
- ? [...files]
928
- : allFiles(site.dist).filter((file) => globs.some((glob) => glob.test(file)));
929
- const table = tables === "line-start" ? /^\s*<(?:table|thead|tbody|tr)\b/im : /<table[\s>]/i;
930
- for (const name of names) {
931
- const text = site.read(name);
932
- if (text === undefined) continue;
933
- if (table.test(text)) report(name, "has an HTML table");
934
- if (text.includes("&#x22;")) report(name, "has &#x22;, left over from an MDC attribute");
935
- }
936
- },
937
- }),
938
- rule({
939
- id: "markdown-copy",
940
- core: false,
941
- defaults: { scope: ["/docs/*", "/blog/*"] },
942
- run({ site, pages, report }, { scope }) {
943
- for (const page of pages) {
944
- if (inScope(page.path, scope) && site.read(`raw${page.path}.md`) === undefined) {
945
- report(page.path, `no raw${page.path}.md`);
946
- }
947
- }
948
- },
949
- }),
950
- rule({
951
- id: "markdown-heading",
952
- core: false,
953
- defaults: { scope: ["/docs/*"], ogTitle: ["/blog/*"] },
954
- run({ site, pages, report }, { scope, ogTitle }) {
955
- /** @type {Map<string, string[]>} */
956
- const headings = new Map();
957
- for (const page of pages) {
958
- const copy = `raw${page.path}.md`;
959
- const first = site.read(copy)?.split("\n")[0];
960
- if (first === undefined) continue;
961
- if (inScope(page.path, scope)) {
962
- if (!first.startsWith("# ")) report(copy, "doesn't start with a # heading");
963
- headings.set(first, [...(headings.get(first) ?? []), copy]);
964
- }
965
- if (inScope(page.path, ogTitle) && first !== `# ${page.first("og:title")}`) {
966
- report(copy, `starts with "${first}", not "# ${page.first("og:title")}"`);
967
- }
968
- }
969
- for (const [first, copies] of headings) {
970
- if (copies.length > 1) report(copies.join(", "), `all start with "${first}"`);
971
- }
972
- },
973
- }),
974
- rule({
975
- id: "markdown-alternate",
976
- core: false,
977
- defaults: { scope: ["/docs/*"] },
978
- run({ site, pages, report }, { scope }) {
979
- for (const page of pages) {
980
- if (!inScope(page.path, scope)) continue;
981
- const copy = `${site.site}/raw${page.path}.md`;
982
- const linked = page
983
- .tags("link")
984
- .some(
985
- (link) =>
986
- link.rel?.toLowerCase() === "alternate" &&
987
- link.type === "text/markdown" &&
988
- link.href === copy,
989
- );
990
- if (!linked)
991
- report(page.path, `no <link rel="alternate" type="text/markdown" href="${copy}">`);
992
- }
993
- },
994
- }),
995
- rule({
996
- id: "redirects-permanent",
997
- core: false,
998
- defaults: { needsDestination: true },
999
- run({ site, report }, { needsDestination }) {
1000
- for (const line of (site.read("_redirects") ?? "").split("\n")) {
1001
- const [from, destination, status = "302"] = line.trim().split(/\s+/);
1002
- if (!from || from.startsWith("#") || (needsDestination && !destination)) continue;
1003
- // Cloudflare redirects with a 302 when a rule names no status.
1004
- if (status === "302" || status === "307") {
1005
- report("_redirects", `${from} redirects with a temporary ${status}`);
1006
- }
1007
- }
1008
- },
1009
- }),
1010
- rule({
1011
- id: "headers-noindex",
1012
- core: false,
1013
- defaults: { patterns: [], urls: [] },
1014
- run({ site, report }, { patterns, urls }) {
1015
- for (const pattern of patterns) {
1016
- const found = site.headers.some(
1017
- (entry) =>
1018
- entry.pattern === pattern &&
1019
- entry.headers.some(
1020
- ([name, value]) => name === "x-robots-tag" && /\bnoindex\b/i.test(value),
1021
- ),
1022
- );
1023
- if (!found) report("_headers", `no ${pattern} rule with X-Robots-Tag: noindex`);
1024
- }
1025
- for (const url of urls) {
1026
- const tags = site
1027
- .headersFor(url)
1028
- .filter(([name]) => name === "x-robots-tag")
1029
- .map(([, value]) => value)
1030
- .join(", ");
1031
- if (!/noindex/i.test(tags)) report("_headers", `${url} gets no X-Robots-Tag: noindex`);
1032
- }
1033
- },
1034
- }),
1035
- rule({
1036
- id: "headers-duplicates",
1037
- core: false,
1038
- defaults: {},
1039
- run({ site, report }) {
1040
- for (const [pattern, same] of Map.groupBy(site.headers, (entry) => entry.pattern)) {
1041
- if (same.length > 1) {
1042
- report(
1043
- "_headers",
1044
- `${same.length} rules for ${pattern}, of which Cloudflare applies only the last`,
1045
- );
1046
- }
1047
- }
1048
- },
1049
- }),
1050
- rule({
1051
- id: "headers-markdown",
1052
- core: false,
1053
- defaults: { scope: ["/docs/*", "/blog/*"] },
1054
- run({ site, pages, report }, { scope }) {
1055
- for (const page of pages) {
1056
- if (!inScope(page.path, scope)) continue;
1057
- const url = `${site.site}/raw${page.path}.md`;
1058
- const headers = site.headersFor(url);
1059
- const link = headers.find(([name]) => name === "link")?.[1];
1060
- if (link !== `<${site.site}${page.path}>; rel="canonical"`) {
1061
- report(url, `Link ${link ?? "(none)"}, not its page as canonical`);
1062
- }
1063
- const robots = headers
1064
- .filter(([name]) => name === "x-robots-tag")
1065
- .map(([, value]) => value);
1066
- if (robots.some((value) => /noindex/i.test(value))) {
1067
- report(url, `X-Robots-Tag ${robots.join(", ")}`);
1068
- }
1069
- }
1070
- },
1071
- }),
1072
- rule({
1073
- id: "not-found",
1074
- core: false,
1075
- defaults: {},
1076
- run({ site, report }) {
1077
- if (site.read("404.html") === undefined) report("404.html", "missing");
1078
- },
1079
- }),
168
+ rule({
169
+ id: "sitemap",
170
+ core: true,
171
+ defaults: {},
172
+ run({ site, report }) {
173
+ const { exists, entries } = site.sitemap;
174
+ if (!exists) {
175
+ return report("sitemap.xml", "missing");
176
+ }
177
+ if (!entries.length) {
178
+ report("sitemap.xml", "no <url>");
179
+ }
180
+ for (const entry of entries) {
181
+ if (entry.error) {
182
+ report("sitemap.xml", `${entry.loc} can't be decoded: ${entry.error}`);
183
+ } else if (!entry.hasLoc) {
184
+ report("sitemap.xml", "a <url> has no <loc>");
185
+ }
186
+ }
187
+ },
188
+ }),
189
+ rule({
190
+ id: "sitemap-host",
191
+ core: true,
192
+ defaults: {},
193
+ run({ site, report }) {
194
+ for (const { loc, hasLoc } of site.sitemap.entries) {
195
+ if (hasLoc && !loc.startsWith(`${site.site}/`)) {
196
+ report("sitemap.xml", `${loc} isn't on ${site.site}`);
197
+ }
198
+ }
199
+ },
200
+ }),
201
+ rule({
202
+ id: "sitemap-duplicates",
203
+ core: false,
204
+ defaults: {},
205
+ run({ site, report }) {
206
+ const seen = new Set();
207
+ for (const { loc, hasLoc } of site.sitemap.entries) {
208
+ if (hasLoc && seen.has(loc)) {
209
+ report("sitemap.xml", `${loc} is listed twice`);
210
+ }
211
+ seen.add(loc);
212
+ }
213
+ },
214
+ }),
215
+ rule({
216
+ id: "lastmod",
217
+ core: true,
218
+ defaults: { format: "loose", realDate: "none" },
219
+ run({ site, report }, { format, realDate }) {
220
+ for (const { loc, lastmod } of site.sitemap.entries) {
221
+ if (!lastmod) {
222
+ report("sitemap.xml", `${loc} has no <lastmod>`);
223
+ } else if (!LASTMOD_FORMATS[format].test(lastmod)) {
224
+ report("sitemap.xml", `${loc} has a <lastmod> that isn't a ${format} date: ${lastmod}`);
225
+ } else if (
226
+ (realDate === "date-only" &&
227
+ (dateOnly(lastmod) ? !isCalendarDay(lastmod) : Number.isNaN(Date.parse(lastmod)))) ||
228
+ (realDate === "parseable" && Number.isNaN(Date.parse(lastmod)))
229
+ ) {
230
+ report("sitemap.xml", `${loc} has a <lastmod> that isn't a real date: ${lastmod}`);
231
+ }
232
+ }
233
+ },
234
+ }),
235
+ rule({
236
+ id: "lastmod-future",
237
+ core: false,
238
+ defaults: { skewHours: 0 },
239
+ run({ site, report }, { skewHours }) {
240
+ const latest = site.now.getTime() + skewHours * 60 * 60 * 1000;
241
+ for (const { loc, lastmod } of site.sitemap.entries) {
242
+ if (lastmod && lastmodTime(lastmod) > latest) {
243
+ report("sitemap.xml", `${loc} has a <lastmod> in the future: ${lastmod}`);
244
+ }
245
+ }
246
+ },
247
+ }),
248
+ rule({
249
+ id: "sitemap-pages",
250
+ core: true,
251
+ defaults: { paths: "exact", notFoundCopy: false },
252
+ run({ site, report }, { notFoundCopy }) {
253
+ const notFound = site.read("404.html");
254
+ for (const { loc, url, hasLoc } of site.sitemap.entries) {
255
+ if (!hasLoc) {
256
+ continue;
257
+ }
258
+ if (!url) {
259
+ report("sitemap.xml", `${loc} isn't a URL`);
260
+ continue;
261
+ }
262
+ const file = site.resolve(url.pathname);
263
+ if (!file) {
264
+ report(url.pathname, `no HTML file in dist is served at ${loc}`);
265
+ } else if (notFoundCopy && notFound !== undefined && site.read(file) === notFound) {
266
+ report(url.pathname, `${file} is the 404 page`);
267
+ }
268
+ }
269
+ },
270
+ }),
271
+ rule({
272
+ id: "sitemap-indexable",
273
+ core: true,
274
+ defaults: { sources: [{ type: "meta", names: ["robots", "googlebot"] }] },
275
+ run(context, { sources }) {
276
+ for (const { path, url } of listed(context)) {
277
+ const file = context.site.resolve(path);
278
+ if (!file) {
279
+ continue;
280
+ }
281
+ const why = context.site.outOfIndex(sources, { file, path, host: url.host });
282
+ if (why) {
283
+ context.report(path, `it's in the sitemap, but out of the index: ${why}`);
284
+ }
285
+ }
286
+ },
287
+ }),
288
+ rule({
289
+ id: "sitemap-coverage",
290
+ core: false,
291
+ defaults: { exclude: /** @type {readonly IndexSource[]} */ ([]) },
292
+ run({ site, report }, { exclude }) {
293
+ const locs = site.locs;
294
+ for (const file of site.htmlFiles) {
295
+ const path = site.served(file);
296
+ if (site.outOfIndex(exclude, { file, path, host: site.host })) {
297
+ continue;
298
+ }
299
+ if (!locs.has(`${site.site}${path}`)) {
300
+ report(path, `${file} isn't in the sitemap`);
301
+ }
302
+ }
303
+ },
304
+ }),
305
+ rule({
306
+ id: "title",
307
+ core: true,
308
+ defaults: { max: 60, exactlyOne: false, nonEmpty: true },
309
+ run({ site, pages, report }, { max, exactlyOne, nonEmpty }) {
310
+ for (const page of pages) {
311
+ const { titles } = page;
312
+ if (exactlyOne && titles.length !== 1) {
313
+ report(page.path, `${titles.length} <title> elements, not exactly one`);
314
+ continue;
315
+ }
316
+ const title = titles[0] ?? "";
317
+ if (nonEmpty && !title) {
318
+ report(page.path, "no <title>");
319
+ } else if (site.length(title) > max) {
320
+ report(page.path, `<title> is ${site.length(title)} characters, over ${max}: "${title}"`);
321
+ }
322
+ }
323
+ },
324
+ }),
325
+ rule({
326
+ id: "title-unique",
327
+ core: true,
328
+ defaults: {},
329
+ run({ pages, report }) {
330
+ const seen = new Map();
331
+ for (const page of pages) {
332
+ const title = page.titles[0];
333
+ if (!title) {
334
+ continue;
335
+ }
336
+ if (seen.has(title)) {
337
+ report(page.path, `<title> is the same as ${seen.get(title)}'s`);
338
+ } else {
339
+ seen.set(title, page.path);
340
+ }
341
+ }
342
+ },
343
+ }),
344
+ rule({
345
+ id: "description",
346
+ core: true,
347
+ defaults: { min: 70, max: 160, exactlyOne: false },
348
+ run({ site, pages, report }, { min, max, exactlyOne }) {
349
+ for (const page of pages) {
350
+ const values = page.meta("description");
351
+ if (exactlyOne && values.length !== 1) {
352
+ report(page.path, `${values.length} meta descriptions, not exactly one`);
353
+ continue;
354
+ }
355
+ const description = values[0] ?? "";
356
+ const length = site.length(description);
357
+ if (!exactlyOne && !description) {
358
+ report(page.path, "no meta description");
359
+ } else if (length < min || length > max) {
360
+ report(page.path, `meta description is ${length} characters, outside ${min} to ${max}`);
361
+ }
362
+ }
363
+ },
364
+ }),
365
+ rule({
366
+ id: "description-unique",
367
+ core: true,
368
+ defaults: {},
369
+ run({ pages, report }) {
370
+ const seen = new Map();
371
+ for (const page of pages) {
372
+ const description = page.meta("description")[0];
373
+ if (!description) {
374
+ continue;
375
+ }
376
+ if (seen.has(description)) {
377
+ report(page.path, `meta description is the same as ${seen.get(description)}'s`);
378
+ } else {
379
+ seen.set(description, page.path);
380
+ }
381
+ }
382
+ },
383
+ }),
384
+ rule({
385
+ id: "h1",
386
+ core: true,
387
+ defaults: {},
388
+ run({ pages, report }) {
389
+ for (const page of pages) {
390
+ if (page.h1 !== 1) {
391
+ report(page.path, `${page.h1} <h1> elements, not exactly one`);
392
+ }
393
+ }
394
+ },
395
+ }),
396
+ rule({
397
+ id: "canonical",
398
+ core: true,
399
+ defaults: { exactlyOne: true, rel: "exact", requireHref: false },
400
+ run({ pages, report }, { exactlyOne, rel, requireHref }) {
401
+ for (const page of pages) {
402
+ const hrefs = page.canonicals(rel, requireHref);
403
+ if (exactlyOne && hrefs.length !== 1) {
404
+ report(page.path, `${hrefs.length} canonical links, not exactly one`);
405
+ } else if (!hrefs[0]) {
406
+ report(page.path, "no canonical link");
407
+ } else if (hrefs[0] !== page.loc) {
408
+ report(page.path, `canonical link ${hrefs[0]} isn't its URL, ${page.loc}`);
409
+ }
410
+ }
411
+ },
412
+ }),
413
+ rule({
414
+ id: "lang",
415
+ core: true,
416
+ defaults: { lang: "en" },
417
+ run({ pages, report }, { lang }) {
418
+ for (const page of pages) {
419
+ if (lang === false ? !page.lang : page.lang !== lang) {
420
+ report(page.path, `<html lang="${page.lang ?? ""}">, needs ${lang || "a language"}`);
421
+ }
422
+ }
423
+ },
424
+ }),
425
+ rule({
426
+ id: "open-graph",
427
+ core: true,
428
+ defaults: { url: "loc" },
429
+ run({ pages, report, optionsOf }, { url }) {
430
+ const { rel, requireHref } = optionsOf("canonical");
431
+ for (const page of pages) {
432
+ for (const key of ["og:title", "og:description", "og:type", "og:image", "og:url"]) {
433
+ if (!page.has(key)) {
434
+ report(page.path, `no ${key}`);
435
+ }
436
+ }
437
+ const ogUrl = page.first("og:url");
438
+ const expected = url === "loc" ? page.loc : page.canonicals(rel, requireHref)[0];
439
+ if (ogUrl?.trim() && ogUrl !== expected) {
440
+ report(
441
+ page.path,
442
+ `og:url ${ogUrl} isn't the ${url === "loc" ? "page's URL" : "canonical link"}`,
443
+ );
444
+ }
445
+ }
446
+ },
447
+ }),
448
+ rule({
449
+ id: "og-image-alt",
450
+ core: false,
451
+ defaults: {},
452
+ run({ pages, report }) {
453
+ for (const page of pages) {
454
+ if (!page.has("og:image:alt")) {
455
+ report(page.path, "no og:image:alt");
456
+ }
457
+ }
458
+ },
459
+ }),
460
+ rule({
461
+ id: "meta-conflicts",
462
+ core: false,
463
+ defaults: {
464
+ keys: [
465
+ "og:title",
466
+ "og:description",
467
+ "og:url",
468
+ "og:type",
469
+ "og:image",
470
+ "og:image:alt",
471
+ "twitter:title",
472
+ "twitter:description",
473
+ "twitter:image",
474
+ ],
475
+ },
476
+ run({ pages, report }, { keys }) {
477
+ for (const page of pages) {
478
+ for (const key of keys) {
479
+ const values = new Set(page.meta(key));
480
+ if (values.size > 1) {
481
+ report(page.path, `${values.size} different values of ${key}`);
482
+ }
483
+ }
484
+ }
485
+ },
486
+ }),
487
+ rule({
488
+ id: "og-image-host",
489
+ core: true,
490
+ defaults: {},
491
+ run({ site, pages, report }) {
492
+ for (const page of pages) {
493
+ const image = page.first("og:image");
494
+ if (image?.trim() && !image.startsWith(`${site.site}/`)) {
495
+ report(page.path, `og:image ${image} isn't on ${site.site}`);
496
+ }
497
+ }
498
+ },
499
+ }),
500
+ rule({
501
+ id: "og-image-size-tags",
502
+ core: false,
503
+ defaults: { onHostOnly: false },
504
+ run({ site, pages, report }, { onHostOnly }) {
505
+ for (const page of pages) {
506
+ if (onHostOnly && !page.first("og:image")?.startsWith(`${site.site}/`)) {
507
+ continue;
508
+ }
509
+ const width = page.first("og:image:width");
510
+ const height = page.first("og:image:height");
511
+ if (width !== "1200") {
512
+ report(page.path, `og:image:width is ${width ?? "(none)"}, not 1200`);
513
+ }
514
+ if (height !== "630") {
515
+ report(page.path, `og:image:height is ${height ?? "(none)"}, not 630`);
516
+ }
517
+ }
518
+ },
519
+ }),
520
+ rule({
521
+ id: "og-image-file",
522
+ core: true,
523
+ defaults: { types: ["png", "jpeg"], png: "name" },
524
+ run({ site, pages, report }, { types, png }) {
525
+ for (const page of pages) {
526
+ const image = page.first("og:image");
527
+ if (!image?.startsWith(`${site.site}/`)) {
528
+ continue;
529
+ }
530
+ let pathname = "";
531
+ try {
532
+ pathname = new URL(image).pathname;
533
+ } catch {
534
+ // Reported as off the site, if anywhere.
535
+ }
536
+ let decoded = pathname;
537
+ try {
538
+ decoded = decodeURIComponent(pathname);
539
+ } catch {
540
+ // Keep the path as it is.
541
+ }
542
+ const file = [decoded, pathname]
543
+ .map((path) => join(site.dist, path))
544
+ .find((path) => isFile(path));
545
+ if (!file) {
546
+ report(page.path, `og:image ${image} isn't in dist`);
547
+ continue;
548
+ }
549
+ const size = imageSize(readFileSync(file), png);
550
+ if (!size || !types.includes(size.type)) {
551
+ report(page.path, `og:image ${image} isn't a ${types.join(" or ").toUpperCase()}`);
552
+ } else if (size.width !== 1200 || size.height !== 630) {
553
+ report(page.path, `og:image ${image} is ${size.width} × ${size.height}, not 1200 × 630`);
554
+ }
555
+ }
556
+ },
557
+ }),
558
+ rule({
559
+ id: "twitter",
560
+ core: true,
561
+ defaults: { card: "summary_large_image" },
562
+ run({ pages, report }, { card }) {
563
+ for (const page of pages) {
564
+ const value = page.first("twitter:card");
565
+ if (card === "any" ? !page.has("twitter:card") : value !== card) {
566
+ report(page.path, `twitter:card is ${value || "(none)"}`);
567
+ }
568
+ if (!page.has("twitter:image")) {
569
+ report(page.path, "no twitter:image");
570
+ }
571
+ }
572
+ },
573
+ }),
574
+ rule({
575
+ id: "twitter-text",
576
+ core: false,
577
+ defaults: {},
578
+ run({ pages, report }) {
579
+ for (const page of pages) {
580
+ for (const key of ["twitter:title", "twitter:description"]) {
581
+ if (!page.has(key)) {
582
+ report(page.path, `no ${key}`);
583
+ }
584
+ }
585
+ }
586
+ },
587
+ }),
588
+ rule({
589
+ id: "json-ld-parse",
590
+ core: true,
591
+ defaults: {},
592
+ run({ pages, report }) {
593
+ for (const page of pages) {
594
+ for (const [index, block] of page.blocks.entries()) {
595
+ if (!block.ok) {
596
+ report(page.path, `JSON-LD block ${index + 1} doesn't parse: ${block.error}`);
597
+ }
598
+ }
599
+ }
600
+ },
601
+ }),
602
+ rule({
603
+ id: "json-ld-present",
604
+ core: false,
605
+ defaults: {},
606
+ run({ pages, report }) {
607
+ for (const page of pages) {
608
+ if (!page.blocks.length) {
609
+ report(page.path, "no JSON-LD");
610
+ }
611
+ }
612
+ },
613
+ }),
614
+ rule({
615
+ id: "json-ld-context",
616
+ core: false,
617
+ defaults: {},
618
+ run({ pages, report }) {
619
+ for (const page of pages) {
620
+ for (const block of page.blocks) {
621
+ if (!block.ok) {
622
+ continue;
623
+ }
624
+ const context = isObject(block.value) ? block.value["@context"] : undefined;
625
+ if (context !== "https://schema.org") {
626
+ report(page.path, "a JSON-LD block's @context isn't https://schema.org");
627
+ }
628
+ }
629
+ }
630
+ },
631
+ }),
632
+ rule({
633
+ id: "json-ld-ids",
634
+ core: false,
635
+ defaults: {},
636
+ run({ pages, report }) {
637
+ for (const page of pages) {
638
+ const ids = new Set();
639
+ for (const node of page.nodes) {
640
+ const id = node["@id"];
641
+ if (typeof id !== "string") {
642
+ continue;
643
+ }
644
+ if (ids.has(id)) {
645
+ report(page.path, `two JSON-LD nodes with the @id ${id}`);
646
+ }
647
+ ids.add(id);
648
+ }
649
+ }
650
+ },
651
+ }),
652
+ rule({
653
+ id: "json-ld-types",
654
+ core: false,
655
+ defaults: {
656
+ types: {
657
+ "/": ["WebSite", "SoftwareSourceCode", "Organization"],
658
+ "/docs/*": ["TechArticle", "BreadcrumbList"],
659
+ },
660
+ },
661
+ run({ site, pages, report }, { types }) {
662
+ for (const page of pages) {
663
+ for (const [pattern, required] of Object.entries(types)) {
664
+ if (!inScope(page.path, [pattern])) {
665
+ continue;
666
+ }
667
+ for (const type of required) {
668
+ if (!page.nodes.some((node) => isType(node, type, site.profile.typeArrays))) {
669
+ report(page.path, `no ${type} in the JSON-LD`);
670
+ }
671
+ }
672
+ }
673
+ }
674
+ },
675
+ }),
676
+ rule({
677
+ id: "json-ld-breadcrumbs",
678
+ core: false,
679
+ defaults: {
680
+ scope: ["/docs/*"],
681
+ nodes: "first",
682
+ item: ["url"],
683
+ exactType: false,
684
+ nonArray: "skip",
685
+ },
686
+ run({ site, pages, report }, { scope, nodes, item: forms, exactType, nonArray }) {
687
+ const locs = site.locs;
688
+ for (const page of pages) {
689
+ if (!inScope(page.path, scope)) {
690
+ continue;
691
+ }
692
+ const lists = page.nodes.filter((node) =>
693
+ isType(node, "BreadcrumbList", !exactType && site.profile.typeArrays),
694
+ );
695
+ for (const breadcrumbs of nodes === "first" ? lists.slice(0, 1) : lists) {
696
+ const items = field(breadcrumbs, "itemListElement");
697
+ // With `iterate`, a value that isn't a list is read as one, and one that can't be read
698
+ // as one fails the rule, as a checker that loops over it does.
699
+ const entries =
700
+ nonArray === "iterate"
701
+ ? // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- the spread is the check
702
+ [.../** @type {Iterable<unknown>} */ (items ?? [])]
703
+ : Array.isArray(items)
704
+ ? items
705
+ : [];
706
+ for (const entry of entries) {
707
+ const item = entry && typeof entry === "object" ? entry.item : undefined;
708
+ const target =
709
+ typeof item === "string"
710
+ ? forms.includes("url")
711
+ ? item
712
+ : undefined
713
+ : forms.includes("id") && isObject(item)
714
+ ? item["@id"]
715
+ : undefined;
716
+ if (typeof target !== "string" || !locs.has(target)) {
717
+ report(
718
+ page.path,
719
+ `a breadcrumb links ${typeof target === "string" ? target : (JSON.stringify(target) ?? "nothing")}, which isn't in the sitemap`,
720
+ );
721
+ }
722
+ }
723
+ }
724
+ }
725
+ },
726
+ }),
727
+ rule({
728
+ id: "json-ld-article",
729
+ core: false,
730
+ defaults: { scope: ["/docs/*"] },
731
+ run({ site, pages, report }, { scope }) {
732
+ for (const page of pages) {
733
+ if (!inScope(page.path, scope)) {
734
+ continue;
735
+ }
736
+ const article = page.nodes.find((node) =>
737
+ isType(node, "TechArticle", site.profile.typeArrays),
738
+ );
739
+ if (!article) {
740
+ continue;
741
+ }
742
+ const lastmod = lastmodOf(site, page.loc);
743
+ if (lastmod && article.dateModified !== lastmod) {
744
+ report(
745
+ page.path,
746
+ `the TechArticle's dateModified ${String(article.dateModified)} isn't the sitemap's ${lastmod}`,
747
+ );
748
+ }
749
+ const image = page.first("og:image");
750
+ if (image && article.image !== image) {
751
+ report(page.path, `the TechArticle's image isn't the og:image, ${image}`);
752
+ }
753
+ }
754
+ },
755
+ }),
756
+ rule({
757
+ id: "json-ld-posting",
758
+ core: false,
759
+ defaults: { scope: ["/blog/*"] },
760
+ run({ site, pages, report }, { scope }) {
761
+ const { typeArrays } = site.profile;
762
+ for (const page of pages) {
763
+ if (!inScope(page.path, scope)) {
764
+ continue;
765
+ }
766
+ const postings = page.nodes.filter((node) => isType(node, "BlogPosting", typeArrays));
767
+ if (postings.length !== 1) {
768
+ report(page.path, `${postings.length} BlogPosting nodes, not one`);
769
+ }
770
+ for (const posting of postings) {
771
+ const missing = ["headline", "description", "datePublished", "image", "url"].filter(
772
+ (key) => !posting[key],
773
+ );
774
+ const author = posting.author;
775
+ if (!isObject(author) || !field(author, "name")) {
776
+ missing.push("author.name");
777
+ }
778
+ if (missing.length) {
779
+ report(page.path, `a BlogPosting without ${missing.join(", ")}`);
780
+ }
781
+ }
782
+ if (page.nodes.some((node) => isType(node, "Article", typeArrays))) {
783
+ report(page.path, "an Article node beside the BlogPosting");
784
+ }
785
+ }
786
+ },
787
+ }),
788
+ rule({
789
+ id: "json-ld-organization",
790
+ core: false,
791
+ defaults: { name: "", scope: ["*"] },
792
+ run({ site, pages, report }, { name, scope }) {
793
+ for (const page of pages) {
794
+ if (!inScope(page.path, scope)) {
795
+ continue;
796
+ }
797
+ const named = page.nodes.some(
798
+ (node) => isType(node, "Organization", site.profile.typeArrays) && node.name === name,
799
+ );
800
+ if (named) {
801
+ report(page.path, `an Organization named ${name}, which isn't an organisation`);
802
+ }
803
+ }
804
+ },
805
+ }),
806
+ rule({
807
+ id: "robots-sitemap",
808
+ core: true,
809
+ defaults: { match: "exact" },
810
+ run({ site, report }, { match }) {
811
+ const text = site.read("robots.txt");
812
+ if (text === undefined) {
813
+ return report("robots.txt", "missing");
814
+ }
815
+ const url = `${site.site}/sitemap.xml`;
816
+ const line = `Sitemap: ${url}`;
817
+ const found =
818
+ match === "loose"
819
+ ? new RegExp(`^Sitemap:\\s*${escapeRegExp(url)}\\s*$`, "im").test(text)
820
+ : match === "trimmed"
821
+ ? text
822
+ .split("\n")
823
+ .map((raw) => raw.replace(/#.*/, "").trim())
824
+ .includes(line)
825
+ : match === "exact"
826
+ ? text.split("\n").includes(line)
827
+ : match === "anchored"
828
+ ? new RegExp(`^${escapeRegExp(line)}$`, "m").test(text)
829
+ : robotsGroups(text).lines.some(
830
+ (entry) => entry.field === "sitemap" && entry.value === url,
831
+ );
832
+ if (!found) {
833
+ report("robots.txt", `no "${line}" line`);
834
+ }
835
+ },
836
+ }),
837
+ rule({
838
+ id: "robots-crawlers",
839
+ core: false,
840
+ defaults: {
841
+ crawlers: AI_CRAWLERS,
842
+ allow: false,
843
+ case: "exact",
844
+ agents: "groups",
845
+ groupRules: "all",
846
+ },
847
+ run({ site, report }, { crawlers, allow, case: letterCase, agents, groupRules }) {
848
+ const text = site.read("robots.txt");
849
+ if (text === undefined) {
850
+ return;
851
+ }
852
+ // With `lines`, every `User-agent` line counts, read as it is, comments and all.
853
+ const groups =
854
+ agents === "lines"
855
+ ? [...text.matchAll(/^user-agent:\s*(.+?)\s*$/gim)].map(([, agent = ""]) => ({
856
+ agents: [agent],
857
+ rules: /** @type {{ field: string, value: string }[]} */ ([]),
858
+ }))
859
+ : robotsGroups(text, groupRules).groups;
860
+ /** @param {string} agent */
861
+ const key = (agent) => (letterCase === "insensitive" ? agent.toLowerCase() : agent);
862
+ for (const crawler of crawlers) {
863
+ const own = groups.filter((group) =>
864
+ group.agents.some((agent) => key(agent) === key(crawler)),
865
+ );
866
+ if (!own.length) {
867
+ report("robots.txt", `no group for User-agent: ${crawler}`);
868
+ continue;
869
+ }
870
+ const checked = allow === "first" ? own.slice(0, 1) : own;
871
+ if (
872
+ allow &&
873
+ (!checked.some((group) => hasRule(group.rules, "allow", "/")) ||
874
+ checked.some((group) => hasRule(group.rules, "disallow", "/")))
875
+ ) {
876
+ report("robots.txt", `User-agent: ${crawler} isn't allowed everywhere`);
877
+ }
878
+ }
879
+ },
880
+ }),
881
+ rule({
882
+ id: "robots-no-disallow",
883
+ core: false,
884
+ defaults: { match: "lines" },
885
+ run({ site, report }, { match }) {
886
+ const text = site.read("robots.txt");
887
+ if (text === undefined) {
888
+ return;
889
+ }
890
+ const found =
891
+ match === "lines"
892
+ ? /^disallow:\s*\/\s*$/im.test(text)
893
+ : robotsGroups(text).groups.some((group) => hasRule(group.rules, "disallow", "/"));
894
+ if (found) {
895
+ report("robots.txt", '"Disallow: /" blocks crawlers from the site');
896
+ }
897
+ },
898
+ }),
899
+ rule({
900
+ id: "robots-wildcard",
901
+ core: false,
902
+ defaults: {},
903
+ run({ site, report }) {
904
+ const text = site.read("robots.txt");
905
+ if (text === undefined) {
906
+ return;
907
+ }
908
+ const wildcards = [...text.matchAll(/^user-agent:\s*(.+?)\s*$/gim)].filter(
909
+ ([, agent]) => agent === "*",
910
+ ).length;
911
+ if (wildcards !== 1) {
912
+ report("robots.txt", `${wildcards} "User-agent: *" lines, not one`);
913
+ }
914
+ },
915
+ }),
916
+ rule({
917
+ id: "robots-directives",
918
+ core: false,
919
+ defaults: {},
920
+ run({ site, report }) {
921
+ const text = site.read("robots.txt");
922
+ if (text === undefined) {
923
+ return;
924
+ }
925
+ for (const raw of text.split("\n")) {
926
+ const line = raw.replace(/#.*/, "").trim();
927
+ const name = line.match(/^([\w-]+):\s*(.*)$/)?.[1];
928
+ if (name && !ROBOTS_DIRECTIVES.has(name.toLowerCase())) {
929
+ report("robots.txt", `"${line}": Lighthouse doesn't know ${name}`);
930
+ }
931
+ }
932
+ },
933
+ }),
934
+ rule({
935
+ id: "llms",
936
+ core: true,
937
+ defaults: { first: "non-empty", title: "", nonEmpty: false },
938
+ run({ site, report }, { first, title, nonEmpty }) {
939
+ const text = site.read("llms.txt");
940
+ if (text === undefined) {
941
+ return report("llms.txt", "missing");
942
+ }
943
+ const line =
944
+ first === "line"
945
+ ? text.split("\n")[0]
946
+ : text.split("\n").find((entry) => !isBlank(entry, site.profile.blankLines));
947
+ const ok = title
948
+ ? first === "line"
949
+ ? text.startsWith(`# ${title}\n`)
950
+ : line === `# ${title}`
951
+ : nonEmpty
952
+ ? /^# \S/.test(line ?? "")
953
+ : Boolean(line?.startsWith("# "));
954
+ if (!ok) {
955
+ report("llms.txt", `doesn't start with "# ${title || "<title>"}"`);
956
+ }
957
+ },
958
+ }),
959
+ rule({
960
+ id: "llms-summary",
961
+ core: true,
962
+ defaults: { position: "second", nonEmpty: false },
963
+ run({ site, report }, { position, nonEmpty }) {
964
+ const text = site.read("llms.txt");
965
+ if (text === undefined) {
966
+ return;
967
+ }
968
+ const lines = text.split("\n").filter((line) => !isBlank(line, site.profile.blankLines));
969
+ /** @param {string | undefined} line */
970
+ const summary = (line) =>
971
+ nonEmpty ? /^> \S/.test(line ?? "") : Boolean(line?.startsWith("> "));
972
+ const found = position === "second" ? summary(lines[1]) : lines.some(summary);
973
+ if (!found) {
974
+ report(
975
+ "llms.txt",
976
+ `no "> " summary line${position === "second" ? " under the heading" : ""}`,
977
+ );
978
+ }
979
+ },
980
+ }),
981
+ rule({
982
+ id: "llms-links",
983
+ core: false,
984
+ defaults: { scope: ["/docs/*"], links: [], form: "parens", minPages: 0 },
985
+ run(context, { scope, links, form, minPages }) {
986
+ const { site, report } = context;
987
+ const text = site.read("llms.txt");
988
+ if (text === undefined) {
989
+ return;
990
+ }
991
+ /** @param {string} url */
992
+ const linked = (url) => text.includes(form === "markdown" ? `](${url})` : `(${url})`);
993
+ const paths = listed(context)
994
+ .filter(({ loc, path }) => loc.startsWith(`${site.site}/`) && inScope(path, scope))
995
+ .map(({ path }) => path);
996
+ if (paths.length < minPages) {
997
+ report("llms.txt", `${paths.length} pages in ${scope.join(", ")}, needs ${minPages}`);
998
+ }
999
+ for (const url of [...paths.map((path) => `${site.site}/raw${path}.md`), ...links]) {
1000
+ if (!linked(url)) {
1001
+ report("llms.txt", `no link to ${url}`);
1002
+ }
1003
+ }
1004
+ },
1005
+ }),
1006
+ rule({
1007
+ id: "llms-docs-section",
1008
+ core: false,
1009
+ defaults: {},
1010
+ run({ site, report }) {
1011
+ const text = site.read("llms.txt");
1012
+ if (text === undefined) {
1013
+ return;
1014
+ }
1015
+ const section = text.split(/^## Docs$/m)[1]?.split(/^## /m)[0] ?? "";
1016
+ const titles = [...section.matchAll(/^- \[([^\]]+)\]\(([^)]+)\)/gm)].map(
1017
+ ([, title]) => title,
1018
+ );
1019
+ if (!titles.length) {
1020
+ report("llms.txt", "no ## Docs section with links");
1021
+ }
1022
+ for (const [title, same] of Map.groupBy(titles, (entry) => entry)) {
1023
+ if (same.length > 1) {
1024
+ report("llms.txt", `${same.length} links in ## Docs share the title "${title}"`);
1025
+ }
1026
+ }
1027
+ },
1028
+ }),
1029
+ rule({
1030
+ id: "llms-full",
1031
+ core: false,
1032
+ defaults: {},
1033
+ run({ site, report }) {
1034
+ if (site.read("llms-full.txt") === undefined) {
1035
+ report("llms-full.txt", "missing");
1036
+ }
1037
+ },
1038
+ }),
1039
+ rule({
1040
+ id: "markdown-clean",
1041
+ core: false,
1042
+ defaults: { files: ["llms-full.txt"], tables: "line-start" },
1043
+ run({ site, report }, { files, tables }) {
1044
+ const globs = files.map(globRegExp);
1045
+ const names = files.every((file) => !file.includes("*"))
1046
+ ? [...files]
1047
+ : allFiles(site.dist).filter((file) => globs.some((glob) => glob.test(file)));
1048
+ const table = tables === "line-start" ? /^\s*<(?:table|thead|tbody|tr)\b/im : /<table[\s>]/i;
1049
+ for (const name of names) {
1050
+ const text = site.read(name);
1051
+ if (text === undefined) {
1052
+ continue;
1053
+ }
1054
+ if (table.test(text)) {
1055
+ report(name, "has an HTML table");
1056
+ }
1057
+ if (text.includes("&#x22;")) {
1058
+ report(name, "has &#x22;, left over from an MDC attribute");
1059
+ }
1060
+ }
1061
+ },
1062
+ }),
1063
+ rule({
1064
+ id: "markdown-copy",
1065
+ core: false,
1066
+ defaults: { scope: ["/docs/*", "/blog/*"] },
1067
+ run({ site, pages, report }, { scope }) {
1068
+ for (const page of pages) {
1069
+ if (inScope(page.path, scope) && site.read(`raw${page.path}.md`) === undefined) {
1070
+ report(page.path, `no raw${page.path}.md`);
1071
+ }
1072
+ }
1073
+ },
1074
+ }),
1075
+ rule({
1076
+ id: "markdown-heading",
1077
+ core: false,
1078
+ defaults: { scope: ["/docs/*"], ogTitle: ["/blog/*"] },
1079
+ run({ site, pages, report }, { scope, ogTitle }) {
1080
+ /** @type {Map<string, string[]>} */
1081
+ const headings = new Map();
1082
+ for (const page of pages) {
1083
+ const copy = `raw${page.path}.md`;
1084
+ const first = site.read(copy)?.split("\n")[0];
1085
+ if (first === undefined) {
1086
+ continue;
1087
+ }
1088
+ if (inScope(page.path, scope)) {
1089
+ if (!first.startsWith("# ")) {
1090
+ report(copy, "doesn't start with a # heading");
1091
+ }
1092
+ headings.set(first, [...(headings.get(first) ?? []), copy]);
1093
+ }
1094
+ if (inScope(page.path, ogTitle) && first !== `# ${page.first("og:title")}`) {
1095
+ report(copy, `starts with "${first}", not "# ${page.first("og:title")}"`);
1096
+ }
1097
+ }
1098
+ for (const [first, copies] of headings) {
1099
+ if (copies.length > 1) {
1100
+ report(copies.join(", "), `all start with "${first}"`);
1101
+ }
1102
+ }
1103
+ },
1104
+ }),
1105
+ rule({
1106
+ id: "markdown-alternate",
1107
+ core: false,
1108
+ defaults: { scope: ["/docs/*"] },
1109
+ run({ site, pages, report }, { scope }) {
1110
+ for (const page of pages) {
1111
+ if (!inScope(page.path, scope)) {
1112
+ continue;
1113
+ }
1114
+ const copy = `${site.site}/raw${page.path}.md`;
1115
+ const linked = page
1116
+ .tags("link")
1117
+ .some(
1118
+ (link) =>
1119
+ link.rel?.toLowerCase() === "alternate" &&
1120
+ link.type === "text/markdown" &&
1121
+ link.href === copy,
1122
+ );
1123
+ if (!linked) {
1124
+ report(page.path, `no <link rel="alternate" type="text/markdown" href="${copy}">`);
1125
+ }
1126
+ }
1127
+ },
1128
+ }),
1129
+ rule({
1130
+ id: "redirects-permanent",
1131
+ core: false,
1132
+ defaults: { needsDestination: true },
1133
+ run({ site, report }, { needsDestination }) {
1134
+ for (const line of (site.read("_redirects") ?? "").split("\n")) {
1135
+ const [from, destination, status = "302"] = line.trim().split(/\s+/);
1136
+ if (!from || from.startsWith("#") || (needsDestination && !destination)) {
1137
+ continue;
1138
+ }
1139
+ // Cloudflare redirects with a 302 when a rule names no status.
1140
+ if (status === "302" || status === "307") {
1141
+ report("_redirects", `${from} redirects with a temporary ${status}`);
1142
+ }
1143
+ }
1144
+ },
1145
+ }),
1146
+ rule({
1147
+ id: "headers-noindex",
1148
+ core: false,
1149
+ defaults: { patterns: [], urls: [] },
1150
+ run({ site, report }, { patterns, urls }) {
1151
+ for (const pattern of patterns) {
1152
+ const found = site.headers.some(
1153
+ (entry) =>
1154
+ entry.pattern === pattern &&
1155
+ entry.headers.some(
1156
+ ([name, value]) => name === "x-robots-tag" && /\bnoindex\b/i.test(value),
1157
+ ),
1158
+ );
1159
+ if (!found) {
1160
+ report("_headers", `no ${pattern} rule with X-Robots-Tag: noindex`);
1161
+ }
1162
+ }
1163
+ for (const url of urls) {
1164
+ const tags = site
1165
+ .headersFor(url)
1166
+ .filter(([name]) => name === "x-robots-tag")
1167
+ .map(([, value]) => value)
1168
+ .join(", ");
1169
+ if (!/noindex/i.test(tags)) {
1170
+ report("_headers", `${url} gets no X-Robots-Tag: noindex`);
1171
+ }
1172
+ }
1173
+ },
1174
+ }),
1175
+ rule({
1176
+ id: "headers-duplicates",
1177
+ core: false,
1178
+ defaults: {},
1179
+ run({ site, report }) {
1180
+ for (const [pattern, same] of Map.groupBy(site.headers, (entry) => entry.pattern)) {
1181
+ if (same.length > 1) {
1182
+ report(
1183
+ "_headers",
1184
+ `${same.length} rules for ${pattern}, of which Cloudflare applies only the last`,
1185
+ );
1186
+ }
1187
+ }
1188
+ },
1189
+ }),
1190
+ rule({
1191
+ id: "headers-markdown",
1192
+ core: false,
1193
+ defaults: { scope: ["/docs/*", "/blog/*"] },
1194
+ run({ site, pages, report }, { scope }) {
1195
+ for (const page of pages) {
1196
+ if (!inScope(page.path, scope)) {
1197
+ continue;
1198
+ }
1199
+ const url = `${site.site}/raw${page.path}.md`;
1200
+ const headers = site.headersFor(url);
1201
+ const link = headers.find(([name]) => name === "link")?.[1];
1202
+ if (link !== `<${site.site}${page.path}>; rel="canonical"`) {
1203
+ report(url, `Link ${link ?? "(none)"}, not its page as canonical`);
1204
+ }
1205
+ const robots = headers
1206
+ .filter(([name]) => name === "x-robots-tag")
1207
+ .map(([, value]) => value);
1208
+ if (robots.some((value) => /noindex/i.test(value))) {
1209
+ report(url, `X-Robots-Tag ${robots.join(", ")}`);
1210
+ }
1211
+ }
1212
+ },
1213
+ }),
1214
+ rule({
1215
+ id: "not-found",
1216
+ core: false,
1217
+ defaults: {},
1218
+ run({ site, report }) {
1219
+ if (site.read("404.html") === undefined) {
1220
+ report("404.html", "missing");
1221
+ }
1222
+ },
1223
+ }),
1080
1224
  ];
1081
1225
 
1082
1226
  const scope = list(pattern);
@@ -1086,68 +1230,72 @@ const scope = list(pattern);
1086
1230
  * @type {Partial<Record<RuleId, Record<string, import("./validate.js").Validator>>>}
1087
1231
  */
1088
1232
  export const SCHEMAS = {
1089
- lastmod: {
1090
- format: oneOf("loose", "date", "w3c"),
1091
- realDate: oneOf("none", "date-only", "parseable"),
1092
- },
1093
- "lastmod-future": { skewHours: count },
1094
- "sitemap-pages": { paths: oneOf("lookup", "exact", "exact-slash"), notFoundCopy: bool },
1095
- "sitemap-indexable": { sources: list(source) },
1096
- "sitemap-coverage": { exclude: list(source) },
1097
- title: { max: count, exactlyOne: bool, nonEmpty: bool },
1098
- description: { min: count, max: count, exactlyOne: bool },
1099
- canonical: {
1100
- exactlyOne: bool,
1101
- rel: oneOf("exact", "token", "exact-any-case"),
1102
- requireHref: bool,
1103
- },
1104
- lang: {
1105
- lang: (value, path) => {
1106
- if (value !== false) text(value, path);
1107
- },
1108
- },
1109
- "open-graph": { url: oneOf("loc", "canonical") },
1110
- "meta-conflicts": { keys: list(text) },
1111
- "og-image-size-tags": { onHostOnly: bool },
1112
- "og-image-file": {
1113
- types: list(oneOf("png", "jpeg"), { nonEmpty: true }),
1114
- png: oneOf("name", "signature"),
1115
- },
1116
- twitter: { card: oneOf("summary_large_image", "any") },
1117
- "json-ld-types": { types: typesByPath },
1118
- "json-ld-breadcrumbs": {
1119
- scope,
1120
- nodes: oneOf("first", "all"),
1121
- item: list(oneOf("url", "id"), { nonEmpty: true }),
1122
- exactType: bool,
1123
- nonArray: oneOf("skip", "iterate"),
1124
- },
1125
- "json-ld-article": { scope },
1126
- "json-ld-posting": { scope },
1127
- "json-ld-organization": { name: text, scope },
1128
- "robots-sitemap": { match: oneOf("loose", "trimmed", "anchored", "exact", "field") },
1129
- "robots-crawlers": {
1130
- crawlers: list(text),
1131
- allow: oneOf(false, "first", "all"),
1132
- case: oneOf("exact", "insensitive"),
1133
- agents: oneOf("groups", "lines"),
1134
- groupRules: oneOf("all", "directives", "allow-disallow"),
1135
- },
1136
- "robots-no-disallow": { match: oneOf("lines", "groups") },
1137
- llms: {
1138
- first: oneOf("line", "non-empty"),
1139
- title: (value, path) => {
1140
- if (typeof value !== "string") text(value, path);
1141
- },
1142
- nonEmpty: bool,
1143
- },
1144
- "llms-summary": { position: oneOf("second", "any"), nonEmpty: bool },
1145
- "llms-links": { scope, links: list(url), form: oneOf("markdown", "parens"), minPages: count },
1146
- "markdown-clean": { files: list(text), tables: oneOf("line-start", "anywhere") },
1147
- "markdown-copy": { scope },
1148
- "markdown-heading": { scope, ogTitle: scope },
1149
- "markdown-alternate": { scope },
1150
- "redirects-permanent": { needsDestination: bool },
1151
- "headers-noindex": { patterns: list(text), urls: list(url) },
1152
- "headers-markdown": { scope },
1233
+ lastmod: {
1234
+ format: oneOf("loose", "date", "w3c"),
1235
+ realDate: oneOf("none", "date-only", "parseable"),
1236
+ },
1237
+ "lastmod-future": { skewHours: count },
1238
+ "sitemap-pages": { paths: oneOf("lookup", "exact", "exact-slash"), notFoundCopy: bool },
1239
+ "sitemap-indexable": { sources: list(source) },
1240
+ "sitemap-coverage": { exclude: list(source) },
1241
+ title: { max: count, exactlyOne: bool, nonEmpty: bool },
1242
+ description: { min: count, max: count, exactlyOne: bool },
1243
+ canonical: {
1244
+ exactlyOne: bool,
1245
+ rel: oneOf("exact", "token", "exact-any-case"),
1246
+ requireHref: bool,
1247
+ },
1248
+ lang: {
1249
+ lang: (value, path) => {
1250
+ if (value !== false) {
1251
+ text(value, path);
1252
+ }
1253
+ },
1254
+ },
1255
+ "open-graph": { url: oneOf("loc", "canonical") },
1256
+ "meta-conflicts": { keys: list(text) },
1257
+ "og-image-size-tags": { onHostOnly: bool },
1258
+ "og-image-file": {
1259
+ types: list(oneOf("png", "jpeg"), { nonEmpty: true }),
1260
+ png: oneOf("name", "signature"),
1261
+ },
1262
+ twitter: { card: oneOf("summary_large_image", "any") },
1263
+ "json-ld-types": { types: typesByPath },
1264
+ "json-ld-breadcrumbs": {
1265
+ scope,
1266
+ nodes: oneOf("first", "all"),
1267
+ item: list(oneOf("url", "id"), { nonEmpty: true }),
1268
+ exactType: bool,
1269
+ nonArray: oneOf("skip", "iterate"),
1270
+ },
1271
+ "json-ld-article": { scope },
1272
+ "json-ld-posting": { scope },
1273
+ "json-ld-organization": { name: text, scope },
1274
+ "robots-sitemap": { match: oneOf("loose", "trimmed", "anchored", "exact", "field") },
1275
+ "robots-crawlers": {
1276
+ crawlers: list(text),
1277
+ allow: oneOf(false, "first", "all"),
1278
+ case: oneOf("exact", "insensitive"),
1279
+ agents: oneOf("groups", "lines"),
1280
+ groupRules: oneOf("all", "directives", "allow-disallow"),
1281
+ },
1282
+ "robots-no-disallow": { match: oneOf("lines", "groups") },
1283
+ llms: {
1284
+ first: oneOf("line", "non-empty"),
1285
+ title: (value, path) => {
1286
+ if (typeof value !== "string") {
1287
+ text(value, path);
1288
+ }
1289
+ },
1290
+ nonEmpty: bool,
1291
+ },
1292
+ "llms-summary": { position: oneOf("second", "any"), nonEmpty: bool },
1293
+ "llms-links": { scope, links: list(url), form: oneOf("markdown", "parens"), minPages: count },
1294
+ "markdown-clean": { files: list(text), tables: oneOf("line-start", "anywhere") },
1295
+ "markdown-copy": { scope },
1296
+ "markdown-heading": { scope, ogTitle: scope },
1297
+ "markdown-alternate": { scope },
1298
+ "redirects-permanent": { needsDestination: bool },
1299
+ "headers-noindex": { patterns: list(text), urls: list(url) },
1300
+ "headers-markdown": { scope },
1153
1301
  };