|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +const fs = require('fs'); |
| 4 | +const { Worker, isMainThread, workerData: path } = require('worker_threads'); |
| 5 | + |
| 6 | +function* getLinksRecursively(node) { |
| 7 | + if ( |
| 8 | + (node.type === 'link' && !node.url.startsWith('#')) || |
| 9 | + node.type === 'image' |
| 10 | + ) { |
| 11 | + yield node; |
| 12 | + } |
| 13 | + for (const child of node.children || []) { |
| 14 | + yield* getLinksRecursively(child); |
| 15 | + } |
| 16 | +} |
| 17 | + |
| 18 | +if (isMainThread) { |
| 19 | + const { extname, join, resolve } = require('path'); |
| 20 | + const DIR = resolve(process.argv[2]); |
| 21 | + |
| 22 | + console.log('Running Markdown link checker...'); |
| 23 | + |
| 24 | + async function* findMarkdownFilesRecursively(dirPath) { |
| 25 | + const fileNames = await fs.promises.readdir(dirPath); |
| 26 | + |
| 27 | + for (const fileName of fileNames) { |
| 28 | + const path = join(dirPath, fileName); |
| 29 | + |
| 30 | + const stats = await fs.promises.stat(path); |
| 31 | + if ( |
| 32 | + stats.isDirectory() && |
| 33 | + fileName !== 'api' && |
| 34 | + fileName !== 'deps' && |
| 35 | + fileName !== 'node_modules' |
| 36 | + ) { |
| 37 | + yield* findMarkdownFilesRecursively(path); |
| 38 | + } else if (extname(fileName) === '.md') { |
| 39 | + yield path; |
| 40 | + } |
| 41 | + } |
| 42 | + } |
| 43 | + |
| 44 | + function errorHandler(error) { |
| 45 | + console.error(error); |
| 46 | + process.exitCode = 1; |
| 47 | + } |
| 48 | + |
| 49 | + setImmediate(async () => { |
| 50 | + for await (const path of findMarkdownFilesRecursively(DIR)) { |
| 51 | + new Worker(__filename, { workerData: path }).on('error', errorHandler); |
| 52 | + } |
| 53 | + }); |
| 54 | +} else { |
| 55 | + const unified = require('unified'); |
| 56 | + const { pathToFileURL } = require('url'); |
| 57 | + |
| 58 | + const tree = unified() |
| 59 | + .use(require('remark-parse')) |
| 60 | + .parse(fs.readFileSync(path)); |
| 61 | + |
| 62 | + const base = pathToFileURL(path); |
| 63 | + for (const node of getLinksRecursively(tree)) { |
| 64 | + const targetURL = new URL(node.url, base); |
| 65 | + if (targetURL.protocol === 'file:' && !fs.existsSync(targetURL)) { |
| 66 | + const error = new Error('Broken link in a Markdown document.'); |
| 67 | + const { start } = node.position; |
| 68 | + error.stack = |
| 69 | + error.stack.substring(0, error.stack.indexOf('\n') + 5) + |
| 70 | + `at ${node.type} (${path}:${start.line}:${start.column})`; |
| 71 | + throw error; |
| 72 | + } |
| 73 | + } |
| 74 | +} |
0 commit comments