|
| 1 | +const pa11y = require('pa11y'); |
| 2 | +const { extname } = require('path'); |
| 3 | +const { isDirectory, isFile } = require('path-type'); |
| 4 | +const { results: cliReporter } = require('pa11y/lib/reporters/cli'); |
| 5 | +const readdirp = require('readdirp'); |
| 6 | +const EMPTY_ARRAY = []; |
| 7 | +const ASTERISK = '*'; |
| 8 | +const HTML_EXT = '.html'; |
| 9 | +const GLOB_HTML = '*.html'; |
| 10 | +exports.runPa11y = async function ({ htmlFilePaths, pa11yOpts, build }) { |
| 11 | + let issueCount = 0; |
| 12 | + const results = await Promise.all(htmlFilePaths.map(async (path) => { |
| 13 | + try { |
| 14 | + const res = await pa11y(path, pa11yOpts); |
| 15 | + if (res.issues && res.issues.length) { |
| 16 | + issueCount += res.issues.length; |
| 17 | + return cliReporter(res); |
| 18 | + } |
| 19 | + } |
| 20 | + catch (error) { |
| 21 | + build.failBuild('pa11y failed', { error }); |
| 22 | + } |
| 23 | + })); |
| 24 | + return { |
| 25 | + issueCount, |
| 26 | + report: results.join(''), |
| 27 | + }; |
| 28 | +}; |
| 29 | +exports.generateFilePaths = async function ({ fileAndDirPaths, ignoreDirectories, absolutePublishDir, }) { |
| 30 | + const excludeDirGlobs = ignoreDirectories.map((dir) => `!${dir.replace(/^\/+/, '')}`); |
| 31 | + const htmlFilePaths = await Promise.all(fileAndDirPaths.map((fileAndDirPath) => findHtmlFiles(`${absolutePublishDir}${fileAndDirPath}`, excludeDirGlobs))); |
| 32 | + return [].concat(...htmlFilePaths); |
| 33 | +}; |
| 34 | +const findHtmlFiles = async function (fileAndDirPath, directoryFilter) { |
| 35 | + if (await isDirectory(fileAndDirPath)) { |
| 36 | + const filePaths = []; |
| 37 | + const stream = readdirp(fileAndDirPath, { |
| 38 | + fileFilter: GLOB_HTML, |
| 39 | + directoryFilter: !!directoryFilter.length ? directoryFilter : ASTERISK, |
| 40 | + }); |
| 41 | + for await (const { fullPath } of stream) { |
| 42 | + filePaths.push(fullPath); |
| 43 | + } |
| 44 | + return filePaths; |
| 45 | + } |
| 46 | + if (!(await isFile(fileAndDirPath))) { |
| 47 | + console.warn(`Folder ${fileAndDirPath} was provided in "checkPaths", but does not exist - it either indicates something went wrong with your build, or you can simply delete this folder from your "checkPaths" in netlify.toml`); |
| 48 | + return EMPTY_ARRAY; |
| 49 | + } |
| 50 | + if (extname(fileAndDirPath) !== HTML_EXT) { |
| 51 | + return EMPTY_ARRAY; |
| 52 | + } |
| 53 | + return [fileAndDirPath]; |
| 54 | +}; |
0 commit comments