@v-office/site-checks 0.0.0 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1089 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { parseHTML } from "linkedom";
4
+ //#region src/checks/consentGate.ts
5
+ /** The consent kit's files in a site: its presence under `src/lib/consent/` is what makes the
6
+ * check apply; the vendors the site enables and the fleet registry's review of them. */
7
+ const KIT_DIR = "src/lib/consent/";
8
+ const ENABLED_FILE = "src/data/consent.ts";
9
+ const REGISTRY_FILE = "src/data/consent-registry.snapshot.json";
10
+ /** The kit's click-to-load frame (`ConsentEmbed.astro`): a third-party frame inside it loads after
11
+ * consent, so it is not a leak. */
12
+ const EMBED_TEMPLATE = "template[data-embed-content]";
13
+ const hostOf = (url) => {
14
+ try {
15
+ return new URL(url).host;
16
+ } catch {
17
+ return;
18
+ }
19
+ };
20
+ /** No third-party script or iframe loads outside the consent layer (the kit injects a vendor's
21
+ * script after consent, so one in the HTML loads before it), and no vendor the site enables is
22
+ * still unapproved in the fleet's consent registry. Skipped in a project without the kit. */
23
+ const consentGate = {
24
+ id: "consent-gate",
25
+ title: "Third-party resources wait for consent",
26
+ severity: "error",
27
+ begin: (ctx) => {
28
+ const sources = ctx.sourceFiles(/* @__PURE__ */ new Set([".ts", ".json"]));
29
+ const byRel = new Map(sources.map((file) => [ctx.rel(file), file]));
30
+ if (![...byRel.keys()].some((rel) => rel.startsWith(KIT_DIR))) return null;
31
+ const siteHost = ctx.config.site ? hostOf(ctx.config.site) : void 0;
32
+ const allowed = new Set(ctx.options.consentAllowedHosts);
33
+ const findings = [];
34
+ return {
35
+ visit: (page) => {
36
+ for (const el of page.document.querySelectorAll("script[src], iframe[src]")) {
37
+ const raw = (el.getAttribute("src") ?? "").trim();
38
+ const src = raw.startsWith("//") ? `https:${raw}` : raw;
39
+ if (!/^https?:\/\//i.test(src)) continue;
40
+ const host = hostOf(src);
41
+ if (!host || host === siteHost || allowed.has(host)) continue;
42
+ if (el.closest(EMBED_TEMPLATE)) continue;
43
+ findings.push({
44
+ path: page.path,
45
+ message: `A third-party <${el.tagName.toLowerCase()}> from ${host} loads before consent. Frame it with ConsentEmbed, or register the vendor so the kit injects it after consent; list a consent-free host in consentAllowedHosts.`
46
+ });
47
+ }
48
+ },
49
+ finish: () => {
50
+ const enabledFile = byRel.get(ENABLED_FILE);
51
+ const registryFile = byRel.get(REGISTRY_FILE);
52
+ if (!enabledFile || !registryFile) return findings;
53
+ const enabled = ctx.readSource(enabledFile).match(/ENABLED_VENDOR_IDS\b[^=]*=\s*\[([^\]]*)\]/);
54
+ if (!enabled) return findings;
55
+ const ids = [...enabled[1].matchAll(/["'`]([^"'`]+)["'`]/g)].map((m) => m[1]);
56
+ const registry = JSON.parse(ctx.readSource(registryFile));
57
+ const status = new Map((registry.vendors ?? []).map((v) => [v.id, v.reviewStatus]));
58
+ for (const id of ids) if (!status.has(id)) findings.push({
59
+ path: ENABLED_FILE,
60
+ message: `The enabled vendor "${id}" is not in the consent registry.`
61
+ });
62
+ else if (status.get(id) !== "approved") findings.push({
63
+ path: ENABLED_FILE,
64
+ message: `The enabled vendor "${id}" is "${status.get(id)}" in the consent registry, not approved.`
65
+ });
66
+ return findings;
67
+ }
68
+ };
69
+ }
70
+ };
71
+ //#endregion
72
+ //#region src/checks/donorTerms.ts
73
+ /** More than this and the point is made; the runner keeps 25 anyway. */
74
+ const MAX_RAW_FINDINGS = 100;
75
+ const normalize$2 = (text) => text.normalize("NFC").toLowerCase().replace(/\s+/g, " ");
76
+ const excerpt$1 = (haystack, term) => {
77
+ const at = haystack.indexOf(term);
78
+ const start = Math.max(0, at - 30);
79
+ const end = Math.min(haystack.length, at + term.length + 30);
80
+ return `${start > 0 ? "…" : ""}${haystack.slice(start, end)}${end < haystack.length ? "…" : ""}`;
81
+ };
82
+ /** Every site starts from a template ("donor") site, and nothing of it may ship: its brand, people,
83
+ * places, phone, email, domain, asset names. The site lists the terms in `site-checks.config.json`
84
+ * (`donorTerms`); without them the check skips, which the report shows. Matched in the visible
85
+ * text, the title, the inline scripts and styles (JSON-LD shows in search results) and the
86
+ * attributes of every built page, in the built file names and in the shipped JS and CSS, where an
87
+ * island's copy lives. */
88
+ const donorTerms = {
89
+ id: "donor-terms",
90
+ title: "Terms of the template site in the built output",
91
+ severity: "error",
92
+ begin: (ctx) => {
93
+ const terms = [...new Set(ctx.options.donorTerms.map(normalize$2).filter(Boolean))];
94
+ if (terms.length === 0 || !ctx.hasDist) return null;
95
+ const findings = [];
96
+ /** One finding per term and place: the first text of `texts` that contains it. */
97
+ const scan = (texts, path, where) => {
98
+ for (const term of terms) {
99
+ if (findings.length >= MAX_RAW_FINDINGS) return;
100
+ const hit = texts.map(normalize$2).find((haystack) => haystack.includes(term));
101
+ if (hit !== void 0) findings.push({
102
+ path,
103
+ message: `donor term "${term}" in ${where}: "${excerpt$1(hit, term)}"`
104
+ });
105
+ }
106
+ };
107
+ return {
108
+ visit: (page) => {
109
+ scan([page.visibleText()], page.path, "the visible text");
110
+ scan(page.attributeValues(), page.path, "an attribute");
111
+ scan([...page.document.querySelectorAll("title, script:not([src]), style")].map((el) => el.textContent ?? ""), page.path, "the title or inline code");
112
+ },
113
+ finish: () => {
114
+ for (const file of ctx.files) {
115
+ scan([file], file, "a file name");
116
+ if (/\.(m?js|css)$/.test(file)) scan([ctx.read(file)], file, "shipped code");
117
+ }
118
+ return findings;
119
+ }
120
+ };
121
+ }
122
+ };
123
+ //#endregion
124
+ //#region src/checks/htmlComments.ts
125
+ /** Astro passes an HTML comment in a template straight into the built page, where a visitor reads
126
+ * it with View Source. Markdown pages too. */
127
+ const SOURCE_EXTENSIONS$1 = /* @__PURE__ */ new Set([
128
+ ".astro",
129
+ ".tsx",
130
+ ".jsx",
131
+ ".md",
132
+ ".mdx",
133
+ ".html"
134
+ ]);
135
+ const MESSAGE = "An HTML comment ships to the built page, readable with View Source. Use {/* … */} in .astro and JSX markup, // in frontmatter, and remove it from Markdown.";
136
+ const htmlComments = {
137
+ id: "html-comments",
138
+ title: "HTML comments in the source",
139
+ severity: "error",
140
+ begin: (ctx) => ({ finish: () => {
141
+ const findings = [];
142
+ for (const file of ctx.sourceFiles(SOURCE_EXTENSIONS$1)) {
143
+ const text = ctx.readSource(file);
144
+ let index = text.indexOf("<!--");
145
+ while (index !== -1) {
146
+ const line = text.slice(0, index).split("\n").length;
147
+ findings.push({
148
+ path: `${ctx.rel(file)}:${line}`,
149
+ message: MESSAGE
150
+ });
151
+ index = text.indexOf("<!--", index + 4);
152
+ }
153
+ }
154
+ return findings;
155
+ } })
156
+ };
157
+ //#endregion
158
+ //#region src/context.ts
159
+ const SKIPPED_TEXT_TAGS = /* @__PURE__ */ new Set([
160
+ "SCRIPT",
161
+ "STYLE",
162
+ "NOSCRIPT",
163
+ "TEMPLATE"
164
+ ]);
165
+ const collectFiles = (dir, base = dir) => fs.readdirSync(dir, { withFileTypes: true }).flatMap((entry) => {
166
+ const full = path.join(dir, entry.name);
167
+ return entry.isDirectory() ? collectFiles(full, base) : [path.relative(base, full).split(path.sep).join("/")];
168
+ });
169
+ function* filesUnder(dir, extensions) {
170
+ if (!fs.existsSync(dir)) return;
171
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
172
+ const full = path.join(dir, entry.name);
173
+ if (entry.isDirectory()) {
174
+ if (entry.name !== "node_modules") yield* filesUnder(full, extensions);
175
+ } else if (extensions.has(path.extname(entry.name).toLowerCase())) yield full;
176
+ }
177
+ }
178
+ /** `about-us/index.html` → `/about-us/`, `imprint.html` → `/imprint`, `index.html` → `/`. */
179
+ const fileToUrl = (file) => {
180
+ if (file === "index.html") return "/";
181
+ if (file.endsWith("/index.html")) return `/${file.slice(0, -10)}`;
182
+ if (file.endsWith(".html")) return `/${file.slice(0, -5)}`;
183
+ return `/${file}`;
184
+ };
185
+ const textOf = (node) => {
186
+ let text = "";
187
+ for (const child of node.childNodes) if (child.nodeType === 3) text += child.textContent ?? "";
188
+ else if (child.nodeType === 1) {
189
+ const el = child;
190
+ if (!SKIPPED_TEXT_TAGS.has(el.tagName)) text += ` ${textOf(el)} `;
191
+ }
192
+ return text;
193
+ };
194
+ const commentsOf = (node, into) => {
195
+ for (const child of node.childNodes) if (child.nodeType === 8) into.push(child.textContent ?? "");
196
+ else if (child.nodeType === 1) commentsOf(child, into);
197
+ };
198
+ const readPackageJson = (root) => {
199
+ const file = path.join(root, "package.json");
200
+ if (!fs.existsSync(file)) return {
201
+ dependencies: {},
202
+ devDependencies: {}
203
+ };
204
+ const pkg = JSON.parse(fs.readFileSync(file, "utf8"));
205
+ return {
206
+ dependencies: pkg.dependencies ?? {},
207
+ devDependencies: pkg.devDependencies ?? {}
208
+ };
209
+ };
210
+ /** Lists `distDir` once. Throws when it cannot be read: the runner fails every check then. */
211
+ const loadBuildOutput = (distDir) => {
212
+ const files = collectFiles(distDir).sort();
213
+ const fileSet = new Set(files);
214
+ const serves = (urlPath) => {
215
+ let p = urlPath.split(/[?#]/, 1)[0] ?? "";
216
+ try {
217
+ p = decodeURIComponent(p);
218
+ } catch {}
219
+ p = p.replace(/^\/+/, "");
220
+ if (p === "") return fileSet.has("index.html");
221
+ if (p.endsWith("/")) return fileSet.has(`${p}index.html`);
222
+ return fileSet.has(p) || fileSet.has(`${p}/index.html`) || fileSet.has(`${p}.html`);
223
+ };
224
+ return {
225
+ distDir,
226
+ files,
227
+ has: (file) => fileSet.has(file),
228
+ read: (file) => fs.readFileSync(path.join(distDir, file), "utf8"),
229
+ serves
230
+ };
231
+ };
232
+ /** No `dist/`: no files, nothing served. */
233
+ const noBuildOutput = (distDir) => ({
234
+ distDir,
235
+ files: [],
236
+ has: () => false,
237
+ read: (file) => {
238
+ throw new Error(`No built output to read ${file} from`);
239
+ },
240
+ serves: () => false
241
+ });
242
+ const loadDistContext = (distDir, opts) => ({
243
+ ...loadBuildOutput(distDir),
244
+ isAstro: opts.isAstro,
245
+ origin: opts.siteUrl ? new URL(opts.siteUrl).origin : void 0
246
+ });
247
+ const loadContext = (input) => {
248
+ const { root, srcDir, publicDir, distDir, config, options } = input;
249
+ const hasDist = fs.existsSync(distDir);
250
+ return {
251
+ ...hasDist ? loadBuildOutput(distDir) : noBuildOutput(distDir),
252
+ root,
253
+ srcDir,
254
+ publicDir,
255
+ hasDist,
256
+ config,
257
+ options,
258
+ sourceFiles: (extensions) => [...filesUnder(srcDir, extensions)].sort(),
259
+ readSource: (absolute) => fs.readFileSync(absolute, "utf8"),
260
+ rel: (absolute) => path.relative(root, absolute).split(path.sep).join("/"),
261
+ packageJson: readPackageJson(root)
262
+ };
263
+ };
264
+ const readPage = (ctx, file) => {
265
+ const url = fileToUrl(file);
266
+ const { document } = parseHTML(ctx.read(file));
267
+ const baseHref = document.querySelector("base[href]")?.getAttribute("href");
268
+ const base = baseHref ? new URL(baseHref, `http://site.invalid${url}`).pathname : url;
269
+ const redirect = [...document.querySelectorAll("meta[http-equiv]")].some((meta) => meta.getAttribute("http-equiv")?.toLowerCase() === "refresh");
270
+ const noindex = [...document.querySelectorAll("meta[name=\"robots\"]")].some((meta) => /\bnoindex\b/i.test(meta.getAttribute("content") ?? ""));
271
+ const root = document.documentElement;
272
+ let text;
273
+ const visibleText = () => {
274
+ if (text === void 0) {
275
+ const body = document.body ?? root;
276
+ text = body ? textOf(body).replace(/\s+/g, " ").trim() : "";
277
+ }
278
+ return text;
279
+ };
280
+ let attributes;
281
+ const attributeValues = () => {
282
+ if (attributes === void 0) {
283
+ attributes = [];
284
+ for (const el of document.querySelectorAll("*")) for (const name of el.getAttributeNames()) {
285
+ const value = el.getAttribute(name);
286
+ if (value) attributes.push(value);
287
+ }
288
+ }
289
+ return attributes;
290
+ };
291
+ let comments;
292
+ return {
293
+ path: file,
294
+ url,
295
+ base,
296
+ redirect,
297
+ noindex,
298
+ document,
299
+ visibleText,
300
+ attributeValues,
301
+ comments: () => {
302
+ if (comments === void 0) {
303
+ comments = [];
304
+ if (root) commentsOf(root, comments);
305
+ }
306
+ return comments;
307
+ }
308
+ };
309
+ };
310
+ /** Same-site URL references only: no scheme (`https:`, `mailto:`, `tel:`, `data:`, …), not
311
+ * protocol-relative, not a fragment — or an absolute URL on the site's own `origin`. */
312
+ const isSameSiteReference = (value, origin) => {
313
+ const v = value.trim();
314
+ if (v === "" || v.startsWith("#") || v.startsWith("//")) return false;
315
+ if (!/^[a-z][a-z0-9+.-]*:/i.test(v)) return true;
316
+ if (!origin) return false;
317
+ try {
318
+ return new URL(v).origin === origin;
319
+ } catch {
320
+ return false;
321
+ }
322
+ };
323
+ /** Resolves a same-site reference against the page it appears on; the URL path only. */
324
+ const resolveReference = (page, value) => new URL(value.trim(), `http://site.invalid${page.base}`).pathname;
325
+ /** The URLs an element references: `href`, `src`, `poster`, every `srcset` candidate. */
326
+ const referencedUrls = (el) => {
327
+ const urls = [];
328
+ for (const attr of [
329
+ "href",
330
+ "src",
331
+ "poster"
332
+ ]) {
333
+ const value = el.getAttribute(attr);
334
+ if (value) urls.push(value);
335
+ }
336
+ const srcset = el.getAttribute("srcset");
337
+ if (srcset) for (const candidate of srcset.split(",")) {
338
+ const url = candidate.trim().split(/\s+/, 1)[0];
339
+ if (url) urls.push(url);
340
+ }
341
+ return urls;
342
+ };
343
+ /** The text of an XML element as a value: `&amp;`, `&lt;`, `&gt;`, `&quot;`, `&apos;` and numeric
344
+ * character references decoded. A sitemap writes `/sonne-&-meer/` as `/sonne-&amp;-meer/`. */
345
+ const xmlText = (text) => text.replace(/&(?:#x([0-9a-f]+)|#(\d+)|(amp|lt|gt|quot|apos));/gi, (entity, hex, dec, name) => {
346
+ if (hex) return String.fromCodePoint(parseInt(hex, 16));
347
+ if (dec) return String.fromCodePoint(parseInt(dec, 10));
348
+ return {
349
+ amp: "&",
350
+ lt: "<",
351
+ gt: ">",
352
+ quot: "\"",
353
+ apos: "'"
354
+ }[name.toLowerCase()] ?? entity;
355
+ });
356
+ //#endregion
357
+ //#region src/checks/imageFormats.ts
358
+ const RASTER = /* @__PURE__ */ new Set([
359
+ ".jpg",
360
+ ".jpeg",
361
+ ".png",
362
+ ".webp"
363
+ ]);
364
+ /** Icons browsers and web manifests load as PNG by name: an AVIF beside them serves nobody. */
365
+ const ICON = /^public\/(?:apple-touch-icon|favicon|icon-\d+)[^/]*\.png$/;
366
+ /** The URLs an element references for an image: `src`, `poster`, every `srcset` candidate. */
367
+ const imageUrls = (el) => {
368
+ const urls = [];
369
+ for (const attr of ["src", "poster"]) {
370
+ const value = el.getAttribute(attr);
371
+ if (value) urls.push(value);
372
+ }
373
+ const srcset = el.getAttribute("srcset");
374
+ if (srcset) for (const candidate of srcset.split(",")) {
375
+ const url = candidate.trim().split(/\s+/, 1)[0];
376
+ if (url) urls.push(url);
377
+ }
378
+ return urls;
379
+ };
380
+ /** A raster image under `public/` without an AVIF sibling: it renders, it just costs every visitor
381
+ * bandwidth. The site's own files decide this, so it refuses the build. */
382
+ const imageFormats = {
383
+ id: "image-formats",
384
+ title: "Image formats",
385
+ severity: "error",
386
+ begin: (ctx) => {
387
+ const ignored = new Set(ctx.options.imageIgnore);
388
+ return { finish: () => {
389
+ const findings = [];
390
+ for (const file of filesUnder(ctx.publicDir, RASTER)) {
391
+ const rel = ctx.rel(file);
392
+ if (ignored.has(rel) || ICON.test(rel)) continue;
393
+ const stem = file.slice(0, -path.extname(file).length);
394
+ if (fs.existsSync(`${stem}.avif`)) continue;
395
+ findings.push({
396
+ path: rel,
397
+ message: "A raster image ships without an AVIF sibling; it renders and just costs the visitor bandwidth. Encode one (scripts/to-avif.mjs), or list the file in imageIgnore with a reason."
398
+ });
399
+ }
400
+ return findings;
401
+ } };
402
+ }
403
+ };
404
+ /** A feed photo from the vOffice image hosts requested as JPEG or PNG where the host would serve
405
+ * WebP. A warning: the photos come from the PMS feed, so a page shows them, and the finding, only
406
+ * once the feed has them; that must not stop the nightly builds that update prices. */
407
+ const feedImageFormats = {
408
+ id: "feed-image-formats",
409
+ title: "Feed photo formats",
410
+ severity: "warning",
411
+ begin: (ctx) => {
412
+ if (!ctx.hasDist) return null;
413
+ const patterns = ctx.options.feedImagePatterns.map((source) => new RegExp(source, "i"));
414
+ const findings = [];
415
+ return {
416
+ visit: (page) => {
417
+ for (const el of page.document.querySelectorAll("img, source, video")) for (const url of imageUrls(el)) if (patterns.some((pattern) => pattern.test(url))) findings.push({
418
+ path: page.path,
419
+ message: `A feed photo is requested as JPEG or PNG: ${url}. Pass it through webpUrl() so the host serves WebP.`
420
+ });
421
+ },
422
+ finish: () => findings
423
+ };
424
+ }
425
+ };
426
+ //#endregion
427
+ //#region src/checks/listingLinks.ts
428
+ /** A page that lists rentals renders the list into its HTML too, inside this container, so a
429
+ * crawler running no JavaScript sees the rentals the live island will show. The search page of
430
+ * the site starter marks its server-rendered results this way. */
431
+ const LIST_CONTAINER = "[data-prerendered-results]";
432
+ /** The live search island; a page that mounts it lists rentals, container or not. */
433
+ const LIST_ISLAND = "SearchResults";
434
+ /** Below this many pages the build is a starter with an empty feed, where an empty list says
435
+ * nothing about the site's code. */
436
+ const SMALL_BUILD = 10;
437
+ const normalize$1 = (urlPath) => {
438
+ const p = urlPath.split(/[?#]/, 1)[0] ?? "";
439
+ return p.length > 1 ? p.replace(/\/+$/, "") : p;
440
+ };
441
+ /** The page as a listing, when it is one: its markup marks it, or `listingPages` names it. Links
442
+ * are those of the list's own markup: the container, else what the island rendered on the server
443
+ * (a client-only island renders nothing). A page known only from `listingPages` has neither, and
444
+ * its header, navigation and footer links are not a list either. */
445
+ const asListing = (ctx, configured, page) => {
446
+ const container = page.document.querySelector(LIST_CONTAINER);
447
+ const islands = [...page.document.querySelectorAll("astro-island")].filter((el) => (el.getAttribute("component-url") ?? "").includes(LIST_ISLAND));
448
+ const url = normalize$1(page.url);
449
+ if (!container && islands.length === 0 && !configured.has(url)) return null;
450
+ const anchors = container ? [...container.querySelectorAll("a[href]")] : islands.length > 0 ? islands.flatMap((island) => [...island.querySelectorAll("a[href]")]) : [...page.document.querySelectorAll("a[href]")].filter((a) => !a.closest("header, nav, footer"));
451
+ const links = /* @__PURE__ */ new Set();
452
+ for (const a of anchors) {
453
+ const href = a.getAttribute("href") ?? "";
454
+ if (/^[a-z][a-z0-9+.-]*:/i.test(href) || href.startsWith("#")) continue;
455
+ const target = normalize$1(new URL(href, `http://site.invalid${page.base}`).pathname);
456
+ if (target !== url && ctx.serves(target)) links.add(target);
457
+ }
458
+ return {
459
+ path: page.path,
460
+ url,
461
+ links: links.size
462
+ };
463
+ };
464
+ /** Every page that lists rentals is indexable: a hidden listing hides its rentals with it. The
465
+ * site's own noindex routes decide this, not the feed, so it refuses the build. Skipped while
466
+ * every page is noindex (a site before launch). */
467
+ const listingNoindex = {
468
+ id: "listing-noindex",
469
+ title: "Rental listings are indexable",
470
+ severity: "error",
471
+ begin: (ctx) => {
472
+ if (!ctx.hasDist) return null;
473
+ const configured = new Set(ctx.options.listingPages.map(normalize$1));
474
+ const hidden = [];
475
+ let indexable = 0;
476
+ return {
477
+ visit: (page) => {
478
+ if (page.redirect) return;
479
+ if (!page.noindex) indexable += 1;
480
+ else if (asListing(ctx, configured, page)) hidden.push(page.path);
481
+ },
482
+ finish: () => indexable === 0 ? [] : hidden.map((path) => ({
483
+ path,
484
+ message: "A page that lists rentals is noindex; the rentals it lists are hidden with it. Take it out of the noindex routes."
485
+ }))
486
+ };
487
+ }
488
+ };
489
+ /** Every page that lists rentals carries links to them in its built HTML; a crawler without
490
+ * JavaScript otherwise sees an empty list. A warning: the links come from the PMS feed, and an
491
+ * empty or booked-out feed must not stop the nightly builds that update prices. Runs once some
492
+ * listing page has links, or the build is more than a starter's handful of pages. */
493
+ const listingLinks = {
494
+ id: "listing-links",
495
+ title: "Rental listings reach crawlers",
496
+ severity: "warning",
497
+ begin: (ctx) => {
498
+ if (!ctx.hasDist) return null;
499
+ const configured = new Set(ctx.options.listingPages.map(normalize$1));
500
+ const clientOnly = new Map(ctx.options.listingClientOnly.map((c) => [normalize$1(c.path), c]));
501
+ const listings = [];
502
+ let pages = 0;
503
+ return {
504
+ visit: (page) => {
505
+ if (page.redirect) return;
506
+ pages += 1;
507
+ const listing = asListing(ctx, configured, page);
508
+ if (listing) listings.push(listing);
509
+ },
510
+ finish: () => {
511
+ const findings = [];
512
+ if (!listings.some((l) => l.links > 0) && pages <= SMALL_BUILD) return findings;
513
+ for (const listing of listings) if (listing.links === 0 && !clientOnly.has(listing.url)) findings.push({
514
+ path: listing.path,
515
+ message: "No links to rentals in the HTML: a crawler running no JavaScript sees an empty list. Render the list server-side (the search page's prerendered results), or list the page in listingClientOnly with the reason."
516
+ });
517
+ return findings;
518
+ }
519
+ };
520
+ }
521
+ };
522
+ //#endregion
523
+ //#region src/checks/optimizeDeps.ts
524
+ const SOURCE_EXTENSIONS = /* @__PURE__ */ new Set([
525
+ ".ts",
526
+ ".tsx",
527
+ ".js",
528
+ ".jsx",
529
+ ".mjs",
530
+ ".astro"
531
+ ]);
532
+ /** `import … from "x"`, `import "x"`, `export … from "x"` and `import("x")`. Type-only forms load
533
+ * nothing and are skipped. */
534
+ const IMPORT_RE = /\b(?:import|export)\s+(type\s+)?(?:[^'"`;]*?\s+from\s+)?['"]([^'"]+)['"]|\bimport\s*\(\s*['"]([^'"]+)['"]\s*\)/g;
535
+ /** The package a specifier belongs to: `@scope/name` or `name`. */
536
+ const packageOf = (specifier) => {
537
+ const parts = specifier.split("/");
538
+ return specifier.startsWith("@") ? parts.slice(0, 2).join("/") : parts[0] ?? specifier;
539
+ };
540
+ /** Styles and assets are served, not pre-bundled: `maplibre-gl/dist/maplibre-gl.css` is no entry. */
541
+ const ASSET = /\.(?:css|scss|sass|less|json|svg|png|jpe?g|webp|avif|gif|woff2?)$/i;
542
+ const isBare = (specifier) => !/^[./#]/.test(specifier) && !/^(?:node|astro|virtual|data):/.test(specifier) && !ASSET.test(specifier);
543
+ /** Every runtime package `src/` imports is either reached by the dev server's startup crawl or
544
+ * named in `vite.optimizeDeps.include`; one that is neither gets discovered mid-session, which
545
+ * re-stamps every pre-bundled dependency and leaves an open tab asking for files that no longer
546
+ * exist. The sites' convention is to list every runtime package, which is what is checked: a bare
547
+ * specifier of a `dependencies` package, not exactly in `include` and not ignored. A warning: it
548
+ * slows the dev server, it changes nothing a visitor sees. */
549
+ const optimizeDeps = {
550
+ id: "optimize-deps",
551
+ title: "Runtime packages missing from vite.optimizeDeps.include",
552
+ severity: "warning",
553
+ begin: (ctx) => ({ finish: () => {
554
+ const included = new Set(ctx.config.optimizeDepsInclude);
555
+ const ignored = new Set(ctx.options.optimizeDepsIgnore);
556
+ const runtime = ctx.packageJson.dependencies;
557
+ const importers = /* @__PURE__ */ new Map();
558
+ for (const file of ctx.sourceFiles(SOURCE_EXTENSIONS)) {
559
+ const text = ctx.readSource(file);
560
+ for (const match of text.matchAll(IMPORT_RE)) {
561
+ const [, typeOnly, fromSpecifier, dynamicSpecifier] = match;
562
+ const specifier = fromSpecifier ?? dynamicSpecifier;
563
+ if (typeOnly || !specifier || !isBare(specifier)) continue;
564
+ const pkg = packageOf(specifier);
565
+ if (pkg === "astro" || pkg.startsWith("@types/") || !(pkg in runtime)) continue;
566
+ if (included.has(specifier) || ignored.has(specifier) || ignored.has(pkg)) continue;
567
+ const files = importers.get(specifier) ?? [];
568
+ const rel = ctx.rel(file);
569
+ if (!files.includes(rel)) files.push(rel);
570
+ importers.set(specifier, files);
571
+ }
572
+ }
573
+ const findings = [];
574
+ for (const [specifier, files] of [...importers].sort(([a], [b]) => a.localeCompare(b))) {
575
+ const shown = files.slice(0, 3).join(", ");
576
+ const more = files.length > 3 ? ` (+${files.length - 3} more)` : "";
577
+ findings.push({
578
+ path: files[0],
579
+ message: `"${specifier}" is imported by ${shown}${more} but not in vite.optimizeDeps.include. Add it there, or to optimizeDepsIgnore in site-checks.config.json if only server-side code uses it.`
580
+ });
581
+ }
582
+ return findings;
583
+ } })
584
+ };
585
+ //#endregion
586
+ //#region src/checks/pageHeads.ts
587
+ const MAX_TITLE = 60;
588
+ const MAX_DESCRIPTION = 160;
589
+ /** The head of every indexable page as a search result shows it: a title over 60 or a description
590
+ * over 160 characters is cut, an empty description is replaced by whatever the crawler picks, and a
591
+ * title or description another page repeats makes the two compete. A missing title or description
592
+ * is the build worker's `page-metadata` finding, not repeated here. A warning: the page works. */
593
+ const pageHeads = {
594
+ id: "page-heads",
595
+ title: "Titles and descriptions of indexable pages",
596
+ severity: "warning",
597
+ begin: (ctx) => {
598
+ if (!ctx.hasDist) return null;
599
+ const findings = [];
600
+ const titles = /* @__PURE__ */ new Map();
601
+ const descriptions = /* @__PURE__ */ new Map();
602
+ const remember = (map, value, path) => map.set(value, [...map.get(value) ?? [], path]);
603
+ return {
604
+ visit: (page) => {
605
+ if (page.redirect || page.noindex || page.path === "404.html") return;
606
+ const title = page.document.querySelector("title")?.textContent?.trim();
607
+ const description = page.document.querySelector("meta[name=\"description\"]")?.getAttribute("content")?.trim();
608
+ if (title) {
609
+ if (title.length > MAX_TITLE) findings.push({
610
+ path: page.path,
611
+ message: `The title has ${title.length} characters; search results cut it after ${MAX_TITLE}.`
612
+ });
613
+ remember(titles, title, page.path);
614
+ }
615
+ if (description !== void 0) {
616
+ if (description === "") findings.push({
617
+ path: page.path,
618
+ message: "The description is empty; search results show whatever the crawler picks."
619
+ });
620
+ else if (description.length > MAX_DESCRIPTION) findings.push({
621
+ path: page.path,
622
+ message: `The description has ${description.length} characters; search results cut it after ${MAX_DESCRIPTION}.`
623
+ });
624
+ if (description) remember(descriptions, description, page.path);
625
+ }
626
+ },
627
+ finish: () => {
628
+ const duplicates = (map, what) => {
629
+ for (const [value, pages] of map) {
630
+ if (pages.length < 2) continue;
631
+ const shown = pages.slice(0, 3).join(", ");
632
+ const more = pages.length > 3 ? ` (+${pages.length - 3} more)` : "";
633
+ findings.push({
634
+ path: pages[0],
635
+ message: `The ${what} "${value}" is repeated by ${shown}${more}; each indexable page needs its own.`
636
+ });
637
+ }
638
+ };
639
+ duplicates(titles, "title");
640
+ duplicates(descriptions, "description");
641
+ return findings;
642
+ }
643
+ };
644
+ }
645
+ };
646
+ //#endregion
647
+ //#region src/checks/sitemapNoindex.ts
648
+ const SITEMAP_INDEX = "sitemap-index.xml";
649
+ const LLMS = "llms.txt";
650
+ const normalize = (urlPath) => {
651
+ let p = urlPath.split(/[?#]/, 1)[0] ?? "";
652
+ try {
653
+ p = decodeURIComponent(p);
654
+ } catch {}
655
+ return p.length > 1 ? p.replace(/\/+$/, "") : p;
656
+ };
657
+ /** `https://www.example.de/a/` and `/a/` → `/a`. */
658
+ const toPath = (loc) => {
659
+ const value = loc.trim();
660
+ try {
661
+ return normalize(new URL(value).pathname);
662
+ } catch {
663
+ return normalize(value);
664
+ }
665
+ };
666
+ const locs = (xml) => [...xml.matchAll(/<loc>\s*([^<]+?)\s*<\/loc>/g)].map((m) => xmlText(m[1]));
667
+ /** The URL lists the build publishes agree with the pages it built: no sitemap entry whose own page
668
+ * says noindex or is not in the build, no `llms.txt` link to a page that is not there. Skipped when
669
+ * the build publishes neither (a site before launch). */
670
+ const sitemapNoindex = {
671
+ id: "sitemap-noindex",
672
+ title: "Published URL lists match the built pages",
673
+ severity: "error",
674
+ begin: (ctx) => {
675
+ if (!ctx.hasDist) return null;
676
+ const start = ctx.has(SITEMAP_INDEX) ? [SITEMAP_INDEX] : ctx.files.filter((f) => /^sitemap[^/]*\.xml$/.test(f));
677
+ if (start.length === 0 && !ctx.has(LLMS)) return null;
678
+ const noindex = /* @__PURE__ */ new Map();
679
+ return {
680
+ visit: (page) => {
681
+ if (!page.redirect && page.noindex) noindex.set(normalize(page.url), page.path);
682
+ },
683
+ finish: () => {
684
+ const findings = [];
685
+ const sitemaps = new Map(start.map((file) => [file, ""]));
686
+ for (const [sitemap, index] of sitemaps) {
687
+ if (!ctx.has(sitemap)) {
688
+ findings.push({
689
+ path: index,
690
+ message: `The sitemap index names ${sitemap}, which is not in the build.`
691
+ });
692
+ continue;
693
+ }
694
+ const xml = ctx.read(sitemap);
695
+ if (/<sitemapindex\b/i.test(xml)) {
696
+ for (const loc of locs(xml)) {
697
+ const child = toPath(loc).replace(/^\//, "");
698
+ if (!sitemaps.has(child)) sitemaps.set(child, sitemap);
699
+ }
700
+ continue;
701
+ }
702
+ for (const loc of locs(xml)) {
703
+ const urlPath = toPath(loc);
704
+ if (!ctx.serves(urlPath)) findings.push({
705
+ path: sitemap,
706
+ message: `The sitemap lists ${loc}, which is not in the build.`
707
+ });
708
+ else if (noindex.has(urlPath)) findings.push({
709
+ path: sitemap,
710
+ message: `The sitemap lists ${loc}, whose page says noindex: the sitemap filter and the noindex routes disagree.`
711
+ });
712
+ }
713
+ }
714
+ if (ctx.has(LLMS)) for (const match of ctx.read(LLMS).matchAll(/\]\(([^)\s]+)\)/g)) {
715
+ const link = match[1];
716
+ if (/^[a-z][a-z0-9+.-]*:/i.test(link) && !ctx.config.site) continue;
717
+ if (/^[a-z][a-z0-9+.-]*:/i.test(link)) {
718
+ let host;
719
+ try {
720
+ host = new URL(link).host;
721
+ } catch {
722
+ continue;
723
+ }
724
+ if (host !== new URL(ctx.config.site).host) continue;
725
+ }
726
+ if (!ctx.serves(toPath(link))) findings.push({
727
+ path: LLMS,
728
+ message: `llms.txt links ${link}, which is not in the build.`
729
+ });
730
+ }
731
+ return findings;
732
+ }
733
+ };
734
+ }
735
+ };
736
+ //#endregion
737
+ //#region src/checks/syncOnce.ts
738
+ const LOADER_FILES = ["src/content.config.ts", "src/content/config.ts"];
739
+ /** A loader written inline, as opposed to `glob()` or `file()`. */
740
+ const INLINE_LOADER = /\bloader\s*:\s*\{/;
741
+ /** It talks to the PMS. */
742
+ const LIVE_FETCH = /\bfetch\s*\(|createWebsiteSDK|createVofficeSdk|\.static\./;
743
+ /** The reuse idiom: the loader keeps the sync token in the store's meta and, when the token the
744
+ * build was started with is still the same, serves the entries it already has. */
745
+ const REUSE_IDIOM = [
746
+ /CONTENT_SYNC_TOKEN/,
747
+ /\bmeta\.get\(/,
748
+ /\bstore\.keys\(\)/
749
+ ];
750
+ /** `astro check` and `astro build` each run the content loader, so an unguarded loader pays every
751
+ * remote fetch twice on every build, against a rate-limited PMS. The build worker starts both with
752
+ * one `CONTENT_SYNC_TOKEN`; a loader that keys its store on it syncs once. A text heuristic, hence
753
+ * a warning. */
754
+ const syncOnce = {
755
+ id: "sync-once",
756
+ title: "Content loaders sync the PMS once per build",
757
+ severity: "warning",
758
+ begin: (ctx) => {
759
+ const loader = ctx.sourceFiles(/* @__PURE__ */ new Set([".ts"])).find((file) => LOADER_FILES.includes(ctx.rel(file)));
760
+ if (!loader) return null;
761
+ return { finish: () => {
762
+ const text = ctx.readSource(loader);
763
+ if (!INLINE_LOADER.test(text) || !LIVE_FETCH.test(text)) return [];
764
+ if (REUSE_IDIOM.every((idiom) => idiom.test(text))) return [];
765
+ return [{
766
+ path: ctx.rel(loader),
767
+ message: "A content loader fetches the PMS without the CONTENT_SYNC_TOKEN idiom; astro check and astro build each sync it, twice per build. Keep the token in the store's meta (meta.get) and reuse the entries (store.keys()) when it matches."
768
+ }];
769
+ } };
770
+ }
771
+ };
772
+ //#endregion
773
+ //#region src/checks/viewSource.ts
774
+ /** Comments the frameworks themselves write into static HTML, and no developer did: Astro's
775
+ * island and server-island markers, React 19's SSR markers (`<!--$-->`, `<!--/$-->`, …, and the
776
+ * `<!-- -->` text separator), Vue's SSR fragment and teleport markers. Matched on the trimmed
777
+ * comment text. A framework upgrade that adds a marker shows up as a refused build; extend the
778
+ * list here, in one place. */
779
+ const FRAMEWORK_COMMENTS = /* @__PURE__ */ new Set([
780
+ "",
781
+ "$",
782
+ "/$",
783
+ "$!",
784
+ "$?",
785
+ "&",
786
+ "/&",
787
+ "F",
788
+ "F!",
789
+ "html",
790
+ "head",
791
+ "body",
792
+ "[",
793
+ "]",
794
+ "teleport start",
795
+ "teleport end"
796
+ ]);
797
+ const isFrameworkComment = (data) => {
798
+ const text = data.trim();
799
+ return FRAMEWORK_COMMENTS.has(text) || text.startsWith("astro:") || text.startsWith("server-island");
800
+ };
801
+ /** Licence banners and bundler annotations survive minification on purpose and say nothing. */
802
+ const LEGAL_BLOCK_COMMENT = /^\/\*\s*[!@#]|@license|@preserve/;
803
+ const BLOCK_COMMENT = /\/\*[\s\S]*?\*\//g;
804
+ /** A line comment at the start of a line. `//` elsewhere is usually a URL. `//#` and `//!` are
805
+ * directives (source maps, legal comments), reported or allowed on their own. */
806
+ const LINE_COMMENT = /^[ \t]*\/\/(?![#!])(.*)$/gm;
807
+ const SOURCE_MAP_URL = /(?:\/\/|\/\*)# sourceMappingURL=/;
808
+ const excerpt = (text) => {
809
+ const flat = text.replace(/\s+/g, " ").trim();
810
+ return flat.length > 80 ? `${flat.slice(0, 79)}…` : flat;
811
+ };
812
+ const blockComments = (text) => (text.match(BLOCK_COMMENT) ?? []).filter((comment) => !LEGAL_BLOCK_COMMENT.test(comment));
813
+ const lineComments = (text) => [...text.matchAll(LINE_COMMENT)].map((match) => `//${match[1] ?? ""}`);
814
+ //#endregion
815
+ //#region src/checks/index.ts
816
+ /** The site checks, in the order the report shows them: the source first, then the built pages.
817
+ * The integration runs these inside the site's own `astro build`; the build worker's checks are
818
+ * the other family (`distChecks/`), and an id here must not reuse one of theirs (a test holds the
819
+ * rule). Adding a check is one file here, one entry, one test, a README row and a CHANGELOG
820
+ * entry. */
821
+ const checks = [
822
+ htmlComments,
823
+ syncOnce,
824
+ optimizeDeps,
825
+ {
826
+ id: "view-source",
827
+ title: "Developer notes visible in View Source",
828
+ severity: "error",
829
+ begin: (ctx) => {
830
+ if (!ctx.hasDist) return null;
831
+ const findings = [];
832
+ const report = (path, what, text) => findings.push({
833
+ path,
834
+ message: `${what}: "${excerpt(text)}"`
835
+ });
836
+ const visit = (page) => {
837
+ for (const comment of page.comments()) if (!isFrameworkComment(comment)) report(page.path, "HTML comment in the page", comment);
838
+ for (const el of page.document.querySelectorAll("script, style")) {
839
+ const text = el.textContent ?? "";
840
+ const what = `comment in an inline <${el.tagName.toLowerCase()}>`;
841
+ for (const comment of blockComments(text)) report(page.path, what, comment);
842
+ if (el.tagName === "SCRIPT") {
843
+ if (SOURCE_MAP_URL.test(text)) report(page.path, "source map reference in an inline <script>", text);
844
+ for (const comment of lineComments(text)) report(page.path, what, comment);
845
+ }
846
+ }
847
+ };
848
+ const finish = () => {
849
+ for (const file of ctx.files) {
850
+ if (file.endsWith(".map")) {
851
+ findings.push({
852
+ path: file,
853
+ message: "A source map ships the original source to anyone who asks for it."
854
+ });
855
+ continue;
856
+ }
857
+ const isJs = /\.m?js$/.test(file);
858
+ const isCss = file.endsWith(".css");
859
+ if (!isJs && !isCss) continue;
860
+ const text = ctx.read(file);
861
+ if (SOURCE_MAP_URL.test(text)) report(file, "source map reference", "sourceMappingURL");
862
+ if (isCss) for (const comment of blockComments(text)) report(file, "comment in shipped CSS", comment);
863
+ if (isJs) for (const comment of lineComments(text)) report(file, "comment in shipped JS", comment);
864
+ }
865
+ return findings;
866
+ };
867
+ return {
868
+ visit,
869
+ finish
870
+ };
871
+ }
872
+ },
873
+ donorTerms,
874
+ consentGate,
875
+ imageFormats,
876
+ feedImageFormats,
877
+ listingNoindex,
878
+ listingLinks,
879
+ sitemapNoindex,
880
+ pageHeads
881
+ ];
882
+ //#endregion
883
+ //#region src/options.ts
884
+ const CONFIG_FILE = "site-checks.config.json";
885
+ /** The vOffice image hosts that answer JPEG unless asked for WebP: imgproxy's `plain` path (v9,
886
+ * `…jpg@webp`) and `dyn.v-office.com` (`….webp`). The v10 host answers WebP by itself. */
887
+ const DEFAULT_FEED_IMAGE_PATTERNS = ["\\/_\\/[^\\s]*\\/plain\\/[^\\s@]+\\.(?:jpe?g|png)$", "^https:\\/\\/dyn\\.v-office\\.com\\/image\\/[^\\s]+\\.(?:jpe?g|png)$"];
888
+ const STRING_LIST_KEYS = [
889
+ "donorTerms",
890
+ "optimizeDepsIgnore",
891
+ "imageIgnore",
892
+ "feedImagePatterns",
893
+ "listingPages",
894
+ "consentAllowedHosts"
895
+ ];
896
+ const isStringList = (value) => Array.isArray(value) && value.every((item) => typeof item === "string");
897
+ const isClientOnlyList = (value) => Array.isArray(value) && value.every((item) => typeof item === "object" && item !== null && typeof item.path === "string" && typeof item.reason === "string");
898
+ const validate = (source, raw) => {
899
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) throw new Error(`[site-checks] ${source} must be a JSON object`);
900
+ const known = /* @__PURE__ */ new Set([...STRING_LIST_KEYS, "listingClientOnly"]);
901
+ const options = {};
902
+ for (const [key, value] of Object.entries(raw)) {
903
+ if (!known.has(key)) throw new Error(`[site-checks] ${source}: unknown key "${key}" (known: ${[...known].join(", ")})`);
904
+ if (key === "listingClientOnly") {
905
+ if (!isClientOnlyList(value)) throw new Error(`[site-checks] ${source}: "${key}" must be an array of { path, reason }`);
906
+ options.listingClientOnly = value;
907
+ } else {
908
+ if (!isStringList(value)) throw new Error(`[site-checks] ${source}: "${key}" must be an array of strings`);
909
+ if (key === "feedImagePatterns") for (const pattern of value) try {
910
+ new RegExp(pattern, "i");
911
+ } catch (err) {
912
+ throw new Error(`[site-checks] ${source}: "${key}" has an invalid regular expression ${JSON.stringify(pattern)}: ${err.message}`);
913
+ }
914
+ options[key] = value;
915
+ }
916
+ }
917
+ return options;
918
+ };
919
+ /** The file's keys with the integration's options on top. A file that cannot be parsed throws:
920
+ * a broken config must not silently disable a check. */
921
+ function loadOptions(root, overrides = {}) {
922
+ const file = path.join(root, CONFIG_FILE);
923
+ let fromFile = {};
924
+ if (fs.existsSync(file)) {
925
+ let raw;
926
+ try {
927
+ raw = JSON.parse(fs.readFileSync(file, "utf8"));
928
+ } catch (err) {
929
+ throw new Error(`[site-checks] ${CONFIG_FILE} is not valid JSON: ${err.message}`);
930
+ }
931
+ fromFile = validate(CONFIG_FILE, raw);
932
+ }
933
+ const given = validate("siteChecks() options", overrides);
934
+ const pick = (key, fallback) => given[key] ?? fromFile[key] ?? fallback;
935
+ return {
936
+ donorTerms: pick("donorTerms", []),
937
+ optimizeDepsIgnore: pick("optimizeDepsIgnore", []),
938
+ imageIgnore: pick("imageIgnore", []),
939
+ feedImagePatterns: pick("feedImagePatterns", DEFAULT_FEED_IMAGE_PATTERNS),
940
+ listingPages: pick("listingPages", []),
941
+ listingClientOnly: pick("listingClientOnly", []),
942
+ consentAllowedHosts: pick("consentAllowedHosts", [])
943
+ };
944
+ }
945
+ //#endregion
946
+ //#region src/runner.ts
947
+ /** Findings kept per check in the report; the rest is counted in `omitted`. */
948
+ const MAX_FINDINGS_PER_CHECK = 25;
949
+ /** The controller's `siteCheckReportSchema` accepts a finding message of at most 2000 characters
950
+ * and a path of at most 1000, and skips a report it cannot read as a whole: one over-long finding
951
+ * (a check that quotes a long URL or template expression) must not cost the whole report. */
952
+ const MAX_MESSAGE_CHARS = 2e3;
953
+ const MAX_PATH_CHARS = 1e3;
954
+ const ELLIPSIS = "…";
955
+ const clip = (text, max) => text.length > max ? text.slice(0, max - 1) + ELLIPSIS : text;
956
+ const bounded = (finding, title) => {
957
+ const message = clip(finding.message.trim() || title, MAX_MESSAGE_CHARS);
958
+ return finding.path === void 0 ? { message } : {
959
+ message,
960
+ path: clip(finding.path, MAX_PATH_CHARS)
961
+ };
962
+ };
963
+ const errorMessage = (err) => err instanceof Error ? err.message : String(err);
964
+ const failed = (check, message) => ({
965
+ id: check.id,
966
+ status: "failed",
967
+ findings: [bounded({ message }, check.title)],
968
+ omitted: 0
969
+ });
970
+ const broken = (check, err) => failed(check, `The check itself failed: ${errorMessage(err)}`);
971
+ const unreadable = (check, err) => failed(check, `The build output could not be read: ${errorMessage(err)}`);
972
+ const finish = async (check, run) => {
973
+ try {
974
+ const findings = await run.finish();
975
+ return {
976
+ id: check.id,
977
+ status: findings.length === 0 ? "ok" : check.severity,
978
+ findings: findings.slice(0, 25).map((f) => bounded(f, check.title)),
979
+ omitted: Math.max(0, findings.length - 25)
980
+ };
981
+ } catch (err) {
982
+ return broken(check, err);
983
+ }
984
+ };
985
+ /** Runs every check of `list` over the context `load` returns. Never throws: a check that throws
986
+ * is a `failed` result, a context that cannot be loaded fails every check the same way. The HTML
987
+ * pages are parsed one at a time and shown to every check before the next one is read. */
988
+ const runChecks = async (load, list) => {
989
+ const started = Date.now();
990
+ const ranAt = new Date(started).toISOString();
991
+ let ctx;
992
+ try {
993
+ ctx = load();
994
+ } catch (err) {
995
+ return {
996
+ ranAt,
997
+ durationMs: Date.now() - started,
998
+ results: list.map((check) => unreadable(check, err))
999
+ };
1000
+ }
1001
+ const results = /* @__PURE__ */ new Map();
1002
+ const runs = /* @__PURE__ */ new Map();
1003
+ for (const check of list) try {
1004
+ const run = check.begin(ctx);
1005
+ if (run) runs.set(check, run);
1006
+ else results.set(check, {
1007
+ id: check.id,
1008
+ status: "skipped",
1009
+ findings: [],
1010
+ omitted: 0
1011
+ });
1012
+ } catch (err) {
1013
+ results.set(check, broken(check, err));
1014
+ }
1015
+ for (const file of ctx.files) {
1016
+ if (!file.endsWith(".html")) continue;
1017
+ const visiting = [...runs].filter(([, run]) => run.visit);
1018
+ if (visiting.length === 0) break;
1019
+ let page;
1020
+ try {
1021
+ page = readPage(ctx, file);
1022
+ } catch (err) {
1023
+ for (const [check] of visiting) {
1024
+ runs.delete(check);
1025
+ results.set(check, unreadable(check, err));
1026
+ }
1027
+ break;
1028
+ }
1029
+ for (const [check, run] of visiting) try {
1030
+ run.visit?.(page);
1031
+ } catch (err) {
1032
+ runs.delete(check);
1033
+ results.set(check, broken(check, err));
1034
+ }
1035
+ }
1036
+ for (const [check, run] of runs) results.set(check, await finish(check, run));
1037
+ return {
1038
+ ranAt,
1039
+ durationMs: Date.now() - started,
1040
+ results: list.map((check) => results.get(check))
1041
+ };
1042
+ };
1043
+ /** Runs every site check over the project and its build. */
1044
+ const runSiteChecks = (input, list = checks) => runChecks(() => loadContext({
1045
+ root: input.root,
1046
+ srcDir: input.srcDir ?? `${input.root}/src`,
1047
+ publicDir: input.publicDir ?? `${input.root}/public`,
1048
+ distDir: input.distDir,
1049
+ config: {
1050
+ site: input.config?.site,
1051
+ optimizeDepsInclude: input.config?.optimizeDepsInclude ?? []
1052
+ },
1053
+ options: loadOptions(input.root, input.options)
1054
+ }), list);
1055
+ /** Results with status `error`: the only ones that refuse a build. */
1056
+ const blockingResults = (report) => report.results.filter((r) => r.status === "error");
1057
+ //#endregion
1058
+ //#region src/report.ts
1059
+ /** The report's file name under `dist/`. The build worker reads it after `astro build`, merges it
1060
+ * with its own checks and never uploads it (it names source paths and configured terms). */
1061
+ const SITE_CHECKS_FILE = "site-checks.json";
1062
+ const writeSiteChecksReport = (distDir, report) => {
1063
+ fs.mkdirSync(distDir, { recursive: true });
1064
+ fs.writeFileSync(path.join(distDir, SITE_CHECKS_FILE), JSON.stringify(report, null, 2) + "\n");
1065
+ };
1066
+ const count = (result) => result.findings.length + result.omitted;
1067
+ const plural = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
1068
+ const line = (finding) => finding.path ? `${finding.path}: ${finding.message}` : finding.message;
1069
+ /** One line per check that found something or could not run, for the build log. */
1070
+ const summaryLines = (report) => report.results.filter((r) => r.status !== "ok" && r.status !== "skipped").map((r) => `[site-checks] ${r.id}: ${r.status}, ${plural(count(r), "finding")}`);
1071
+ /** The error `astro build` ends with when a check refuses: every failing check, its first findings,
1072
+ * and where the whole report is. */
1073
+ const refusalMessage = (report) => {
1074
+ const blocking = blockingResults(report);
1075
+ const lines = [`[site-checks] build refused: ${plural(blocking.length, "check")} with errors`];
1076
+ for (const result of blocking) {
1077
+ const shown = result.findings.slice(0, 3);
1078
+ const more = count(result) - shown.length;
1079
+ lines.push(` - ${result.id} (${plural(count(result), "finding")})`);
1080
+ for (const finding of shown) lines.push(` ${line(finding)}`);
1081
+ if (more > 0) lines.push(` (+${more} more)`);
1082
+ }
1083
+ lines.push(` Report: dist/${SITE_CHECKS_FILE}`);
1084
+ return lines.join("\n");
1085
+ };
1086
+ /** One line naming what refused the build, for the studio: the failing checks and their counts. */
1087
+ const summarizeBlocking = (report) => "Checks refused the build: " + blockingResults(report).map((r) => `${r.id} (${plural(count(r), "finding")})`).join(", ");
1088
+ //#endregion
1089
+ export { referencedUrls as _, writeSiteChecksReport as a, MAX_PATH_CHARS as c, runSiteChecks as d, CONFIG_FILE as f, loadDistContext as g, isSameSiteReference as h, summaryLines as i, blockingResults as l, checks as m, refusalMessage as n, MAX_FINDINGS_PER_CHECK as o, loadOptions as p, summarizeBlocking as r, MAX_MESSAGE_CHARS as s, SITE_CHECKS_FILE as t, runChecks as u, resolveReference as v, xmlText as y };