| 1 | 'use strict'; |
| 2 | const fs = require('fs'); |
| 3 | const path = require('path'); |
| 4 | const urlMod = require('url'); |
| 5 | const base64Stream = require('base64-stream'); |
| 6 | const parseCookiePhantomjs = require('parse-cookie-phantomjs'); |
| 7 | const phantomBridge = require('phantom-bridge'); |
| 8 | const byline = require('byline'); |
| 9 | |
| 10 | const handleCookies = (cookies, url) => { |
| 11 | const parsedUrl = urlMod.parse(url); |
| 12 | |
| 13 | return (cookies || []).map(x => { |
| 14 | const ret = typeof x === 'string' ? parseCookiePhantomjs(x) : x; |
| 15 | |
| 16 | if (!ret.domain) { |
| 17 | ret.domain = parsedUrl.hostname; |
| 18 | } |
| 19 | |
| 20 | if (!ret.path) { |
| 21 | ret.path = parsedUrl.path; |
| 22 | } |
| 23 | |
| 24 | return ret; |
| 25 | }); |
| 26 | }; |
| 27 | |
| 28 | module.exports = (url, size, opts) => { |
| 29 | opts = Object.assign({ |
| 30 | delay: 0, |
| 31 | scale: 1, |
| 32 | format: 'png' |
| 33 | }, opts); |
| 34 | |
| 35 | const args = Object.assign(opts, { |
| 36 | url, |
| 37 | width: size.split(/x/i)[0] * opts.scale, |
| 38 | height: size.split(/x/i)[1] * opts.scale, |
| 39 | cookies: handleCookies(opts.cookies, url), |
| 40 | format: opts.format === 'jpg' ? 'jpeg' : opts.format, |
| 41 | css: /\.css$/.test(opts.css) ? fs.readFileSync(opts.css, 'utf8') : opts.css, |
| 42 | script: /\.js$/.test(opts.script) ? fs.readFileSync(opts.script, 'utf8') : opts.script |
| 43 | }); |
| 44 | |
| 45 | const cp = phantomBridge(path.join(__dirname, 'stream.js'), [ |
| 46 | '--ignore-ssl-errors=true', |
| 47 | '--local-to-remote-url-access=true', |
| 48 | '--ssl-protocol=any', |
| 49 | JSON.stringify(args) |
| 50 | ]); |
| 51 | |
| 52 | const stream = base64Stream.decode(); |
| 53 | |
| 54 | process.stderr.setMaxListeners(0); |
| 55 | |
| 56 | cp.stderr.setEncoding('utf8'); |
| 57 | cp.stdout.pipe(stream); |
| 58 | |
| 59 | byline(cp.stderr).on('data', data => { |
| 60 | data = data.trim(); |
| 61 | |
| 62 | if (/ phantomjs\[/.test(data)) { |
| 63 | return; |
| 64 | } |
| 65 | |
| 66 | if (/http:\/\/requirejs.org\/docs\/errors.html#mismatch/.test(data)) { |
| 67 | return; |
| 68 | } |
| 69 | |
| 70 | if (data.startsWith('WARN: ')) { |
| 71 | stream.emit('warning', data.replace(/^WARN: /, '')); |
| 72 | stream.emit('warn', data.replace(/^WARN: /, '')); // TODO: deprecate this event in v5 |
| 73 | return; |
| 74 | } |
| 75 | |
| 76 | if (data.length > 0) { |
| 77 | const err = new Error(data); |
| 78 | err.noStack = true; |
| 79 | cp.stdout.unpipe(stream); |
| 80 | stream.emit('error', err); |
| 81 | } |
| 82 | }); |
| 83 | |
| 84 | return stream; |
| 85 | }; |