@uxfront/site-checks 0.0.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/index.d.ts ADDED
@@ -0,0 +1,362 @@
1
+ /**
2
+ * Where a page's tags are read: `head` (everything before `</head>`, or the whole page without
3
+ * one), `head-element` (the `<head>` element, or nothing without one), `document`, or `markup`
4
+ * (the document without its `<script>` elements and comments).
5
+ */
6
+ export type Scope = "head" | "head-element" | "document" | "markup";
7
+
8
+ /** An entity the parser decodes: `numeric` for every `&#…;` and `&#x…;`, or a name like `amp` or `#x27`. */
9
+ export type Entity = "numeric" | "amp" | "lt" | "gt" | "quot" | "apos" | `#${string}`;
10
+
11
+ /**
12
+ * How a page and the site's files are read. Every rule reads through it, so a site's profile
13
+ * reads its HTML exactly as its own checker did. The README gives each setting's values.
14
+ */
15
+ export interface ParseProfile {
16
+ /** Where `<meta>` and `<link>` tags are read. Defaults to `document`. */
17
+ scope?: Scope;
18
+ /** Where `<title>` is read. Defaults to `head`. */
19
+ titleScope?: Scope;
20
+ /**
21
+ * The `<title>` elements read: `any` (attributes and any text), `plain-text` (attributes, and
22
+ * text without a `<`) or `bare` (no attributes, and text without a `<`). Defaults to `any`.
23
+ */
24
+ titleTag?: "any" | "plain-text" | "bare";
25
+ /** When a title is trimmed: `after-decode`, `before-decode` or `none`. Defaults to `after-decode`. */
26
+ trimTitle?: "after-decode" | "before-decode" | "none";
27
+ /** The attribute values read: `any` (double, single or no quotes) or `double` only. */
28
+ quotes?: "any" | "double";
29
+ /** Whether tag names match in lower case only, so `<META>` isn't a `<meta>`. Defaults to `false`. */
30
+ caseSensitiveTags?: boolean;
31
+ /**
32
+ * What ends a tag's name: `word` (a word boundary, so `<meta-card>` reads as a `<meta>`) or
33
+ * `space` (a space, `/` or `>`). Defaults to `word`.
34
+ */
35
+ tagEnd?: "word" | "space";
36
+ /**
37
+ * How a `<meta>` is found by key: `name-or-property` (either attribute), or `property-first`
38
+ * (its `property`, or else its `name`, leaving out a tag with no `content`).
39
+ */
40
+ metaKey?: "name-or-property" | "property-first";
41
+ /** Whether `<meta>` `content` and `<html lang>` values are trimmed. Defaults to `false`. */
42
+ trimValues?: boolean;
43
+ /** The entities decoded in attribute values, titles and sitemap URLs. */
44
+ decode?: ReadonlyArray<Entity>;
45
+ /**
46
+ * `one-pass` decodes each reference once, so `&amp;lt;` stays `&lt;`. `numeric-first` decodes
47
+ * numeric references before named ones, so `&#38;lt;` becomes `<`.
48
+ */
49
+ decodeOrder?: "one-pass" | "numeric-first";
50
+ /** Whether named entities decode in any case, like `&AMP;`. Defaults to `false`. */
51
+ decodeIgnoreCase?: boolean;
52
+ /** The units of a length: `code-points`, or `utf-16` code units like `String.length`. */
53
+ count?: "code-points" | "utf-16";
54
+ /**
55
+ * Where `<h1>` is counted: `anywhere`, `markup` (outside `<script>` and comments), or `rendered`
56
+ * (outside `<script>`, `<style>`, `<template>` and comments).
57
+ */
58
+ h1?: "anywhere" | "markup" | "rendered";
59
+ /**
60
+ * The JSON-LD nodes of a block: `graph-or-block` (the `@graph` members, or else the block),
61
+ * `block-and-graph` (the block and its `@graph` members), `all` (the block and its `@graph`
62
+ * members, recursively, arrays flattened) or `graph-deep` (the `@graph` members, recursively,
63
+ * or else the block, arrays flattened).
64
+ */
65
+ nodes?: "graph-or-block" | "block-and-graph" | "all" | "graph-deep";
66
+ /** Whether an array `@type` matches any of its members. */
67
+ typeArrays?: boolean;
68
+ /**
69
+ * The `<script>` elements read as JSON-LD: `exact` (`type="application/ld+json"`) or
70
+ * `prefix-any-case` (a `type` that starts with it, in any case). Defaults to `exact`.
71
+ */
72
+ jsonLdType?: "exact" | "prefix-any-case";
73
+ /**
74
+ * The lines of `llms.txt` that count as blank: `whitespace` (only spaces), or `empty` (nothing,
75
+ * so a CRLF file's `\r` counts as text). Defaults to `whitespace`.
76
+ */
77
+ blankLines?: "whitespace" | "empty";
78
+ /** Whether `<loc>` and `<lastmod>` values are trimmed. Defaults to `true`. */
79
+ trimSitemap?: boolean;
80
+ /** Whether a `<loc>` listed twice is checked once. Defaults to `false`. */
81
+ mergeDuplicateLocs?: boolean;
82
+ /**
83
+ * How `_headers` is read: `lines` (line by line, skipping `#` lines and the spaces at each
84
+ * line's ends) or `blocks` (each unindented line and the indented lines after it as one rule,
85
+ * where a `#` line is a rule of its own and a line that ends in `\r` isn't a header).
86
+ * Defaults to `lines`.
87
+ */
88
+ headersParser?: "lines" | "blocks";
89
+ }
90
+
91
+ /**
92
+ * What takes a page out of the index, for `sitemap-indexable` and `sitemap-coverage`.
93
+ *
94
+ * - `meta`: a `<meta>` named one of `names` whose `content` holds one of `values`. With
95
+ * `property`, a tag is found as the profile finds any `<meta>`, by `name` or `property`. With
96
+ * `anyCaseNames`, its `name` matches in any case. `scope` overrides the profile's.
97
+ * - `refresh`: a `<meta http-equiv="refresh">`.
98
+ * - `files`: the page's file is one of these paths in `dist`, like `404.html`.
99
+ * - `under`: the page's file is under one of these folders in `dist`, like `raw/`.
100
+ * - `redirects`: a `_redirects` rule starts at the page's path.
101
+ * - `headers`: a `_headers` rule sends an `X-Robots-Tag` that holds one of `values`. `hosts` says
102
+ * how rules with a host match: `ignore` them, `match` the host as Cloudflare does, or `drop` the
103
+ * host and match the path alone, reading only the last `X-Robots-Tag` of a rule.
104
+ */
105
+ export type IndexSource =
106
+ | {
107
+ type: "meta";
108
+ names: ReadonlyArray<string>;
109
+ /** Defaults to `["noindex"]`. */
110
+ values?: ReadonlyArray<string>;
111
+ /** Match whole words only. */
112
+ word?: boolean;
113
+ caseSensitive?: boolean;
114
+ property?: boolean;
115
+ anyCaseNames?: boolean;
116
+ scope?: Scope;
117
+ }
118
+ | { type: "refresh" }
119
+ | { type: "files"; files: ReadonlyArray<string> }
120
+ | { type: "under"; paths: ReadonlyArray<string> }
121
+ | { type: "redirects" }
122
+ | {
123
+ type: "headers";
124
+ hosts: "ignore" | "match" | "drop";
125
+ /** Defaults to `["noindex"]`. */
126
+ values?: ReadonlyArray<string>;
127
+ word?: boolean;
128
+ };
129
+
130
+ /**
131
+ * A set of site paths: `*` for every page, a path ending in `*` for every page under it, like
132
+ * `/docs/*`, or an exact path, like `/`.
133
+ */
134
+ export type PathPattern = string;
135
+
136
+ /** A rule that takes no options, only `true` or `false`. */
137
+ export type NoOptions = Record<string, never>;
138
+
139
+ /** The options of each rule. `true` turns a rule on with its defaults, `false` turns it off. */
140
+ export interface RuleOptions {
141
+ sitemap: NoOptions;
142
+ "sitemap-host": NoOptions;
143
+ "sitemap-duplicates": NoOptions;
144
+ lastmod: {
145
+ /** `loose`, `date` (`YYYY-MM-DD`) or `w3c`. Defaults to `w3c`. */
146
+ format?: "loose" | "date" | "w3c";
147
+ /** How a value is checked as a date. Defaults to `none`. */
148
+ realDate?: "none" | "date-only" | "parseable";
149
+ };
150
+ "lastmod-future": { skewHours?: number };
151
+ "sitemap-pages": {
152
+ /** How a `<loc>` maps to a file. Defaults to `exact`. */
153
+ paths?: "lookup" | "exact" | "exact-slash";
154
+ /** Fail a page whose file is the same text as `404.html`. */
155
+ notFoundCopy?: boolean;
156
+ };
157
+ "sitemap-indexable": { sources?: ReadonlyArray<IndexSource> };
158
+ "sitemap-coverage": {
159
+ /** The files left out of the sitemap on purpose. Defaults to `sitemap-indexable`'s `sources`. */
160
+ exclude?: ReadonlyArray<IndexSource>;
161
+ };
162
+ title: { max?: number; exactlyOne?: boolean; nonEmpty?: boolean };
163
+ "title-unique": NoOptions;
164
+ description: { min?: number; max?: number; exactlyOne?: boolean };
165
+ "description-unique": NoOptions;
166
+ h1: NoOptions;
167
+ canonical: {
168
+ exactlyOne?: boolean;
169
+ /** `exact`, `exact-any-case` or `token`. */
170
+ rel?: "token" | "exact" | "exact-any-case";
171
+ /** Whether a canonical link with no `href` counts. */
172
+ requireHref?: boolean;
173
+ };
174
+ lang: {
175
+ /** The value `lang` must have. Set it to `false` to accept any value. Defaults to `"en"`. */
176
+ lang?: string | false;
177
+ };
178
+ "open-graph": { url?: "loc" | "canonical" };
179
+ "og-image-alt": NoOptions;
180
+ "meta-conflicts": { keys?: ReadonlyArray<string> };
181
+ "og-image-host": NoOptions;
182
+ "og-image-size-tags": { onHostOnly?: boolean };
183
+ "og-image-file": {
184
+ types?: ReadonlyArray<"png" | "jpeg">;
185
+ /** How a PNG is told apart: `name` (bytes 1 to 3 spell `PNG`) or `signature` (all 8). */
186
+ png?: "name" | "signature";
187
+ };
188
+ twitter: { card?: "summary_large_image" | "any" };
189
+ "twitter-text": NoOptions;
190
+ "json-ld-parse": NoOptions;
191
+ "json-ld-present": NoOptions;
192
+ "json-ld-context": NoOptions;
193
+ "json-ld-ids": NoOptions;
194
+ "json-ld-types": { types?: Readonly<Record<PathPattern, ReadonlyArray<string>>> };
195
+ "json-ld-breadcrumbs": {
196
+ scope?: ReadonlyArray<PathPattern>;
197
+ nodes?: "first" | "all";
198
+ item?: ReadonlyArray<"url" | "id">;
199
+ /** Whether a `BreadcrumbList` must have exactly that `@type`, whatever `typeArrays` says. */
200
+ exactType?: boolean;
201
+ /** What an `itemListElement` that isn't a list does: `skip`, or `iterate` it, failing when it can't. */
202
+ nonArray?: "skip" | "iterate";
203
+ };
204
+ "json-ld-article": { scope?: ReadonlyArray<PathPattern> };
205
+ "json-ld-posting": { scope?: ReadonlyArray<PathPattern> };
206
+ "json-ld-organization": {
207
+ /** The name no `Organization` may have, like `"Unframework"`. It has no default. */
208
+ name: string;
209
+ scope?: ReadonlyArray<PathPattern>;
210
+ };
211
+ "robots-sitemap": { match?: "loose" | "trimmed" | "anchored" | "exact" | "field" };
212
+ "robots-crawlers": {
213
+ crawlers?: ReadonlyArray<string>;
214
+ allow?: false | "first" | "all";
215
+ case?: "exact" | "insensitive";
216
+ /** Where agent names are read: `groups`, or every `User-agent` line as it is, `lines`. */
217
+ agents?: "groups" | "lines";
218
+ /** Which lines end a group's run of agents: `all`, `directives` or `allow-disallow`. */
219
+ groupRules?: "all" | "directives" | "allow-disallow";
220
+ };
221
+ "robots-no-disallow": { match?: "lines" | "groups" };
222
+ "robots-wildcard": NoOptions;
223
+ "robots-directives": NoOptions;
224
+ llms: { first?: "line" | "non-empty"; title?: string; nonEmpty?: boolean };
225
+ "llms-summary": { position?: "second" | "any"; nonEmpty?: boolean };
226
+ "llms-links": {
227
+ scope?: ReadonlyArray<PathPattern>;
228
+ links?: ReadonlyArray<string>;
229
+ form?: "markdown" | "parens";
230
+ minPages?: number;
231
+ };
232
+ "llms-docs-section": NoOptions;
233
+ "llms-full": NoOptions;
234
+ "markdown-clean": { files?: ReadonlyArray<string>; tables?: "line-start" | "anywhere" };
235
+ "markdown-copy": { scope?: ReadonlyArray<PathPattern> };
236
+ "markdown-heading": { scope?: ReadonlyArray<PathPattern>; ogTitle?: ReadonlyArray<PathPattern> };
237
+ "markdown-alternate": { scope?: ReadonlyArray<PathPattern> };
238
+ "redirects-permanent": {
239
+ /** Whether a rule with no destination is left out. */
240
+ needsDestination?: boolean;
241
+ };
242
+ "headers-noindex": { patterns?: ReadonlyArray<string>; urls?: ReadonlyArray<string> };
243
+ "headers-duplicates": NoOptions;
244
+ "headers-markdown": { scope?: ReadonlyArray<PathPattern> };
245
+ "not-found": NoOptions;
246
+ }
247
+
248
+ export type RuleId = keyof RuleOptions;
249
+
250
+ export type RuleSetting<Id extends RuleId> = RuleOptions[Id] extends NoOptions
251
+ ? boolean
252
+ : boolean | RuleOptions[Id];
253
+
254
+ export type Rules = {
255
+ [Id in Exclude<RuleId, "json-ld-organization">]?: RuleSetting<Id>;
256
+ } & {
257
+ /** It needs a `name`, so it takes `false` or its options, not `true`. */
258
+ "json-ld-organization"?: false | RuleOptions["json-ld-organization"];
259
+ };
260
+
261
+ /** A page the checks read: a `<loc>` of the sitemap, or a path in `pages`, and its file. */
262
+ export interface CheckedPage {
263
+ /** The page's URL, like `https://uxfront.com/docs/`. */
264
+ readonly loc: string;
265
+ /** The URL's path, like `/docs/`. */
266
+ readonly path: string;
267
+ /** The file's path in `dist`, like `docs/index.html`. */
268
+ readonly file: string;
269
+ readonly html: string;
270
+ /** The `content` of every `<meta>` whose `name` or `property` is `key`, in order. */
271
+ meta(key: string): Array<string>;
272
+ /** The `<title>` elements' text, decoded and trimmed. */
273
+ readonly titles: ReadonlyArray<string>;
274
+ /** The JSON-LD nodes of the page, read as the profile's `nodes` says. */
275
+ // oxlint-disable-next-line quality/no-unsafe-dictionary-type -- a page's JSON-LD can hold any schema.org type
276
+ readonly nodes: ReadonlyArray<Record<string, unknown>>;
277
+ }
278
+
279
+ /** A `<url>` of `sitemap.xml`. */
280
+ export interface SitemapEntry {
281
+ /** The decoded `<loc>`, or an empty string. */
282
+ readonly loc: string;
283
+ readonly lastmod: string | undefined;
284
+ }
285
+
286
+ /** What an extra rule gets: the parsed site and a way to report problems. */
287
+ export interface RuleContext {
288
+ readonly site: string;
289
+ readonly dist: string;
290
+ readonly pages: ReadonlyArray<CheckedPage>;
291
+ readonly sitemap: ReadonlyArray<SitemapEntry>;
292
+ /** A file in `dist` as text, or `undefined` when it doesn't exist. */
293
+ read: (file: string) => string | undefined;
294
+ /** The headers `_headers` gives a URL, as Cloudflare matches it, with lower-case names. */
295
+ headersFor: (url: string) => Array<[name: string, value: string]>;
296
+ /** Reports a problem with a page's path or a file's name. */
297
+ report: (target: string, message: string) => void;
298
+ }
299
+
300
+ /** A rule a site adds for itself, run and reported like the others. */
301
+ export interface ExtraRule {
302
+ id: string;
303
+ check: (context: RuleContext) => void;
304
+ }
305
+
306
+ export interface CheckOptions {
307
+ /** The production origin, like `https://uxfront.com`. */
308
+ site: string;
309
+ /** The build folder. */
310
+ dist: string;
311
+ /** Site paths to check, like `/` and `/docs/`. Defaults to every `<loc>` in `sitemap.xml`. */
312
+ pages?: ReadonlyArray<string>;
313
+ parse?: ParseProfile;
314
+ rules?: Rules;
315
+ extraRules?: ReadonlyArray<ExtraRule>;
316
+ /** The time `lastmod-future` compares with. Defaults to now. */
317
+ now?: Date;
318
+ }
319
+
320
+ /** The options a config file exports: everything but `dist`, which the CLI takes. */
321
+ export type SiteChecksConfig = Omit<CheckOptions, "dist">;
322
+
323
+ export interface Problem {
324
+ /** A page's path, or a file's name. */
325
+ target: string;
326
+ message: string;
327
+ }
328
+
329
+ export interface RuleResult {
330
+ id: string;
331
+ problems: Array<Problem>;
332
+ }
333
+
334
+ export interface Report {
335
+ /** Every rule that ran, in order, with its problems. */
336
+ rules: Array<RuleResult>;
337
+ /** The number of pages checked. */
338
+ pages: number;
339
+ /** The number of problems in all rules. */
340
+ problems: number;
341
+ }
342
+
343
+ /** The nine AI search and assistant crawlers `robots-crawlers` checks by default, like `GPTBot`. */
344
+ export declare const AI_CRAWLERS: ReadonlyArray<string>;
345
+
346
+ /** The 51 rule IDs, in order. */
347
+ export declare const RULE_IDS: ReadonlyArray<RuleId>;
348
+
349
+ /** The 20 rules that run when a config doesn't name them. */
350
+ export declare const CORE_RULES: ReadonlyArray<RuleId>;
351
+
352
+ /** The parsing profile a config gets when it doesn't set `parse`. */
353
+ export declare const DEFAULT_PARSE: Readonly<Required<ParseProfile>>;
354
+
355
+ /** Reads a built site and checks it. Throws on options it can't use, like an unknown rule ID. */
356
+ export declare function checkSeo(options: CheckOptions): Report;
357
+
358
+ /** One line per rule, `✓ <id>` or `✗ <id>` with its problems under it, then a summary. */
359
+ export declare function formatReport(report: Report): string;
360
+
361
+ /** Returns its argument, typed, for a config file. */
362
+ export declare function defineConfig(config: SiteChecksConfig): SiteChecksConfig;
package/index.js ADDED
@@ -0,0 +1,10 @@
1
+ export { AI_CRAWLERS } from "./lib/rules.js";
2
+ export { CORE_RULES, DEFAULT_PARSE, RULE_IDS, checkSeo, formatReport } from "./lib/check.js";
3
+
4
+ /** @import { SiteChecksConfig } from "./index.js" */
5
+
6
+ /**
7
+ * Returns its argument, typed, for a config file.
8
+ * @param {SiteChecksConfig} config
9
+ */
10
+ export const defineConfig = (config) => config;
package/lib/check.js ADDED
@@ -0,0 +1,260 @@
1
+ import { RULES, SCHEMAS } from "./rules.js";
2
+ import { Site } from "./site.js";
3
+ import { PARSE, isPlainObject, list, pattern } from "./validate.js";
4
+
5
+ /** @import { CheckOptions, ParseProfile, Problem, Report, RuleId, RuleOptions } from "../index.js" */
6
+ /** @import { Page } from "./site.js" */
7
+
8
+ /** @type {Readonly<Required<ParseProfile>>} */
9
+ export const DEFAULT_PARSE = Object.freeze({
10
+ scope: "document",
11
+ titleScope: "head",
12
+ titleTag: "any",
13
+ trimTitle: "after-decode",
14
+ quotes: "any",
15
+ caseSensitiveTags: false,
16
+ tagEnd: "word",
17
+ metaKey: "name-or-property",
18
+ trimValues: false,
19
+ decode: Object.freeze(/** @type {const} */ (["numeric", "quot", "apos", "lt", "gt", "amp"])),
20
+ decodeOrder: "one-pass",
21
+ decodeIgnoreCase: false,
22
+ count: "utf-16",
23
+ h1: "anywhere",
24
+ nodes: "graph-or-block",
25
+ typeArrays: true,
26
+ jsonLdType: "exact",
27
+ blankLines: "whitespace",
28
+ trimSitemap: true,
29
+ mergeDuplicateLocs: false,
30
+ headersParser: "lines",
31
+ });
32
+
33
+ /** @type {readonly RuleId[]} */
34
+ export const RULE_IDS = Object.freeze(RULES.map((rule) => rule.id));
35
+
36
+ /** @type {readonly RuleId[]} */
37
+ export const CORE_RULES = Object.freeze(RULES.filter((rule) => rule.core).map((rule) => rule.id));
38
+
39
+ /**
40
+ * The options of every rule, with the defaults filled in, and whether it runs. Throws on an
41
+ * unknown rule, an unknown option or a value an option doesn't take.
42
+ * @param {CheckOptions["rules"]} rules
43
+ */
44
+ function resolveRules(rules = {}) {
45
+ if (!isPlainObject(rules)) {
46
+ throw new TypeError("rules must be an object of rule IDs");
47
+ }
48
+ for (const id of Object.keys(rules)) {
49
+ if (!RULE_IDS.some((ruleId) => ruleId === id)) {
50
+ throw new Error(`Unknown rule "${id}". The rules are: ${RULE_IDS.join(", ")}`);
51
+ }
52
+ }
53
+ /** @type {Map<RuleId, { enabled: boolean, options: Record<string, unknown> }>} */
54
+ const resolved = new Map();
55
+ for (const rule of RULES) {
56
+ const setting = /** @type {Record<string, unknown>} */ (rules)[rule.id];
57
+ if (setting !== undefined && typeof setting !== "boolean" && !isPlainObject(setting)) {
58
+ throw new TypeError(
59
+ `rules["${rule.id}"] must be true, false or an object of options, not ${JSON.stringify(setting)}`,
60
+ );
61
+ }
62
+ const given = isPlainObject(setting) ? setting : {};
63
+ const schema = SCHEMAS[rule.id] ?? {};
64
+ for (const [key, value] of Object.entries(given)) {
65
+ const check = schema[key];
66
+ if (!check) {
67
+ const known = Object.keys(schema);
68
+ throw new Error(
69
+ `Rule "${rule.id}" has no option "${key}"${known.length ? `. Its options are: ${known.join(", ")}` : ". It takes no options"}`,
70
+ );
71
+ }
72
+ check(value, `rules["${rule.id}"].${key}`);
73
+ }
74
+ const enabled = setting === undefined ? rule.core : setting !== false;
75
+ if (rule.id === "json-ld-organization" && enabled && !given.name) {
76
+ throw new TypeError(
77
+ 'rules["json-ld-organization"] needs a name, like { name: "Unframework" }',
78
+ );
79
+ }
80
+ resolved.set(rule.id, { enabled, options: { ...rule.defaults, ...given } });
81
+ }
82
+ // Pages left out of the sitemap on purpose are, by default, the ones out of the index.
83
+ const coverage = resolved.get("sitemap-coverage");
84
+ const given = /** @type {Record<string, unknown>} */ (rules)["sitemap-coverage"];
85
+ if (coverage && !(isPlainObject(given) && "exclude" in given)) {
86
+ coverage.options.exclude = resolved.get("sitemap-indexable")?.options.sources;
87
+ }
88
+ return resolved;
89
+ }
90
+
91
+ /** @param {unknown} error */
92
+ const messageOf = (error) => (error instanceof Error ? error.message : String(error));
93
+
94
+ /** @param {CheckOptions} options @returns {Report} */
95
+ export function checkSeo(options) {
96
+ if (!isPlainObject(options)) {
97
+ throw new TypeError("checkSeo takes an object of options");
98
+ }
99
+ const { site: origin, dist, pages: only, parse = {}, rules, extraRules = [], now } = options;
100
+ if (typeof origin !== "string" || !/^https?:\/\/[^/]+\/?$/.test(origin)) {
101
+ throw new TypeError(
102
+ `site must be an origin, like "https://uxfront.com", not ${JSON.stringify(origin)}`,
103
+ );
104
+ }
105
+ if (typeof dist !== "string" || !dist) {
106
+ throw new TypeError("dist must be the build folder");
107
+ }
108
+ if (!isPlainObject(parse)) {
109
+ throw new TypeError("parse must be an object of settings");
110
+ }
111
+ for (const [key, value] of Object.entries(parse)) {
112
+ const check = PARSE[key];
113
+ if (!check) {
114
+ throw new Error(
115
+ `parse has no option "${key}". Its options are: ${Object.keys(PARSE).join(", ")}`,
116
+ );
117
+ }
118
+ check(value, `parse.${key}`);
119
+ }
120
+ if (only !== undefined) {
121
+ list(pattern, { nonEmpty: true })(only, "pages");
122
+ }
123
+ // oxlint-disable-next-line @nkzw/no-instanceof -- now comes from a config, and only a Date has getTime
124
+ if (now !== undefined && !(now instanceof Date && !Number.isNaN(now.getTime()))) {
125
+ throw new TypeError("now must be a Date");
126
+ }
127
+ const profile = /** @type {Required<ParseProfile>} */ ({ ...DEFAULT_PARSE, ...parse });
128
+ const resolved = resolveRules(rules);
129
+ if (!Array.isArray(extraRules)) {
130
+ throw new TypeError("extraRules must be a list");
131
+ }
132
+ const extraIds = new Set();
133
+ for (const extra of extraRules) {
134
+ if (!extra || typeof extra.id !== "string" || !extra.id || typeof extra.check !== "function") {
135
+ throw new TypeError("Each extra rule needs an id and a check function");
136
+ }
137
+ if (RULE_IDS.some((id) => id === extra.id) || extraIds.has(extra.id)) {
138
+ throw new Error(`Two rules have the ID "${extra.id}"`);
139
+ }
140
+ extraIds.add(extra.id);
141
+ }
142
+
143
+ /** @template {RuleId} Id @param {Id} id */
144
+ const optionsOf = (id) =>
145
+ // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- resolveRules checked them
146
+ /** @type {Required<RuleOptions[Id]>} */ (/** @type {unknown} */ (resolved.get(id)?.options));
147
+ const pageOptions = optionsOf("sitemap-pages");
148
+ const site = new Site({
149
+ site: origin,
150
+ dist,
151
+ profile,
152
+ paths: pageOptions.paths,
153
+ now: now ?? new Date(),
154
+ });
155
+
156
+ // The pages the page rules read: each `<loc>` served from an HTML file, or each path in `pages`.
157
+ const notFound = site.read("404.html");
158
+ /** @type {{ loc: string, path: string }[]} */
159
+ let targets = only
160
+ ? only.map((path) => ({ loc: `${site.site}${path}`, path }))
161
+ : site.sitemap.entries.flatMap(({ loc, url }) => (url ? [{ loc, path: url.pathname }] : []));
162
+ if (profile.mergeDuplicateLocs) {
163
+ targets = [...new Map(targets.map((target) => [target.loc, target])).values()];
164
+ }
165
+ /** @type {Page[]} */
166
+ const pages = [];
167
+ /** @type {string[]} */
168
+ const missing = [];
169
+ for (const { loc, path } of targets) {
170
+ const file = site.resolve(path);
171
+ if (!file) {
172
+ if (only) {
173
+ missing.push(path);
174
+ }
175
+ continue;
176
+ }
177
+ if (pageOptions.notFoundCopy && notFound !== undefined && site.read(file) === notFound) {
178
+ continue;
179
+ }
180
+ pages.push(site.page(loc, path, file));
181
+ }
182
+ // A path in `pages` with no file is a problem of sitemap-pages, so it never passes quietly.
183
+ if (missing.length && !resolved.get("sitemap-pages")?.enabled) {
184
+ throw new Error(
185
+ `pages has paths with no HTML file in dist, ${missing.join(", ")}, and sitemap-pages, which reports them, is off`,
186
+ );
187
+ }
188
+
189
+ /** @type {Report["rules"]} */
190
+ const results = [];
191
+ /** @param {string} id @param {(report: (target: string, message: string) => void) => void} run */
192
+ const record = (id, run) => {
193
+ /** @type {Problem[]} */
194
+ const problems = [];
195
+ const report = (/** @type {string} */ target, /** @type {string} */ message) =>
196
+ problems.push({ target: String(target), message: String(message) });
197
+ try {
198
+ run(report);
199
+ } catch (error) {
200
+ // A file the rule can't read, like a value no decoder can read, is a problem with the
201
+ // build, so the rule reports it and the other rules still run.
202
+ report("(the rule)", `couldn't finish: ${messageOf(error)}`);
203
+ }
204
+ results.push({ id, problems });
205
+ };
206
+ for (const rule of RULES) {
207
+ const setting = resolved.get(rule.id);
208
+ if (!setting?.enabled) {
209
+ continue;
210
+ }
211
+ record(rule.id, (report) => {
212
+ // RULES holds one Rule type per ID, so TypeScript can't call their union's run. resolveRules
213
+ // checked these options against this rule's schema.
214
+ // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- a union of run types takes no call
215
+ /** @type {(context: object, options: object) => void} */ (rule.run)(
216
+ { site, pages, optionsOf, report },
217
+ setting.options,
218
+ );
219
+ if (rule.id === "sitemap-pages") {
220
+ for (const path of missing) {
221
+ report(path, "a path in pages has no HTML file in dist");
222
+ }
223
+ }
224
+ });
225
+ }
226
+ for (const extra of extraRules) {
227
+ record(extra.id, (report) =>
228
+ extra.check({
229
+ site: site.site,
230
+ dist,
231
+ pages,
232
+ sitemap: site.sitemap.entries.map(({ loc, lastmod }) => ({ loc, lastmod })),
233
+ read: (/** @type {string} */ file) => site.read(file),
234
+ headersFor: (/** @type {string} */ url) => site.headersFor(url),
235
+ report,
236
+ }),
237
+ );
238
+ }
239
+ return {
240
+ rules: results,
241
+ pages: pages.length,
242
+ problems: results.reduce((sum, result) => sum + result.problems.length, 0),
243
+ };
244
+ }
245
+
246
+ /** @param {Report} report */
247
+ export function formatReport({ rules, pages, problems }) {
248
+ const lines = [];
249
+ for (const { id, problems: own } of rules) {
250
+ lines.push(`${own.length ? "✗" : "✓"} ${id}`);
251
+ for (const { target, message } of own) {
252
+ lines.push(` ${target}: ${message}`);
253
+ }
254
+ }
255
+ lines.push(
256
+ "",
257
+ `${pages} ${pages === 1 ? "page" : "pages"} checked, ${problems} ${problems === 1 ? "problem" : "problems"}`,
258
+ );
259
+ return lines.join("\n");
260
+ }