Repository navigation
Expand file tree
/
Copy pathchecksitemap.js
More file actions
78 lines (65 loc) · 2.05 KB
/
Copy pathchecksitemap.js
File metadata and controls
78 lines (65 loc) · 2.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
const fs = require('node:fs');
const path = require('node:path');
const root = __dirname;
const buildDirectory = path.resolve(root, 'build');
const forbiddenPaths = new Set([
'/blog/authors',
'/blog/authors/lavrton',
'/kai',
'/markdown-page',
'/search',
]);
function outputCandidates(pathname) {
const cleanPath = decodeURIComponent(pathname).replace(/^\/+/, '');
if (!cleanPath) {
return [path.join(buildDirectory, 'index.html')];
}
const outputPath = path.join(buildDirectory, cleanPath);
return pathname.endsWith('/')
? [path.join(outputPath, 'index.html')]
: [outputPath, path.join(outputPath, 'index.html')];
}
function checkSitemap(sitemapPath) {
if (!fs.existsSync(sitemapPath)) {
console.error(`Sitemap does not exist: ${sitemapPath}`);
return false;
}
const xml = fs.readFileSync(sitemapPath, 'utf8');
const urls = [...xml.matchAll(/<loc>(.*?)<\/loc>/g)].map(
(match) => new URL(match[1])
);
const failures = [];
for (const url of urls) {
const normalizedPath =
url.pathname.length > 1 ? url.pathname.replace(/\/$/, '') : url.pathname;
const pathWithoutLocale = normalizedPath.replace(/^\/zh-Hans(?=\/|$)/, '') || '/';
if (forbiddenPaths.has(pathWithoutLocale)) {
failures.push(`Forbidden sitemap URL: ${url.href}`);
continue;
}
if (!outputCandidates(url.pathname).some((file) => fs.existsSync(file))) {
failures.push(`No build output for: ${url.href}`);
}
}
if (failures.length) {
failures.forEach((failure) => console.error(failure));
return false;
}
console.log(`Sitemap contains ${urls.length} valid local URLs.`);
return true;
}
function main() {
const requested = process.argv[2];
const sitemapPaths = requested
? [path.resolve(root, requested)]
: [
path.join(buildDirectory, 'sitemap.xml'),
...(fs.existsSync(path.join(root, 'i18n', 'zh-Hans'))
? [path.join(buildDirectory, 'zh-Hans', 'sitemap.xml')]
: []),
];
if (!sitemapPaths.every(checkSitemap)) {
process.exitCode = 1;
}
}
main();