-
Notifications
You must be signed in to change notification settings - Fork 14
/
validate-links-integration.ts
169 lines (148 loc) · 4.2 KB
/
validate-links-integration.ts
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
import type { AstroIntegration, AstroIntegrationLogger } from 'astro';
import { unified } from 'unified';
import remarkParse from 'remark-parse';
import { visit } from 'unist-util-visit';
import remarkStringify from 'remark-stringify';
import fs from 'fs';
import path from 'path';
import axios from 'axios';
const INTEGRATION_NAME = 'astro-plugin-validate-links';
async function validateLinks(
links: string[],
type: 'absolute' | 'relative',
collectionPages: string[],
logger: AstroIntegrationLogger,
) {
if (type === 'relative') {
let notFoundLinks = [];
links.forEach(async (link) => {
const cleanedPathName = link.split('/');
if (cleanedPathName.at(-1) === '') {
cleanedPathName.pop();
}
const isLink404 = !collectionPages.includes(
cleanedPathName.join('/'),
);
if (isLink404) {
logger.error(`404 Not Found: ${cleanedPathName.join('/')}`);
notFoundLinks.push(cleanedPathName.join('/'));
}
});
if (notFoundLinks.length > 0) {
throw new Error('Error: 404 links found! Fix the above errors! ^');
}
} else {
const linkPromises = links.map(async (link) => {
try {
await axios.head(link, { timeout: 2000, maxRedirects: 10 });
return { link, status: 'ok' };
} catch (error: any) {
if (error?.response && error?.response?.status === 404) {
logger.error(`404 not found: ${link}`);
return { link, status: '404 not found' };
}
logger.error(`invalid link: ${link}`);
return { link, status: 'error', error };
}
});
await Promise.allSettled(linkPromises);
}
}
interface PluginOptions {
validateAbsoluteLinks?: boolean;
}
const createPlugin = (options: PluginOptions): AstroIntegration => {
return {
name: INTEGRATION_NAME,
hooks: {
'astro:build:done': async ({ dir, routes, pages, logger }) => {
logger.info('Validating links...');
const collectionPages = pages
.filter(
(page) =>
page.pathname.startsWith('docs') ||
page.pathname.startsWith('blog'),
)
.map(({ pathname }) => {
const cleanedPathname = `/${pathname}`.split('/');
cleanedPathname.pop();
return cleanedPathname.join('/');
});
const contentDir = './src/content';
function readFile(filePath: string) {
return fs.readFileSync(filePath, 'utf-8');
}
function getFilePaths(dir: string) {
const filePaths: string[] = [];
function traverseDirectory(currentDir: string) {
const files = fs.readdirSync(currentDir);
for (const file of files) {
const filePath = path.join(currentDir, file);
const stats = fs.statSync(filePath);
if (stats.isDirectory()) {
traverseDirectory(filePath);
} else if (
path.extname(filePath) === '.md' ||
path.extname(filePath) === '.mdx'
) {
filePaths.push(filePath);
}
}
}
traverseDirectory(dir);
return filePaths;
}
// Extract links from Markdown files
async function extractLinks(filePaths: string[]) {
const absoluteLinks = new Set<string>();
const relativeLinks = new Set<string>();
for (const filePath of filePaths) {
const content = readFile(filePath);
await unified()
.use(remarkParse)
.use(() => {
return function transform(tree) {
visit(tree, 'link', (linkNode) => {
const url: string = (linkNode as any)
?.url;
if (!url.includes('./')) {
if (url.startsWith('/')) {
relativeLinks.add(url);
} else if (url.includes('http')) {
absoluteLinks.add(
(linkNode as any)?.url,
);
}
}
});
};
})
.use(remarkStringify)
.process(content);
}
return {
absoluteLinks,
relativeLinks,
};
}
const filePaths = getFilePaths(contentDir);
const links = await extractLinks(filePaths);
await validateLinks(
Array.from(links.relativeLinks),
'relative',
collectionPages,
logger,
);
if (options?.validateAbsoluteLinks) {
await validateLinks(
Array.from(links.absoluteLinks),
'absolute',
collectionPages,
logger,
);
}
},
},
};
};
export default createPlugin;