|
| 1 | +const Visit = require('unist-util-visit') |
| 2 | +const FsExtra = require('fs-extra') |
| 3 | +const Path = require('path') |
| 4 | + |
| 5 | +/** |
| 6 | + * Checks if the specified URL is an absolute path. |
| 7 | + * @param {string} url URL. |
| 8 | + * @returns {boolean} `true` if the URL is an absolute path. |
| 9 | + * @throws `url` type is not string. |
| 10 | + * @see https://stackoverflow.com/questions/10687099/how-to-test-if-a-url-string-is-absolute-or-relative |
| 11 | + */ |
| 12 | +const isAbsoluteURL = (url) => { |
| 13 | + if (typeof url !== 'string') { |
| 14 | + throw new Error('`url` type is not string.') |
| 15 | + } |
| 16 | + |
| 17 | + return /^(?:[a-z]+:)?\/\//i.test(url) |
| 18 | +} |
| 19 | + |
| 20 | +/** |
| 21 | + * Check that the file with the specified URL is to be ignored. |
| 22 | + * @param {string} url URL. |
| 23 | + * @param {string[]} extentions File extensions. |
| 24 | + * @returns {boolean} `true` if ignored |
| 25 | + */ |
| 26 | +const isIgnore = (url, extentions) => { |
| 27 | + return Array.isArray(extentions) |
| 28 | + ? extentions.some((ext) => url.endsWith(ext)) |
| 29 | + : false |
| 30 | +} |
| 31 | + |
| 32 | +module.exports = ( |
| 33 | + { files, linkPrefix, markdownNode, markdownAST, getNode }, |
| 34 | + pluginOptions = {} |
| 35 | +) => { |
| 36 | + // Copy linked files to the public directory and modify the AST to point to new location of the files. |
| 37 | + const visitor = (link) => { |
| 38 | + if ( |
| 39 | + isAbsoluteURL(link.url) || |
| 40 | + isIgnore(link.url, pluginOptions.ignoreFileExtensions) |
| 41 | + ) { |
| 42 | + return |
| 43 | + } |
| 44 | + |
| 45 | + const linkPath = Path.join(getNode(markdownNode.parent).dir, link.url) |
| 46 | + const linkNode = files.find((file) => { |
| 47 | + return file && file.absolutePath ? file.absolutePath === linkPath : false |
| 48 | + }) |
| 49 | + |
| 50 | + if (!(linkNode && linkNode.absolutePath)) { |
| 51 | + return |
| 52 | + } |
| 53 | + |
| 54 | + const newPath = Path.join( |
| 55 | + process.cwd(), |
| 56 | + 'public', |
| 57 | + `${linkNode.relativePath}` |
| 58 | + ) |
| 59 | + |
| 60 | + link.url = Path.join(linkPrefix || '/', linkNode.relativePath) |
| 61 | + if (FsExtra.existsSync(newPath)) { |
| 62 | + return |
| 63 | + } |
| 64 | + |
| 65 | + FsExtra.copy(linkPath, newPath, (err) => { |
| 66 | + if (err) { |
| 67 | + console.error(`error copying file`, err) |
| 68 | + } |
| 69 | + }) |
| 70 | + } |
| 71 | + |
| 72 | + Visit(markdownAST, `image`, (image) => visitor(image)) |
| 73 | + Visit(markdownAST, `link`, (link) => visitor(link)) |
| 74 | +} |
0 commit comments