|
| 1 | +const spawn = require("child_process").spawn; |
| 2 | + |
| 3 | +class HTMLValidatePlugin { |
| 4 | + constructor(options) { |
| 5 | + ({ |
| 6 | + path: this.path, |
| 7 | + extensions: this.extensions, |
| 8 | + config: this.config, |
| 9 | + global: this.global, |
| 10 | + } = options); |
| 11 | + } |
| 12 | + |
| 13 | + convertExtensionArrayToRegex() { |
| 14 | + // replace array as curly braced string for replacing commas and spaces |
| 15 | + let processedExtension = `"{${this.extensions}}"` |
| 16 | + .replace(/\'/g, "") |
| 17 | + .replace(/\ /g, ""); |
| 18 | + // strip out curly braces if there was only one index provided in extensions array |
| 19 | + return processedExtension.includes(",") |
| 20 | + ? processedExtension |
| 21 | + : processedExtension.replace(/\{/g, "").replace(/\}/g, ""); |
| 22 | + } |
| 23 | + |
| 24 | + runCliBasedOnScope(userParams, spawnParams) { |
| 25 | + /* |
| 26 | + arguments are in an array and shell option is 'false' by default; this is better for security |
| 27 | + https://stackoverflow.com/a/50424976d |
| 28 | + https://nodejs.org/api/child_process.html#child_process_child_process_spawn_command_args_options |
| 29 | + */ |
| 30 | + return this.global |
| 31 | + ? spawn("html-validate", [`${userParams}`], spawnParams) |
| 32 | + : spawn( |
| 33 | + "node", |
| 34 | + ["node_modules/.bin/html-validate", `${userParams}`], |
| 35 | + spawnParams |
| 36 | + ); |
| 37 | + } |
| 38 | + |
| 39 | + apply(compiler) { |
| 40 | + // initiate script when webpack compilation is completed |
| 41 | + compiler.hooks.done.tap("HTMLValidatePlugin", () => { |
| 42 | + const path = `${this.path || "src/**/*"}`; |
| 43 | + const extension = `${ |
| 44 | + this.extensions ? this.convertExtensionArrayToRegex() : "html" |
| 45 | + }`; |
| 46 | + const config = `${ |
| 47 | + this.config ? "--config " + this.config + ".json" : false |
| 48 | + }`; |
| 49 | + |
| 50 | + // set up cli payload |
| 51 | + const userParams = `${path}.${extension} ${config}`; |
| 52 | + const spawnParams = { |
| 53 | + shell: true, |
| 54 | + /*inherit color output */ stdio: "inherit", |
| 55 | + }; |
| 56 | + |
| 57 | + this.runCliBasedOnScope(userParams, spawnParams); |
| 58 | + }); |
| 59 | + } |
| 60 | +} |
| 61 | + |
| 62 | +module.exports = HTMLValidatePlugin; |
0 commit comments