-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaxe-auto-reporter.mjs
379 lines (347 loc) · 16.1 KB
/
axe-auto-reporter.mjs
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
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
import { mkdir, readFile, writeFile } from 'fs/promises';
import puppeteer from 'puppeteer';
import { loadPage } from '@axe-core/puppeteer';
import AXELOCALES_JA from 'axe-core/locales/ja.json' with { type: 'json' };
import path from 'path';
import config from './config.mjs';
// Viewport settings
const VIEWPORTS = {
PC: { width: 1024, height: 768 },
MOBILE: { width: 375, height: 812 }
};
// Configure
const reportConfigure = () => {
const newConfig = { ...config };
if (newConfig.locale === 'ja') {
newConfig.localeData = AXELOCALES_JA;
}
if (newConfig.mode === 'pc') {
newConfig.viewport = VIEWPORTS.PC;
} else if (newConfig.mode === 'mobile') {
newConfig.viewport = VIEWPORTS.MOBILE;
} else {
console.error('\x1b[31mInvalid mode specified\x1b[0m');
throw new Error('Invalid mode specified');
}
return newConfig;
};
// Error Handling
process.on('unhandledRejection', (error) => {
console.error('\x1b[31mUnhandled promise rejection:\x1b[0m', error);
process.exit(1);
});
// Folder existence check and creation
const ensureDirectoryExists = async (dir) => {
try {
await mkdir(dir, { recursive: true });
} catch (error) {
if (error.code !== 'EEXIST') throw error;
}
};
// HTML escape
const escapeHtml = unsafe => (
unsafe
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''')
.replace(/\n/g, '<br>')
);
try {
// Load configure
const { urlList, localeData, tags, locale, viewport } = reportConfigure();
// Puppeteer launch
const browser = await puppeteer.launch({
headless: 'new',
defaultViewport: viewport,
});
// Read URLs from the external file
const urlsContent = await readFile(urlList, 'utf-8');
const urls = urlsContent.split('\n').filter(Boolean);
// Create a 'results' directory if it doesn't exist
const resultsFolder = 'results';
await ensureDirectoryExists(resultsFolder);
// Create a folder inside 'results' based on the current datetime (`yyyy-mm-dd_hh-mm-ss`)
const now = new Date();
const dateTimeFolder = new Intl.DateTimeFormat('ja-JP', {
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
hour12: false
}).format(now).replace(/[\/\s:]/g, '-');
const folderName = path.join(resultsFolder, dateTimeFolder);
await ensureDirectoryExists(folderName);
// Create subdirectories for JSON and HTML files inside the dateTime folder
const jsonFolder = path.join(folderName, 'json');
const htmlFolder = path.join(folderName, 'html');
await Promise.all([
ensureDirectoryExists(jsonFolder),
ensureDirectoryExists(htmlFolder)
]);
// Sanitize file name
const sanitizeFilenamePart = (str) => str.replace(/[^a-zA-Z0-9\-_.]/g, '_');
// Set count for progress
let processedCount = 0;
// Run Tests
for (const url of urls) {
if (typeof url !== 'string') continue;
let page;
try {
// Output progress (start)
console.log(`Processing ${processedCount + 1}/${urls.length}: ${url}`);
// Load page
const axeBuilder = await loadPage(browser, url.trim());
page = axeBuilder.page;
// Get a screenshot of the page in Base64 format
const screenshotBase64 = await page.screenshot({ encoding: 'base64' });
// Get test results
const results = await axeBuilder.configure({ locale: localeData }).withTags(tags).analyze();
// Create file name
const parsedURL = new URL(url);
const domain = parsedURL.hostname;
const pathName = sanitizeFilenamePart(parsedURL.pathname.slice(1).replace(/\/$/g, ''));
const queryString = sanitizeFilenamePart(parsedURL.search.slice(1));
const baseFilename = `${domain}${pathName ? `_${pathName}` : ''}${queryString ? `_${queryString}` : ''}`;
// Save results to an external JSON file (eg. example.com_pathname.json)
const jsonFilename = path.join(jsonFolder, `${baseFilename}.json`);
await writeFile(jsonFilename, JSON.stringify(results, null, 2), 'utf-8');
// Save results to an external HTML file (eg. example.com_pathname.html)
const htmlFilename = path.join(htmlFolder, `${baseFilename}.html`);
const htmlContent = await generateHtmlReport(url, results, screenshotBase64, locale);
await writeFile(htmlFilename, htmlContent, 'utf-8');
// Output progress (complete)
processedCount++;
console.log(`\x1b[32mCompleted!\x1b[0m ${processedCount}/${urls.length}: ${url}`);
} catch (error) {
console.error(`\x1b[31mFailed to process URL:\x1b[0m ${url}`, {
message: error.message,
stack: error.stack,
url,
timestamp: new Date().toISOString()
});
processedCount++;
} finally {
if (page && !page.isClosed()) {
await page.close();
}
}
}
await browser.close();
} catch (error) {
console.error('Fatal error:', error);
process.exit(1);
}
// Generate HTML
async function generateHtmlReport(url, results, screenshotBase64, locale) {
const translations = {
ja: {
labelTitle: 'アクセシビリティレポート',
labelViolations: '試験結果',
labelFailureMessage: '発見された問題点',
labelFailureSummaly: '修正提案',
labelImgAlt: 'ページのスクリーンショット',
labelTargetHTML: '対象 HTML',
labelHelpPage: '参考情報',
labelNoIssues: '問題点は発見されませんでした!',
labelImpact: '影響度',
impactData: {
minor: '軽度',
moderate: '中程度',
serious: '深刻',
critical: '重大',
},
labelViolationFilter: '影響度フィルター',
labelViolationFilterNote: '(チェックを外すと該当する影響度の問題点が非表示になります)',
labelViolationFilterReset: 'フィルターをリセット',
labelViolationFilterResetAriaLabel: '影響度フィルターをリセットしてすべての問題点を表示',
},
en: {
labelTitle: 'Accessibility Report',
labelViolations: 'Test Result',
labelFailureMessage: 'Failure Message',
labelFailureSummaly: 'Failure Summary',
labelImgAlt: 'Screenshot of the page',
labelTargetHTML: 'Target HTML',
labelHelpPage: 'More Information',
labelNoIssues: 'You have (0) automatic issues, nice!',
labelImpact: 'Impact',
impactData: {
minor: 'Minor',
moderate: 'Moderate',
serious: 'Serious',
critical: 'Critical',
},
labelViolationFilter: 'Impact Filter',
labelViolationFilterNote: '(Uncheck to hide failures of the corresponding impact level)',
labelViolationFilterReset: 'Reset Filter',
labelViolationFilterResetAriaLabel: 'Reset the impact filter to display all failures.',
},
// Add translations for other languages as necessary.
};
const translate = (key, subkey) => {
const keys = translations[locale] || translations.ja;
return subkey ? keys[key][subkey] || keys[key] : keys[key] || 'Translation missing';
};
const template = await readFile('template/template.html', 'utf-8');
const cssContent = await readFile('template/styles.css', 'utf-8');
let impactListHtml;
let violationHtml;
if (!results?.violations?.length) {
violationHtml = `
<div class="violationBody">
<p class="noIssues">
<span class="icon" aria-hidden="true">
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5" />
</svg>
</span>
${translate('labelNoIssues')}
</p>
</div>
`;
} else {
const impactCounts = {
minor: 0,
moderate: 0,
serious: 0,
critical: 0
};
for (const violation of results.violations) {
for (const node of violation.nodes) {
if (Object.hasOwn(impactCounts, node.impact)) {
impactCounts[node.impact]++;
}
}
}
impactListHtml = Object.entries(impactCounts).map(([impact, count]) => `
<li>
<span class="sr-only">
<input type="checkbox" name="filter-${impact}" id="filter-${impact}" checked>
</span>
<label class="violationFilterBtn" for="filter-${impact}">
<span class="violationLabel ${impact}">${translate('impactData', impact)}</span>
<span class="violationFilterNum">${count}</span>
</label>
</li>
`).join('');
violationHtml = results.violations.map(violation => `
<div class="violationBody">
<div class="violationBodyHeader">
<h3>${escapeHtml(violation.description)}</h3>
<div class="helpUrl">
<dl>
<dt>${translate('labelHelpPage')}</dt>
<dd><a href="${violation.helpUrl}" target="_blank" rel="noopener">${escapeHtml(violation.help)}</a></dd>
</dl>
</div>
<div class="tagList">
<ul>${violation.tags.map(tag => `<li><span>${escapeHtml(tag)}</span></li>`).join('')}</ul>
</div>
</div>
<div class="violationItem">
<ul>
${violation.nodes.map(node => `
<li data-impact="${node.impact}">
<dl>
<div class="failureMessage">
<dt>
${translate('labelFailureMessage')}
<span class="impact">${translate('labelImpact')}
<span class="impactLabel ${node.impact}">${translate('impactData', node.impact)}</span>
</span>
</dt>
<dd class="failureList">
<ul>
${node.any && node.any.length ? node.any.map(anyMessage => `
<li>
<span class="failureListIcon" aria-hidden="true">
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" d="M12 9v3.75m9-.75a9 9 0 11-18 0 9 9 0 0118 0zm-9 3.75h.008v.008H12v-.008z" />
</svg>
</span>
${escapeHtml(anyMessage.message)}</li>
`).join('') : ''}
${node.none && node.none.length ? node.none.map(noneMessage => `
<li>
<span class="failureListIcon" aria-hidden="true">
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" d="M12 9v3.75m9-.75a9 9 0 11-18 0 9 9 0 0118 0zm-9 3.75h.008v.008H12v-.008z" />
</svg>
</span>
${escapeHtml(noneMessage.message)}</li>
`).join('') : ''}
</ul>
</dd>
</div>
<div class="failureSummaly">
<dt>${translate('labelFailureSummaly')}</dt>
<dd>${escapeHtml(node.failureSummary)}</dd>
</div>
<div class="targetHTML">
<dt>${translate('labelTargetHTML')}</dt>
<dd><code tabindex="0">${escapeHtml(node.html)}</code></dd>
</div>
<div class="targetDom">
<dt>DOM</dt>
<dd><code tabindex="0">${escapeHtml(node.target[0])}</code></dd>
</div>
</dl>
</li>
`).join('')}
</ul>
</div>
</div>
`).join('');
}
return template
.replace('{{STYLE}}', `<style>${cssContent}</style>`)
.replace('{{LOCALE}}', locale)
.replace('{{PAGE_TITLE}}', translate('labelTitle'))
.replace('{{URL}}', escapeHtml(url))
.replace('{{HEADER}}', `
<hgroup class="title">
<h1>${translate('labelTitle')}</h1>
<p class="testUrl">
<span class="urlLabel">URL:</span>
${escapeHtml(url)}
</p>
</hgroup>
`)
.replace('{{CONTENT}}', `
<div class="main-contents">
<div class="screenshot">
<img src="data:image/png;base64,${screenshotBase64}" alt="${translate('labelImgAlt')}">
</div>
<div class="violation">
<div class="violationHeader">
<h2>${translate('labelViolations')}</h2>
</div>
${impactListHtml ? `
<div class="violationSummary">
<dl class="violationFilter">
<dt>
${translate('labelViolationFilter')}
<span class="sr-only">${translate('labelViolationFilterNote')}</span>
</dt>
<dd>
<ul>
${impactListHtml}
<li class="violationFilterReset">
<button class="violationFilterResetBtn" id="filter-reset" aria-label="${translate('labelViolationFilterResetAriaLabel')}">
${translate('labelViolationFilterReset')}
</button>
</li>
</ul>
</dd>
</dl>
</div>
` : ''}
${violationHtml}
</div>
</div>
`);
};