-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathindex.js
85 lines (78 loc) · 2.44 KB
/
index.js
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
const { chromium } = require("playwright");
const Sitemapper = require("sitemapper");
const { chunks } = require("./src/util");
const MAX_PAGES = 100;
const fetchSitemapUrls = async baseUrl => {
const sitemap = new Sitemapper();
const { sites } = await sitemap.fetch(`${baseUrl}/sitemap.xml`);
const maxSites = Math.min(sites.length, MAX_PAGES);
//TODO: sort by sitemap priority
if (maxSites === 0) {
return [baseUrl];
}
const absoluteUrlSites = sites.map(site => {
if (site.startsWith("/")) {
return `${baseUrl}${site}`;
}
return site;
});
return absoluteUrlSites.slice(0, maxSites);
};
const runAccessibilityTestsOnUrl = async url => {
const browser = await chromium.launch();
const context = await browser.newContext();
try {
const page = await context.newPage();
await page.goto(url);
await page.addScriptTag({
url: "https://cdnjs.cloudflare.com/ajax/libs/axe-core/3.4.2/axe.min.js"
});
const axeViolations = await page.evaluate(async () => {
const axeResults = await new Promise((resolve, reject) => {
window.axe.run((err, results) => {
if (err) {
reject(err);
} else {
resolve(results);
}
});
});
return {
violations: axeResults.violations.map(violation => ({
id: violation.id,
impact: violation.impact,
description: violation.description,
nodes: violation.nodes.map(node => node.html)
}))
};
});
return { url, ...axeViolations };
} catch (e) {
return { url, violations: [], error: e.message };
} finally {
await browser.close();
}
};
const runAllChecks = async (urls, spinner) => {
const chunkedUrls = [...chunks(urls, 5)];
const totalViolationsByPage = [];
for (const urlChunk of chunkedUrls) {
if (spinner) {
spinner.text = `Running accessibility checks... (${totalViolationsByPage.length ||
1} of ${urls.length} pages)`;
}
const violationPromises = urlChunk.map(url =>
runAccessibilityTestsOnUrl(url)
);
const resolvedViolationsByPage = await Promise.all(violationPromises);
totalViolationsByPage.push(...resolvedViolationsByPage);
}
return totalViolationsByPage;
};
const lumberjack = async (baseUrl, options, spinner) => {
const urls = options.baseUrlOnly
? [baseUrl]
: await fetchSitemapUrls(baseUrl);
return runAllChecks(urls, spinner);
};
module.exports = lumberjack;