Debian Codegraph @

docs/scripts/check-site.mjs

raw symbols SCIP
1 import { existsSync, readdirSync, readFileSync } from 'node:fs'
2 import { dirname, extname, join, relative, resolve } from 'node:path'
3 import { fileURLToPath } from 'node:url'
4
5 const docsDirectory = resolve(dirname(fileURLToPath(import.meta.url)), '..')
6 const outputDirectory = join(docsDirectory, '.vitepress', 'dist')
7 const basePath = process.env.BASE_PATH ?? '/frei0r/'
8 const normalizedBasePath = basePath === '/'
9 ? ''
10 : `/${basePath.replace(/^\/+|\/+$/g, '')}`
11
12 if (!existsSync(join(outputDirectory, 'index.html'))) {
13 throw new Error('Build the website before running the checker.')
14 }
15
16 const htmlFiles = []
17
18 function collectHtml(directory) {
19 for (const entry of readdirSync(directory, { withFileTypes: true })) {
20 const path = join(directory, entry.name)
21 if (entry.isDirectory()) {
22 if (relative(outputDirectory, path) === 'codedoc') {
23 continue
24 }
25 collectHtml(path)
26 } else if (extname(entry.name) === '.html') {
27 htmlFiles.push(path)
28 }
29 }
30 }
31
32 function localCandidates(sourceFile, value) {
33 const withoutFragment = value.split('#', 1)[0].split('?', 1)[0]
34 if (!withoutFragment || withoutFragment.startsWith('//')) {
35 return []
36 }
37
38 const withoutBase = normalizedBasePath && withoutFragment.startsWith(`${normalizedBasePath}/`)
39 ? `/${withoutFragment.slice(normalizedBasePath.length + 1)}`
40 : withoutFragment === normalizedBasePath
41 ? '/'
42 : withoutFragment
43
44 const base = withoutFragment.startsWith('/')
45 ? outputDirectory
46 : dirname(sourceFile)
47 const target = resolve(base, withoutBase.replace(/^\/+/, ''))
48
49 return [target, `${target}.html`, join(target, 'index.html')]
50 }
51
52 collectHtml(outputDirectory)
53
54 const missing = []
55 const attributePattern = /\b(?:href|src)=["']([^"'<>]+)["']/g
56
57 for (const htmlFile of htmlFiles) {
58 const html = readFileSync(htmlFile, 'utf8')
59 for (const match of html.matchAll(attributePattern)) {
60 const value = match[1]
61 if (/^(?:[a-z]+:|#)/i.test(value)) {
62 continue
63 }
64
65 const candidates = localCandidates(htmlFile, decodeURI(value))
66 if (candidates.length > 0 && !candidates.some(existsSync)) {
67 missing.push(`${relative(outputDirectory, htmlFile)} -> ${value}`)
68 }
69 }
70 }
71
72 const retainedPaths = [
73 'index.html',
74 'pics/fla_name_lb.webp',
75 'pics/frei0r.png',
76 'frei0r-all.webm',
77 'codedoc/html/index.html',
78 'codedoc/html/frei0r_8h.html'
79 ]
80
81 for (const path of retainedPaths) {
82 if (!existsSync(join(outputDirectory, path))) {
83 missing.push(`retained path missing: ${path}`)
84 }
85 }
86
87 if (missing.length > 0) {
88 console.error(missing.join('\n'))
89 process.exit(1)
90 }
91
92 console.log(`Checked ${htmlFiles.length} HTML files and ${retainedPaths.length} retained paths.`)