/
index.js
393 lines (356 loc) · 12.8 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
'use strict'
let Puppeteer, PuppeteerBrowserFetcher
try {
Puppeteer = require('puppeteer/lib/Puppeteer')
PuppeteerBrowserFetcher = require('puppeteer/lib/BrowserFetcher')
} catch (err) {
console.warn(`
Puppeteer is missing. :-)
Note: puppeteer is a peer dependency of puppeteer-extra,
which means you can install your own preferred version.
To get the latest stable verson run: 'yarn add puppeteer'
To get the latest tip-of-tree verson run: 'yarn add puppeteer@next'
`)
throw err
}
const merge = require('deepmerge')
const debug = require('debug')('puppeteer-extra')
/**
* Modular plugin framework to teach `puppeteer` new tricks.
*
* This module acts a drop-in replacement for `puppeteer`.
*
* Allows PuppeteerExtraPlugin's to register themselves and
* to extend puppeteer with additional functionality.
*
* @example
* const puppeteer = require('puppeteer-extra')
* puppeteer.use(require('puppeteer-extra-plugin-anonymize-ua')())
* puppeteer.use(require('puppeteer-extra-plugin-font-size')({defaultFontSize: 18}))
*
* ;(async () => {
* const browser = await puppeteer.launch({headless: false})
* const page = await browser.newPage()
* await page.goto('http://example.com', {waitUntil: 'domcontentloaded'})
* await browser.close()
* })()
*/
class PuppeteerExtra {
constructor () {
this._plugins = []
// Ensure there are certain properties (e.g. the `options.args` array)
this._defaultLaunchOptions = { args: [] }
}
/**
* Outside interface to register plugins.
*
* @param {PuppeteerExtraPlugin} plugin
* @return {this} - For chaining
*
* @example
* const puppeteer = require('puppeteer-extra')
* puppeteer.use(require('puppeteer-extra-plugin-anonymize-ua')())
* puppeteer.use(require('puppeteer-extra-plugin-user-preferences')())
* const browser = await puppeteer.launch(...)
*/
use (plugin) {
if ((typeof plugin !== 'object') || !plugin._isPuppeteerExtraPlugin) {
console.error(`Warning: Plugin is not derived from PuppeteerExtraPlugin, ignoring.`, plugin)
return this
}
if (!plugin.name) {
console.error(`Warning: Plugin with no name registering, ignoring.`, plugin)
return this
}
if (plugin.requirements.has('dataFromPlugins')) {
plugin.getDataFromPlugins = this.getPluginData.bind(this)
}
plugin._register(Object.getPrototypeOf(plugin))
this._plugins.push(plugin)
debug('plugin registered', plugin.name)
return this
}
/**
* Launch a new browser instance with given arguments.
*
* Augments the original `puppeteer.launch` method with plugin lifecycle methods.
*
* All registered plugins that have a `beforeLaunch` method will be called
* in sequence to potentially update the `options` Object before launching the browser.
*
* @todo pass `defaultArgs` to `beforeLaunch` calls to plugins.
*
* @param {Object=} options - Regular [Puppeteer launch options](https://github.com/GoogleChrome/puppeteer/blob/master/docs/api.md#puppeteerlaunchoptions)
* @return {Puppeteer.Browser}
*/
async launch (options = {}) {
options = merge(this._defaultLaunchOptions, options)
this.resolvePluginDependencies()
this.orderPlugins()
// Give plugins the chance to modify the options before launch
options = await this.callPluginsWithValue('beforeLaunch', options)
const opts = { context: 'launch', options, defaultArgs: this.defaultArgs }
// Let's check requirements after plugin had the chance to modify the options
this.checkPluginRequirements(opts)
const browser = await Puppeteer.launch(options)
this._patchPageCreationMethods(browser)
await this.callPlugins('_bindBrowserEvents', browser, opts)
return browser
}
/**
* Attach Puppeteer to an existing Chromium instance.
*
* Augments the original `puppeteer.connect` method with plugin lifecycle methods.
*
* All registered plugins that have a `beforeConnect` method will be called
* in sequence to potentially update the `options` Object before launching the browser.
*
* @param {{browserWSEndpoint: string, ignoreHTTPSErrors: boolean}} options
* @return {Promise<!Puppeteer.Browser>}
*/
async connect (options = {}) {
this.resolvePluginDependencies()
this.orderPlugins()
// Give plugins the chance to modify the options before connect
options = await this.callPluginsWithValue('beforeConnect', options)
const opts = { context: 'connect', options }
// Let's check requirements after plugin had the chance to modify the options
this.checkPluginRequirements(opts)
const browser = await Puppeteer.connect(options)
this._patchPageCreationMethods(browser)
await this.callPlugins('_bindBrowserEvents', browser, opts)
return browser
}
/**
* Patch page creation methods (both regular and incognito contexts).
*
* Unfortunately it's possible that the `targetcreated` events are not triggered
* early enough for listeners (e.g. plugins using `onPageCreated`) to be able to
* modify the page instance (e.g. user-agent) before the browser request occurs.
*
* This only affects the first request of a newly created page target.
*
* As a workaround I've noticed that navigating to `about:blank` (again),
* right after a page has been created reliably fixes this issue and adds
* no noticable delay or side-effects.
*
* This problem is not specific to `puppeteer-extra` but default Puppeteer behaviour.
*
* Note: This patch only fixes explicitly created pages, implicitly created ones
* (e.g. through `window.open`) are still subject to this issue. I didn't find a
* reliable mitigation for implicitly created pages yet.
*
* Puppeteer issues:
* https://github.com/GoogleChrome/puppeteer/issues/2669
* https://github.com/GoogleChrome/puppeteer/issues/386#issuecomment-343059315
* https://github.com/GoogleChrome/puppeteer/issues/1378#issue-273733905
*
* @private
*/
_patchPageCreationMethods (browser) {
browser._createPageInContext = (function (originalMethod, context) {
return async (contextId) => {
const page = await originalMethod.apply(context, arguments)
await page.goto('about:blank')
return page
}
})(browser._createPageInContext, browser)
}
/**
* Get all registered plugins.
*
* @member {Array<PuppeteerExtraPlugin>}
*/
get plugins () { return this._plugins }
/**
* Get the names of all registered plugins.
*
* @member {Array<string>}
* @private
*/
get pluginNames () { return this._plugins.map(p => p.name) }
/**
* Collects the exposed `data` property of all registered plugins.
* Will be reduced/flattened to a single array.
*
* Can be accessed by plugins that listed the `dataFromPlugins` requirement.
*
* Implemented mainly for plugins that need data from other plugins (e.g. `user-preferences`).
*
* @see puppeteer-extra-plugin/data
* @param {string=} name - Filter data by name property
* @return {Array<Object>}
*/
getPluginData (name = null) {
const data = this._plugins
.map(p => Array.isArray(p.data) ? p.data : [p.data])
.reduce((acc, arr) => [...acc, ...arr], [])
return name ? data.filter(d => d.name === name) : data
}
/**
* Get all plugins that feature a given property/class method.
*
* @param {string} prop
* @return {Array<PuppeteerExtraPlugin>}
* @private
*/
getPluginsByProp (prop) {
return this._plugins.filter(plugin => (prop in plugin))
}
/**
* Lightweight plugin dependency management to require plugins and code mods on demand.
*
* This uses the `dependencies` stanza (a `Set`) exposed by `puppeteer-extra` plugins.
*
* @todo Allow objects as depdencies that contains opts for the requested plugin.
*
* @private
*/
resolvePluginDependencies () {
// Request missing dependencies from all plugins and flatten to a single Set
const missingPlugins = this._plugins
.map(p => p._getMissingDependencies(this._plugins))
.reduce((combined, list) => {
return new Set([...combined, ...list])
}, new Set())
if (!missingPlugins.size) {
debug('no dependencies are missing')
return
}
debug('dependencies missing', missingPlugins)
// Loop through all dependencies declared missing by plugins
for (let name of [...missingPlugins]) {
// Check if the dependency hasn't been registered as plugin already.
// This might happen when multiple plugins have nested dependencies.
if (this.pluginNames.includes(name)) {
debug(`ignoring dependency '${name}', which has been required already.`)
continue
}
// We follow a plugin naming convention, but let's rather enforce it <3
name = name.startsWith('puppeteer-extra-plugin') ? name : `puppeteer-extra-plugin-${name}`
// In case a module sub resource is requested print out the main package name
// e.g. puppeteer-extra-plugin-stealth/evasions/console.debug => puppeteer-extra-plugin-stealth
const packageName = name.split('/')[0]
let dep = null
try {
// Try to require and instantiate the stated dependency
dep = require(name)()
// Register it with `puppeteer-extra` as plugin
this.use(dep)
} catch (err) {
console.warn(`
A plugin listed '${name}' as dependency,
which is currently missing. Please install it:
yarn add ${packageName}
Note: You don't need to require the plugin yourself,
unless you want to modify it's default settings.
`)
throw err
}
// Handle nested dependencies :D
if (dep.dependencies.size) {
this.resolvePluginDependencies()
}
}
}
/**
* Order plugins that have expressed a special placement requirement.
*
* This is useful/necessary for e.g. plugins that depend on the data from other plugins.
*
* @todo Support more than 'runLast'.
* @todo If there are multiple plugins defining 'runLast', sort them depending on who depends on whom. :D
*
* @private
*/
orderPlugins () {
debug('orderPlugins:before', this.pluginNames)
const runLast = this._plugins
.filter(p => p.requirements.has('runLast'))
.map(p => p.name)
for (const name of runLast) {
const index = this._plugins.findIndex(p => p.name === name)
this._plugins.push(this._plugins.splice(index, 1)[0])
}
debug('orderPlugins:after', this.pluginNames)
}
/**
* Lightweight plugin requirement checking.
*
* The main intent is to notify the user when a plugin won't work as expected.
*
* @todo This could be improved, e.g. be evaluated by the plugin base class.
*
* @private
*/
checkPluginRequirements (opts = {}) {
for (const plugin of this._plugins) {
for (const requirement of plugin.requirements) {
if ((opts.context === 'launch') && (requirement === 'headful') && opts.options.headless) {
console.warn(`Warning: Plugin '${plugin.name}' is not supported in headless mode.`)
}
if ((opts.context === 'connect') && (requirement === 'launch')) {
console.warn(`Warning: Plugin '${plugin.name}' doesn't support puppeteer.connect().`)
}
}
}
}
/**
* Call plugins sequentially with the same values.
* Plugins that expose the supplied property will be called.
*
* @param {string} prop - The plugin property to call
* @param {...*} values - Any number of values
* @private
*/
async callPlugins (prop, ...values) {
for (const plugin of this.getPluginsByProp(prop)) {
await plugin[prop].apply(plugin, values)
}
}
/**
* Call plugins sequentially and pass on a value (waterfall style).
* Plugins that expose the supplied property will be called.
*
* The plugins can either modify the value or return an updated one.
* Will return the latest, updated value which ran through all plugins.
*
* @param {string} prop - The plugin property to call
* @param {*} value - Any value
* @return {*} - The new updated value
* @private
*/
async callPluginsWithValue (prop, value) {
for (const plugin of this.getPluginsByProp(prop)) {
const newValue = await plugin[prop](value)
if (newValue) { value = newValue }
}
return value
}
/**
* Regular Puppeteer method that is being passed through.
*
* @return {string}
*/
executablePath () {
return Puppeteer.executablePath()
}
/**
* Regular Puppeteer method that is being passed through.
*
* @return {Array<string>}
*/
defaultArgs () {
return Puppeteer.defaultArgs()
}
/**
* Regular Puppeteer method that is being passed through.
*
* @param {Object=} options
* @return {PuppeteerBrowserFetcher}
*/
createBrowserFetcher (options) {
return new PuppeteerBrowserFetcher(options)
}
}
module.exports = new PuppeteerExtra()