|
| 1 | +const path = require('path'); |
| 2 | +const { spawn } = require('child_process'); |
| 3 | +const { version } = require('../../package.json'); |
| 4 | + |
| 5 | +const CONVERTER_TOOL_PATH = path.resolve(__dirname, '../../bin/ConverterTool'); |
| 6 | + |
| 7 | +module.exports = (function () { |
| 8 | + /** |
| 9 | + * Runs shell script |
| 10 | + * |
| 11 | + * @param command |
| 12 | + * @param args |
| 13 | + * @param callback |
| 14 | + */ |
| 15 | + const runScript = (command, args, callback) => { |
| 16 | + const child = spawn(command, args); |
| 17 | + |
| 18 | + let stdout = ''; |
| 19 | + let stderr = ''; |
| 20 | + |
| 21 | + child.stdout.setEncoding('utf8'); |
| 22 | + child.stdout.on('data', (data) => { |
| 23 | + data = data.toString(); |
| 24 | + stdout += data; |
| 25 | + }); |
| 26 | + |
| 27 | + child.stderr.setEncoding('utf8'); |
| 28 | + child.stderr.on('data', (data) => { |
| 29 | + data = data.toString(); |
| 30 | + stderr += data; |
| 31 | + }); |
| 32 | + |
| 33 | + child.on('close', (code) => { |
| 34 | + callback(code, stdout, stderr); |
| 35 | + }); |
| 36 | + |
| 37 | + return child; |
| 38 | + }; |
| 39 | + |
| 40 | + /** |
| 41 | + * Runs converter method for rules |
| 42 | + * |
| 43 | + * @param rules array of rules |
| 44 | + * @param advancedBlocking if we need advanced blocking content |
| 45 | + * @param rulesLimit |
| 46 | + */ |
| 47 | + const jsonFromRules = async (rules, advancedBlocking, rulesLimit) => { |
| 48 | + return new Promise((resolve, reject) => { |
| 49 | + const child = runScript(CONVERTER_TOOL_PATH, [ |
| 50 | + `-limit=${rulesLimit}`, |
| 51 | + '-optimize=false', |
| 52 | + `-advancedBlocking=${advancedBlocking}`, |
| 53 | + ], (code, stdout, stderr) => { |
| 54 | + if (code !== 0) { |
| 55 | + reject(stderr); |
| 56 | + return; |
| 57 | + } |
| 58 | + |
| 59 | + const result = JSON.parse(stdout); |
| 60 | + |
| 61 | + resolve(result); |
| 62 | + }); |
| 63 | + |
| 64 | + child.stdin.setEncoding('utf8'); |
| 65 | + for (const r of rules) { |
| 66 | + child.stdin.write(r); |
| 67 | + child.stdin.write('\n'); |
| 68 | + } |
| 69 | + |
| 70 | + child.stdin.end(); |
| 71 | + }); |
| 72 | + }; |
| 73 | + |
| 74 | + /** |
| 75 | + * Returns Safari Converter Lib version |
| 76 | + */ |
| 77 | + const getConverterVersion = () => { |
| 78 | + return version; |
| 79 | + } |
| 80 | + |
| 81 | + return { |
| 82 | + jsonFromRules, |
| 83 | + getConverterVersion, |
| 84 | + }; |
| 85 | +})(); |
0 commit comments