@crawlee/browser-pool 4.0.0-beta.14 → 4.0.0-beta.140
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +14 -14
- package/abstract-classes/browser-controller.d.ts +70 -13
- package/abstract-classes/browser-controller.js +21 -22
- package/abstract-classes/browser-plugin.d.ts +48 -15
- package/abstract-classes/browser-plugin.js +69 -11
- package/anonymize-proxy.d.ts +5 -2
- package/anonymize-proxy.js +9 -5
- package/browser-pool.d.ts +100 -28
- package/browser-pool.js +198 -77
- package/container-proxy-server.d.ts +0 -1
- package/container-proxy-server.js +0 -1
- package/events.d.ts +2 -3
- package/events.js +0 -1
- package/fingerprinting/hooks.d.ts +0 -1
- package/fingerprinting/hooks.js +26 -10
- package/fingerprinting/types.d.ts +2 -3
- package/fingerprinting/types.js +0 -1
- package/fingerprinting/utils.d.ts +0 -1
- package/fingerprinting/utils.js +5 -6
- package/index.d.ts +14 -7
- package/index.js +5 -3
- package/launch-context.d.ts +20 -5
- package/launch-context.js +21 -10
- package/package.json +9 -9
- package/playwright/playwright-browser.d.ts +2 -6
- package/playwright/playwright-browser.js +16 -17
- package/playwright/playwright-controller.d.ts +0 -1
- package/playwright/playwright-controller.js +6 -3
- package/playwright/playwright-plugin.d.ts +10 -7
- package/playwright/playwright-plugin.js +40 -16
- package/proxy-server.d.ts +0 -1
- package/proxy-server.js +0 -1
- package/puppeteer/puppeteer-controller.d.ts +0 -1
- package/puppeteer/puppeteer-controller.js +16 -9
- package/puppeteer/puppeteer-plugin.d.ts +5 -3
- package/puppeteer/puppeteer-plugin.js +83 -46
- package/remote-browser-pool.d.ts +165 -0
- package/remote-browser-pool.js +195 -0
- package/remote-browser-provider.d.ts +83 -0
- package/remote-browser-provider.js +67 -0
- package/utils.d.ts +7 -1
- package/utils.js +19 -1
- package/abstract-classes/browser-controller.d.ts.map +0 -1
- package/abstract-classes/browser-controller.js.map +0 -1
- package/abstract-classes/browser-plugin.d.ts.map +0 -1
- package/abstract-classes/browser-plugin.js.map +0 -1
- package/anonymize-proxy.d.ts.map +0 -1
- package/anonymize-proxy.js.map +0 -1
- package/browser-pool.d.ts.map +0 -1
- package/browser-pool.js.map +0 -1
- package/container-proxy-server.d.ts.map +0 -1
- package/container-proxy-server.js.map +0 -1
- package/events.d.ts.map +0 -1
- package/events.js.map +0 -1
- package/fingerprinting/hooks.d.ts.map +0 -1
- package/fingerprinting/hooks.js.map +0 -1
- package/fingerprinting/types.d.ts.map +0 -1
- package/fingerprinting/types.js.map +0 -1
- package/fingerprinting/utils.d.ts.map +0 -1
- package/fingerprinting/utils.js.map +0 -1
- package/index.d.ts.map +0 -1
- package/index.js.map +0 -1
- package/launch-context.d.ts.map +0 -1
- package/launch-context.js.map +0 -1
- package/logger.d.ts +0 -3
- package/logger.d.ts.map +0 -1
- package/logger.js +0 -5
- package/logger.js.map +0 -1
- package/playwright/playwright-browser.d.ts.map +0 -1
- package/playwright/playwright-browser.js.map +0 -1
- package/playwright/playwright-controller.d.ts.map +0 -1
- package/playwright/playwright-controller.js.map +0 -1
- package/playwright/playwright-plugin.d.ts.map +0 -1
- package/playwright/playwright-plugin.js.map +0 -1
- package/proxy-server.d.ts.map +0 -1
- package/proxy-server.js.map +0 -1
- package/puppeteer/puppeteer-controller.d.ts.map +0 -1
- package/puppeteer/puppeteer-controller.js.map +0 -1
- package/puppeteer/puppeteer-plugin.d.ts.map +0 -1
- package/puppeteer/puppeteer-plugin.js.map +0 -1
- package/utils.d.ts.map +0 -1
- package/utils.js.map +0 -1
package/browser-pool.js
CHANGED
|
@@ -1,15 +1,35 @@
|
|
|
1
|
+
import { AsyncResource } from 'node:async_hooks';
|
|
2
|
+
import { SessionError, serviceLocator } from '@crawlee/core';
|
|
3
|
+
import { parseArgument, schemas } from '@crawlee/utils/internal';
|
|
1
4
|
import { FingerprintGenerator } from 'fingerprint-generator';
|
|
2
5
|
import { FingerprintInjector } from 'fingerprint-injector';
|
|
3
6
|
import { nanoid } from 'nanoid';
|
|
4
|
-
import ow from 'ow';
|
|
5
7
|
import pLimit from 'p-limit';
|
|
6
8
|
import QuickLRU from 'quick-lru';
|
|
7
9
|
import { TypedEmitter } from 'tiny-typed-emitter';
|
|
10
|
+
import { z } from 'zod';
|
|
8
11
|
import { addTimeoutToPromise, tryCancel } from '@apify/timeout';
|
|
12
|
+
import { BROWSER_POOL_EVENTS } from './events.js';
|
|
9
13
|
import { createFingerprintPreLaunchHook, createPostPageCreateHook, createPrePageCreateHook, } from './fingerprinting/hooks.js';
|
|
10
|
-
|
|
14
|
+
const PAGE_CLOSE_TIMEOUT_MILLIS = 5000;
|
|
11
15
|
const PAGE_CLOSE_KILL_TIMEOUT_MILLIS = 1000;
|
|
12
16
|
const BROWSER_KILLER_INTERVAL_MILLIS = 10 * 1000;
|
|
17
|
+
const browserPoolOptionsSchema = z.strictObject({
|
|
18
|
+
browserPlugins: schemas.anyArray.refine((value) => value.length >= 1, 'Expected a non-empty array'),
|
|
19
|
+
maxOpenPagesPerBrowser: schemas.anyNumber.default(20),
|
|
20
|
+
retireBrowserAfterPageCount: schemas.anyNumber.default(100),
|
|
21
|
+
operationTimeoutSecs: schemas.anyNumber.default(15),
|
|
22
|
+
closeInactiveBrowserAfterSecs: schemas.anyNumber.default(300),
|
|
23
|
+
retireInactiveBrowserAfterSecs: schemas.anyNumber.default(10),
|
|
24
|
+
preLaunchHooks: schemas.anyArray.default(() => []),
|
|
25
|
+
postLaunchHooks: schemas.anyArray.default(() => []),
|
|
26
|
+
prePageCreateHooks: schemas.anyArray.default(() => []),
|
|
27
|
+
postPageCreateHooks: schemas.anyArray.default(() => []),
|
|
28
|
+
prePageCloseHooks: schemas.anyArray.default(() => []),
|
|
29
|
+
postPageCloseHooks: schemas.anyArray.default(() => []),
|
|
30
|
+
useFingerprints: z.boolean().default(true),
|
|
31
|
+
fingerprintOptions: schemas.anyObject.default(() => ({})),
|
|
32
|
+
});
|
|
13
33
|
/**
|
|
14
34
|
* The `BrowserPool` class is the most important class of the `browser-pool` module.
|
|
15
35
|
* It manages opening and closing of browsers and their pages and its constructor
|
|
@@ -60,6 +80,7 @@ const BROWSER_KILLER_INTERVAL_MILLIS = 10 * 1000;
|
|
|
60
80
|
export class BrowserPool extends TypedEmitter {
|
|
61
81
|
browserPlugins;
|
|
62
82
|
maxOpenPagesPerBrowser;
|
|
83
|
+
maxOpenBrowsers;
|
|
63
84
|
retireBrowserAfterPageCount;
|
|
64
85
|
operationTimeoutMillis;
|
|
65
86
|
closeInactiveBrowserAfterMillis;
|
|
@@ -81,29 +102,16 @@ export class BrowserPool extends TypedEmitter {
|
|
|
81
102
|
fingerprintInjector;
|
|
82
103
|
fingerprintGenerator;
|
|
83
104
|
fingerprintCache;
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
105
|
+
// kept as TS-private: tests replace this interval through bracket access
|
|
106
|
+
browserKillerInterval = setInterval(async () => this.closeInactiveRetiredBrowsers(), BROWSER_KILLER_INTERVAL_MILLIS);
|
|
107
|
+
#browserRetireInterval;
|
|
108
|
+
#limiter = pLimit(1);
|
|
109
|
+
#log;
|
|
87
110
|
constructor(options) {
|
|
88
111
|
super();
|
|
112
|
+
this.#log = serviceLocator.getLogger().child({ prefix: 'BrowserPool' });
|
|
89
113
|
this.browserKillerInterval.unref();
|
|
90
|
-
|
|
91
|
-
browserPlugins: ow.array.minLength(1),
|
|
92
|
-
maxOpenPagesPerBrowser: ow.optional.number,
|
|
93
|
-
retireBrowserAfterPageCount: ow.optional.number,
|
|
94
|
-
operationTimeoutSecs: ow.optional.number,
|
|
95
|
-
closeInactiveBrowserAfterSecs: ow.optional.number,
|
|
96
|
-
retireInactiveBrowserAfterSecs: ow.optional.number,
|
|
97
|
-
preLaunchHooks: ow.optional.array,
|
|
98
|
-
postLaunchHooks: ow.optional.array,
|
|
99
|
-
prePageCreateHooks: ow.optional.array,
|
|
100
|
-
postPageCreateHooks: ow.optional.array,
|
|
101
|
-
prePageCloseHooks: ow.optional.array,
|
|
102
|
-
postPageCloseHooks: ow.optional.array,
|
|
103
|
-
useFingerprints: ow.optional.boolean,
|
|
104
|
-
fingerprintOptions: ow.optional.object,
|
|
105
|
-
}));
|
|
106
|
-
const { browserPlugins, maxOpenPagesPerBrowser = 20, retireBrowserAfterPageCount = 100, operationTimeoutSecs = 15, closeInactiveBrowserAfterSecs = 300, retireInactiveBrowserAfterSecs = 10, preLaunchHooks = [], postLaunchHooks = [], prePageCreateHooks = [], postPageCreateHooks = [], prePageCloseHooks = [], postPageCloseHooks = [], useFingerprints = true, fingerprintOptions = {}, } = options;
|
|
114
|
+
const { browserPlugins, maxOpenPagesPerBrowser, retireBrowserAfterPageCount, operationTimeoutSecs, closeInactiveBrowserAfterSecs, retireInactiveBrowserAfterSecs, preLaunchHooks, postLaunchHooks, prePageCreateHooks, postPageCreateHooks, prePageCloseHooks, postPageCloseHooks, useFingerprints, fingerprintOptions, } = parseArgument(options, browserPoolOptionsSchema);
|
|
107
115
|
const firstPluginConstructor = browserPlugins[0].constructor;
|
|
108
116
|
for (let i = 1; i < browserPlugins.length; i++) {
|
|
109
117
|
const providedPlugin = browserPlugins[i];
|
|
@@ -115,18 +123,19 @@ export class BrowserPool extends TypedEmitter {
|
|
|
115
123
|
}
|
|
116
124
|
this.browserPlugins = browserPlugins;
|
|
117
125
|
this.maxOpenPagesPerBrowser = maxOpenPagesPerBrowser;
|
|
126
|
+
this.maxOpenBrowsers = Infinity;
|
|
118
127
|
this.retireBrowserAfterPageCount = retireBrowserAfterPageCount;
|
|
119
128
|
this.operationTimeoutMillis = operationTimeoutSecs * 1000;
|
|
120
129
|
this.closeInactiveBrowserAfterMillis = closeInactiveBrowserAfterSecs * 1000;
|
|
121
130
|
this.useFingerprints = useFingerprints;
|
|
122
131
|
this.fingerprintOptions = fingerprintOptions;
|
|
123
|
-
this
|
|
132
|
+
this.#browserRetireInterval = setInterval(async () => this.activeBrowserControllers.forEach((controller) => {
|
|
124
133
|
if (controller.activePages === 0 &&
|
|
125
134
|
controller.lastPageOpenedAt < Date.now() - retireInactiveBrowserAfterSecs * 1000) {
|
|
126
135
|
this.retireBrowserController(controller);
|
|
127
136
|
}
|
|
128
137
|
}), retireInactiveBrowserAfterSecs * 1000);
|
|
129
|
-
this
|
|
138
|
+
this.#browserRetireInterval.unref();
|
|
130
139
|
// hooks
|
|
131
140
|
this.preLaunchHooks = preLaunchHooks;
|
|
132
141
|
this.postLaunchHooks = postLaunchHooks;
|
|
@@ -136,30 +145,56 @@ export class BrowserPool extends TypedEmitter {
|
|
|
136
145
|
this.postPageCloseHooks = postPageCloseHooks;
|
|
137
146
|
// fingerprinting
|
|
138
147
|
if (this.useFingerprints) {
|
|
139
|
-
this.
|
|
148
|
+
this.initializeFingerprinting();
|
|
140
149
|
}
|
|
141
150
|
}
|
|
142
151
|
/**
|
|
143
152
|
* Opens a new page in one of the running browsers or launches
|
|
144
153
|
* a new browser and opens a page there, if no browsers are active,
|
|
145
154
|
* or their page limits have been exceeded.
|
|
155
|
+
*
|
|
156
|
+
* **Session injection (best-effort):** When a {@link NewPageOptions.session|session} is
|
|
157
|
+
* provided, this implementation uses it as a cache key for browser fingerprints (when
|
|
158
|
+
* fingerprinting is enabled) and reads
|
|
159
|
+
* {@link ProxyInfo.url|session.proxyInfo.url} /
|
|
160
|
+
* {@link ProxyInfo.ignoreTlsErrors|session.proxyInfo.ignoreTlsErrors} as defaults
|
|
161
|
+
* for `proxyUrl` and `ignoreTlsErrors` respectively. Explicit `proxyUrl` /
|
|
162
|
+
* `ignoreTlsErrors` values in the options take precedence.
|
|
163
|
+
*
|
|
164
|
+
* Beyond fingerprint caching and proxy configuration, no other session
|
|
165
|
+
* properties are consumed — cookie and header injection remain the
|
|
166
|
+
* crawler's responsibility.
|
|
146
167
|
*/
|
|
147
168
|
async newPage(options = {}) {
|
|
148
|
-
const { id = nanoid(), pageOptions, browserPlugin = this.
|
|
169
|
+
const { id = nanoid(), pageOptions, browserPlugin = this.pickBrowserPlugin(), session, proxyUrl = session?.proxyInfo?.url, ignoreTlsErrors = session?.proxyInfo?.ignoreTlsErrors, } = options;
|
|
149
170
|
if (this.pages.has(id)) {
|
|
150
171
|
throw new Error(`Page with ID: ${id} already exists.`);
|
|
151
172
|
}
|
|
152
173
|
if (browserPlugin && !this.browserPlugins.includes(browserPlugin)) {
|
|
153
174
|
throw new Error('Provided browserPlugin is not one of the plugins used by BrowserPool.');
|
|
154
175
|
}
|
|
176
|
+
// Bind the limiter callback to the current async-hooks context. p-limit
|
|
177
|
+
// otherwise resumes queued callbacks in the previous task's
|
|
178
|
+
// AsyncLocalStorage context, leaking aborted cancelTasks across unrelated
|
|
179
|
+
// requests (https://github.com/apify/crawlee/issues/3670). Mirrors the
|
|
180
|
+
// fix p-limit landed upstream in v5 (sindresorhus/p-limit#71); v5 is an
|
|
181
|
+
// ESM-only rewrite, so we can't bump it in Crawlee v3.
|
|
182
|
+
// Besides the cancelTask leak, the wrapper also keeps the per-request *storage transaction*
|
|
183
|
+
// ALS-scoped: without it, a queued callback would resume in the previous request's async
|
|
184
|
+
// context and run request B's storage writes inside request A's transaction.
|
|
185
|
+
// TODO(crawlee@v4): bump p-limit to v5 and drop this AsyncResource.bind wrapper.
|
|
155
186
|
// Limiter is necessary - https://github.com/apify/crawlee/issues/1126
|
|
156
|
-
return this
|
|
157
|
-
let browserController = this.
|
|
187
|
+
return this.#limiter(AsyncResource.bind(async () => {
|
|
188
|
+
let browserController = this.pickBrowserWithFreeCapacity(browserPlugin, { proxyUrl });
|
|
158
189
|
if (!browserController)
|
|
159
|
-
browserController = await this.
|
|
190
|
+
browserController = await this.launchBrowser(id, {
|
|
191
|
+
browserPlugin,
|
|
192
|
+
proxyUrl,
|
|
193
|
+
ignoreTlsErrors,
|
|
194
|
+
});
|
|
160
195
|
tryCancel();
|
|
161
|
-
return await this.
|
|
162
|
-
});
|
|
196
|
+
return await this.createPageForBrowser(id, browserController, pageOptions, proxyUrl, ignoreTlsErrors);
|
|
197
|
+
}));
|
|
163
198
|
}
|
|
164
199
|
/**
|
|
165
200
|
* Unlike {@link newPage}, `newPageInNewBrowser` always launches a new
|
|
@@ -167,13 +202,13 @@ export class BrowserPool extends TypedEmitter {
|
|
|
167
202
|
* configure the new browser.
|
|
168
203
|
*/
|
|
169
204
|
async newPageInNewBrowser(options = {}) {
|
|
170
|
-
const { id = nanoid(), pageOptions, launchOptions, browserPlugin = this.
|
|
205
|
+
const { id = nanoid(), pageOptions, launchOptions, browserPlugin = this.pickBrowserPlugin() } = options;
|
|
171
206
|
if (this.pages.has(id)) {
|
|
172
207
|
throw new Error(`Page with ID: ${id} already exists.`);
|
|
173
208
|
}
|
|
174
|
-
const browserController = await this.
|
|
209
|
+
const browserController = await this.launchBrowser(id, { launchOptions, browserPlugin });
|
|
175
210
|
tryCancel();
|
|
176
|
-
return await this.
|
|
211
|
+
return await this.createPageForBrowser(id, browserController, pageOptions);
|
|
177
212
|
}
|
|
178
213
|
/**
|
|
179
214
|
* Opens new pages with all available plugins and returns an array
|
|
@@ -239,7 +274,7 @@ export class BrowserPool extends TypedEmitter {
|
|
|
239
274
|
getPageId(page) {
|
|
240
275
|
return this.pageIds.get(page);
|
|
241
276
|
}
|
|
242
|
-
async
|
|
277
|
+
async createPageForBrowser(pageId, browserController, pageOptions = {}, proxyUrl, ignoreTlsErrors) {
|
|
243
278
|
// This is needed for concurrent newPage calls to wait for the browser launch.
|
|
244
279
|
// It's not ideal though, we need to come up with a better API.
|
|
245
280
|
// eslint-disable-next-line dot-notation -- accessing private property
|
|
@@ -248,8 +283,14 @@ export class BrowserPool extends TypedEmitter {
|
|
|
248
283
|
const finalPageOptions = browserController.launchContext.useIncognitoPages ? pageOptions : undefined;
|
|
249
284
|
if (finalPageOptions) {
|
|
250
285
|
Object.assign(finalPageOptions, browserController.normalizeProxyOptions(proxyUrl, pageOptions));
|
|
286
|
+
if (ignoreTlsErrors) {
|
|
287
|
+
Object.assign(finalPageOptions, {
|
|
288
|
+
ignoreHTTPSErrors: true,
|
|
289
|
+
acceptInsecureCerts: true,
|
|
290
|
+
});
|
|
291
|
+
}
|
|
251
292
|
}
|
|
252
|
-
await this.
|
|
293
|
+
await this.executeHooks(this.prePageCreateHooks, pageId, browserController, finalPageOptions);
|
|
253
294
|
tryCancel();
|
|
254
295
|
let page;
|
|
255
296
|
try {
|
|
@@ -262,15 +303,15 @@ export class BrowserPool extends TypedEmitter {
|
|
|
262
303
|
if (browserController.totalPages >= this.retireBrowserAfterPageCount) {
|
|
263
304
|
this.retireBrowserController(browserController);
|
|
264
305
|
}
|
|
265
|
-
this.
|
|
306
|
+
this.overridePageClose(page);
|
|
266
307
|
}
|
|
267
308
|
catch (err) {
|
|
268
309
|
this.retireBrowserController(browserController);
|
|
269
310
|
throw new Error(`browserController.newPage() failed: ${browserController.id}\nCause:${err.message}.`);
|
|
270
311
|
}
|
|
271
|
-
await this.
|
|
312
|
+
await this.executeHooks(this.postPageCreateHooks, page, browserController);
|
|
272
313
|
tryCancel();
|
|
273
|
-
this.emit(
|
|
314
|
+
this.emit(BROWSER_POOL_EVENTS.PAGE_CREATED, page);
|
|
274
315
|
return page;
|
|
275
316
|
}
|
|
276
317
|
/**
|
|
@@ -285,7 +326,7 @@ export class BrowserPool extends TypedEmitter {
|
|
|
285
326
|
if (hasBeenRetiredOrKilled)
|
|
286
327
|
return;
|
|
287
328
|
this.retiredBrowserControllers.add(browserController);
|
|
288
|
-
this.emit(
|
|
329
|
+
this.emit(BROWSER_POOL_EVENTS.BROWSER_RETIRED, browserController);
|
|
289
330
|
this.startingBrowserControllers.delete(browserController);
|
|
290
331
|
this.activeBrowserControllers.delete(browserController);
|
|
291
332
|
}
|
|
@@ -298,6 +339,59 @@ export class BrowserPool extends TypedEmitter {
|
|
|
298
339
|
if (browserController)
|
|
299
340
|
this.retireBrowserController(browserController);
|
|
300
341
|
}
|
|
342
|
+
/**
|
|
343
|
+
* Releases a page back to the pool. The page is closed and, if the
|
|
344
|
+
* optional `error` is a {@link SessionError}, the browser controller
|
|
345
|
+
* that served the page is retired so that its tainted state (cookies,
|
|
346
|
+
* storage, etc.) cannot leak into future sessions.
|
|
347
|
+
*
|
|
348
|
+
* This is the primary way the crawler should return pages to the pool.
|
|
349
|
+
*
|
|
350
|
+
* @param page The page to release.
|
|
351
|
+
* @param options.error The error that caused the page to be released, if any.
|
|
352
|
+
*/
|
|
353
|
+
async closePage(page, options) {
|
|
354
|
+
if (options?.error instanceof SessionError) {
|
|
355
|
+
this.retireBrowserByPage(page);
|
|
356
|
+
}
|
|
357
|
+
// Puppeteer 25+ can hang `page.close()` indefinitely when the page's navigation was aborted, don't let it block the crawler.
|
|
358
|
+
await addTimeoutToPromise(async () => page.close(), PAGE_CLOSE_TIMEOUT_MILLIS, `page.close() timed out after ${PAGE_CLOSE_TIMEOUT_MILLIS / 1000} seconds`);
|
|
359
|
+
}
|
|
360
|
+
/**
|
|
361
|
+
* Extracts the relevant state (currently just cookies) from a page via its
|
|
362
|
+
* owning {@link BrowserController}. Returns empty state when the page is
|
|
363
|
+
* no longer associated with a controller.
|
|
364
|
+
*
|
|
365
|
+
* As with {@link BrowserPool.injectPageState}, cookies are isolated per
|
|
366
|
+
* page only when the pool is configured with `useIncognitoPages: true`.
|
|
367
|
+
* With the default `useIncognitoPages: false`, the extracted cookies
|
|
368
|
+
* include those set by any sibling page sharing the same browser.
|
|
369
|
+
*/
|
|
370
|
+
async extractPageState(page) {
|
|
371
|
+
const controller = this.getBrowserControllerByPage(page);
|
|
372
|
+
if (!controller) {
|
|
373
|
+
return { cookies: [] };
|
|
374
|
+
}
|
|
375
|
+
return { cookies: await controller.getCookies(page) };
|
|
376
|
+
}
|
|
377
|
+
/**
|
|
378
|
+
* Injects state into a page via its owning {@link BrowserController}.
|
|
379
|
+
*
|
|
380
|
+
* No-op when the page is no longer associated with a controller.
|
|
381
|
+
*
|
|
382
|
+
* Note that cookies are isolated per page only when the pool is configured
|
|
383
|
+
* with `useIncognitoPages: true` — each page then gets its own browser
|
|
384
|
+
* context. With the default `useIncognitoPages: false`, all pages in a
|
|
385
|
+
* browser share a single context, so injected cookies are visible to every
|
|
386
|
+
* page served by that browser.
|
|
387
|
+
*/
|
|
388
|
+
async injectPageState(page, state) {
|
|
389
|
+
const controller = this.getBrowserControllerByPage(page);
|
|
390
|
+
if (!controller) {
|
|
391
|
+
return;
|
|
392
|
+
}
|
|
393
|
+
await controller.setCookies(page, state.cookies);
|
|
394
|
+
}
|
|
301
395
|
/**
|
|
302
396
|
* Removes all active browsers from the pool. The browsers will be
|
|
303
397
|
* closed after all their pages are closed.
|
|
@@ -312,50 +406,61 @@ export class BrowserPool extends TypedEmitter {
|
|
|
312
406
|
* @return {Promise<void>}
|
|
313
407
|
*/
|
|
314
408
|
async closeAllBrowsers() {
|
|
315
|
-
const controllers = this.
|
|
409
|
+
const controllers = this.getAllBrowserControllers();
|
|
316
410
|
const promises = [...controllers]
|
|
317
411
|
.filter((controller) => controller.isActive)
|
|
318
412
|
.map(async (controller) => controller.close());
|
|
319
413
|
await Promise.all(promises);
|
|
320
414
|
}
|
|
415
|
+
async [Symbol.asyncDispose]() {
|
|
416
|
+
await this.destroy();
|
|
417
|
+
}
|
|
321
418
|
/**
|
|
322
419
|
* Closes all managed browsers and tears down the pool.
|
|
323
420
|
*/
|
|
324
421
|
async destroy() {
|
|
325
422
|
clearInterval(this.browserKillerInterval);
|
|
326
|
-
clearInterval(this
|
|
423
|
+
clearInterval(this.#browserRetireInterval);
|
|
327
424
|
this.browserKillerInterval = undefined;
|
|
328
|
-
this
|
|
425
|
+
this.#browserRetireInterval = undefined;
|
|
329
426
|
await this.closeAllBrowsers();
|
|
330
|
-
this.
|
|
427
|
+
this.teardown();
|
|
331
428
|
}
|
|
332
|
-
|
|
429
|
+
teardown() {
|
|
333
430
|
this.startingBrowserControllers.clear();
|
|
334
431
|
this.activeBrowserControllers.clear();
|
|
335
432
|
this.retiredBrowserControllers.clear();
|
|
336
433
|
this.removeAllListeners();
|
|
337
434
|
}
|
|
338
|
-
|
|
435
|
+
getAllBrowserControllers() {
|
|
339
436
|
return new Set([
|
|
340
437
|
...this.startingBrowserControllers,
|
|
341
438
|
...this.activeBrowserControllers,
|
|
342
439
|
...this.retiredBrowserControllers,
|
|
343
440
|
]);
|
|
344
441
|
}
|
|
345
|
-
async
|
|
346
|
-
const { browserPlugin, launchOptions,
|
|
442
|
+
async launchBrowser(pageId, options) {
|
|
443
|
+
const { browserPlugin, launchOptions, proxyUrl, ignoreTlsErrors } = options;
|
|
347
444
|
const browserController = browserPlugin.createController();
|
|
348
445
|
this.startingBrowserControllers.add(browserController);
|
|
349
446
|
const launchContext = browserPlugin.createLaunchContext({
|
|
350
447
|
id: pageId,
|
|
351
448
|
launchOptions,
|
|
352
|
-
proxyTier,
|
|
353
449
|
proxyUrl,
|
|
354
450
|
});
|
|
451
|
+
// Disable SSL verification for MITM proxies
|
|
452
|
+
if (ignoreTlsErrors) {
|
|
453
|
+
/**
|
|
454
|
+
* @see https://playwright.dev/docs/api/class-browser/#browser-new-context
|
|
455
|
+
* @see https://github.com/puppeteer/puppeteer/blob/main/docs/api.md
|
|
456
|
+
*/
|
|
457
|
+
launchContext.launchOptions.ignoreHTTPSErrors = true;
|
|
458
|
+
launchContext.launchOptions.acceptInsecureCerts = true;
|
|
459
|
+
}
|
|
355
460
|
try {
|
|
356
461
|
// If the hooks or the launch fails, we need to delete the controller,
|
|
357
462
|
// because otherwise it would be stuck in limbo without a browser.
|
|
358
|
-
await this.
|
|
463
|
+
await this.executeHooks(this.preLaunchHooks, pageId, launchContext);
|
|
359
464
|
tryCancel();
|
|
360
465
|
const browser = await browserPlugin.launch(launchContext);
|
|
361
466
|
tryCancel();
|
|
@@ -365,18 +470,17 @@ export class BrowserPool extends TypedEmitter {
|
|
|
365
470
|
this.startingBrowserControllers.delete(browserController);
|
|
366
471
|
throw err;
|
|
367
472
|
}
|
|
368
|
-
log.debug('Launched new browser.', { id: browserController.id });
|
|
369
|
-
browserController.proxyTier = proxyTier;
|
|
473
|
+
this.#log.debug('Launched new browser.', { id: browserController.id });
|
|
370
474
|
browserController.proxyUrl = proxyUrl;
|
|
371
475
|
try {
|
|
372
476
|
// If the launch fails on the post-launch hooks, we need to clean up
|
|
373
477
|
// both the controller and the browser before throwing.
|
|
374
|
-
await this.
|
|
478
|
+
await this.executeHooks(this.postLaunchHooks, pageId, browserController);
|
|
375
479
|
}
|
|
376
480
|
catch (err) {
|
|
377
481
|
this.startingBrowserControllers.delete(browserController);
|
|
378
482
|
browserController.close().catch((closeErr) => {
|
|
379
|
-
log.error(`Could not close browser whose post-launch hooks failed.\nCause:${closeErr.message}`, {
|
|
483
|
+
this.#log.error(`Could not close browser whose post-launch hooks failed.\nCause:${closeErr.message}`, {
|
|
380
484
|
id: browserController.id,
|
|
381
485
|
});
|
|
382
486
|
});
|
|
@@ -386,33 +490,31 @@ export class BrowserPool extends TypedEmitter {
|
|
|
386
490
|
browserController.activate();
|
|
387
491
|
this.startingBrowserControllers.delete(browserController);
|
|
388
492
|
this.activeBrowserControllers.add(browserController);
|
|
389
|
-
this.emit(
|
|
493
|
+
this.emit(BROWSER_POOL_EVENTS.BROWSER_LAUNCHED, browserController);
|
|
390
494
|
return browserController;
|
|
391
495
|
}
|
|
392
496
|
/**
|
|
393
497
|
* Picks plugins round robin.
|
|
394
498
|
* @private
|
|
395
499
|
*/
|
|
396
|
-
|
|
500
|
+
pickBrowserPlugin() {
|
|
397
501
|
const pluginIndex = this.pageCounter % this.browserPlugins.length;
|
|
398
502
|
this.pageCounter++;
|
|
399
503
|
return this.browserPlugins[pluginIndex];
|
|
400
504
|
}
|
|
401
|
-
|
|
505
|
+
pickBrowserWithFreeCapacity(browserPlugin, options) {
|
|
402
506
|
return [...this.activeBrowserControllers].find((controller) => {
|
|
403
507
|
const hasCapacity = controller.activePages < this.maxOpenPagesPerBrowser;
|
|
404
508
|
const isCorrectPlugin = controller.browserPlugin === browserPlugin;
|
|
405
509
|
const isSameProxyUrl = controller.proxyUrl === options?.proxyUrl;
|
|
406
|
-
const isCorrectProxyTier = controller.proxyTier === options?.proxyTier;
|
|
407
510
|
return (isCorrectPlugin &&
|
|
408
511
|
hasCapacity &&
|
|
409
|
-
(
|
|
410
|
-
(options?.proxyTier && isCorrectProxyTier) ||
|
|
512
|
+
(!controller.launchContext.browserPerProxy ||
|
|
411
513
|
(options?.proxyUrl && isSameProxyUrl) ||
|
|
412
|
-
(!options?.proxyUrl && !
|
|
514
|
+
(!options?.proxyUrl && !controller.proxyUrl)));
|
|
413
515
|
});
|
|
414
516
|
}
|
|
415
|
-
async
|
|
517
|
+
async closeInactiveRetiredBrowsers() {
|
|
416
518
|
const closedBrowserIds = [];
|
|
417
519
|
for (const controller of this.retiredBrowserControllers) {
|
|
418
520
|
const millisSinceLastPageOpened = Date.now() - controller.lastPageOpenedAt;
|
|
@@ -420,61 +522,81 @@ export class BrowserPool extends TypedEmitter {
|
|
|
420
522
|
const isBrowserEmpty = controller.activePages === 0;
|
|
421
523
|
if (isBrowserIdle || isBrowserEmpty) {
|
|
422
524
|
const { id } = controller;
|
|
423
|
-
log.debug('Closing retired browser.', { id });
|
|
525
|
+
this.#log.debug('Closing retired browser.', { id });
|
|
424
526
|
await controller.close();
|
|
425
527
|
this.retiredBrowserControllers.delete(controller);
|
|
426
528
|
closedBrowserIds.push(id);
|
|
427
529
|
}
|
|
428
530
|
}
|
|
429
531
|
if (closedBrowserIds.length) {
|
|
430
|
-
log.debug('Closed retired browsers.', {
|
|
532
|
+
this.#log.debug('Closed retired browsers.', {
|
|
431
533
|
count: closedBrowserIds.length,
|
|
432
534
|
closedBrowserIds,
|
|
433
535
|
});
|
|
434
536
|
}
|
|
435
537
|
}
|
|
436
|
-
|
|
538
|
+
overridePageClose(page) {
|
|
437
539
|
const originalPageClose = page.close;
|
|
438
540
|
const browserController = this.pageToBrowserController.get(page);
|
|
439
541
|
const pageId = this.getPageId(page);
|
|
440
542
|
page.close = async (...args) => {
|
|
441
|
-
await this.
|
|
543
|
+
await this.executeHooks(this.prePageCloseHooks, page, browserController);
|
|
442
544
|
await originalPageClose.apply(page, args).catch((err) => {
|
|
443
|
-
log.debug(`Could not close page.\nCause:${err.message}`, { id: browserController.id });
|
|
545
|
+
this.#log.debug(`Could not close page.\nCause:${err.message}`, { id: browserController.id });
|
|
444
546
|
});
|
|
445
|
-
await this.
|
|
547
|
+
await this.executeHooks(this.postPageCloseHooks, pageId, browserController);
|
|
446
548
|
this.pages.delete(pageId);
|
|
447
|
-
this.
|
|
448
|
-
this.emit(
|
|
549
|
+
this.closeRetiredBrowserWithNoPages(browserController);
|
|
550
|
+
this.emit(BROWSER_POOL_EVENTS.PAGE_CLOSED, page);
|
|
449
551
|
};
|
|
450
552
|
}
|
|
451
|
-
async
|
|
553
|
+
async executeHooks(hooks, ...args) {
|
|
452
554
|
for (const hook of hooks) {
|
|
453
555
|
await hook(...args);
|
|
454
556
|
}
|
|
455
557
|
}
|
|
456
|
-
|
|
558
|
+
closeRetiredBrowserWithNoPages(browserController) {
|
|
457
559
|
if (browserController.activePages === 0 && this.retiredBrowserControllers.has(browserController)) {
|
|
458
560
|
// Run this with a delay, otherwise page.close()
|
|
459
561
|
// might fail with "Protocol error (Target.closeTarget): Target closed."
|
|
460
562
|
setTimeout(() => {
|
|
461
|
-
log.debug('Closing retired browser because it has no active pages', { id: browserController.id });
|
|
563
|
+
this.#log.debug('Closing retired browser because it has no active pages', { id: browserController.id });
|
|
462
564
|
void browserController.close().finally(() => {
|
|
463
565
|
this.retiredBrowserControllers.delete(browserController);
|
|
464
566
|
});
|
|
465
567
|
}, PAGE_CLOSE_KILL_TIMEOUT_MILLIS);
|
|
466
568
|
}
|
|
467
569
|
}
|
|
468
|
-
|
|
570
|
+
/**
|
|
571
|
+
* Returns `true` if the pool can accept a new browser launch without exceeding
|
|
572
|
+
* {@link BrowserPoolOptions.maxOpenBrowsers}. Counts starting, active, and retired browsers.
|
|
573
|
+
*/
|
|
574
|
+
hasFreeBrowserSlot() {
|
|
575
|
+
const total = this.startingBrowserControllers.size +
|
|
576
|
+
this.activeBrowserControllers.size +
|
|
577
|
+
this.retiredBrowserControllers.size;
|
|
578
|
+
return total < this.maxOpenBrowsers;
|
|
579
|
+
}
|
|
580
|
+
/**
|
|
581
|
+
* Returns `true` if any active browser has room for another page.
|
|
582
|
+
*/
|
|
583
|
+
hasActiveBrowserWithFreeCapacity() {
|
|
584
|
+
for (const controller of this.activeBrowserControllers) {
|
|
585
|
+
if (controller.activePages < this.maxOpenPagesPerBrowser)
|
|
586
|
+
return true;
|
|
587
|
+
}
|
|
588
|
+
return false;
|
|
589
|
+
}
|
|
590
|
+
initializeFingerprinting() {
|
|
469
591
|
const { useFingerprintCache = true, fingerprintCacheSize = 10_000 } = this.fingerprintOptions;
|
|
470
592
|
this.fingerprintGenerator = new FingerprintGenerator(this.fingerprintOptions.fingerprintGeneratorOptions);
|
|
471
593
|
this.fingerprintInjector = new FingerprintInjector();
|
|
472
594
|
if (useFingerprintCache) {
|
|
473
595
|
this.fingerprintCache = new QuickLRU({ maxSize: fingerprintCacheSize });
|
|
474
596
|
}
|
|
475
|
-
this.
|
|
597
|
+
this.addFingerprintHooks();
|
|
476
598
|
}
|
|
477
|
-
|
|
599
|
+
addFingerprintHooks() {
|
|
478
600
|
this.preLaunchHooks = [
|
|
479
601
|
...this.preLaunchHooks,
|
|
480
602
|
// This is flipped because of the fingerprint cache.
|
|
@@ -485,4 +607,3 @@ export class BrowserPool extends TypedEmitter {
|
|
|
485
607
|
this.postPageCreateHooks = [createPostPageCreateHook(this.fingerprintInjector), ...this.postPageCreateHooks];
|
|
486
608
|
}
|
|
487
609
|
}
|
|
488
|
-
//# sourceMappingURL=browser-pool.js.map
|
package/events.d.ts
CHANGED
|
@@ -1,11 +1,10 @@
|
|
|
1
|
-
export declare
|
|
1
|
+
export declare enum BROWSER_POOL_EVENTS {
|
|
2
2
|
BROWSER_LAUNCHED = "browserLaunched",
|
|
3
3
|
BROWSER_RETIRED = "browserRetired",
|
|
4
4
|
BROWSER_CLOSED = "browserClosed",
|
|
5
5
|
PAGE_CREATED = "pageCreated",
|
|
6
6
|
PAGE_CLOSED = "pageClosed"
|
|
7
7
|
}
|
|
8
|
-
export declare
|
|
8
|
+
export declare enum BROWSER_CONTROLLER_EVENTS {
|
|
9
9
|
BROWSER_CLOSED = "browserClosed"
|
|
10
10
|
}
|
|
11
|
-
//# sourceMappingURL=events.d.ts.map
|
package/events.js
CHANGED
|
@@ -14,4 +14,3 @@ export declare function createPrePageCreateHook(): (_pageId: string, browserCont
|
|
|
14
14
|
* @internal
|
|
15
15
|
*/
|
|
16
16
|
export declare function createPostPageCreateHook(fingerprintInjector: FingerprintInjector): (page: any, browserController: BrowserController) => Promise<void>;
|
|
17
|
-
//# sourceMappingURL=hooks.d.ts.map
|
package/fingerprinting/hooks.js
CHANGED
|
@@ -1,29 +1,42 @@
|
|
|
1
1
|
import { PlaywrightPlugin } from '../playwright/playwright-plugin.js';
|
|
2
2
|
import { PuppeteerPlugin } from '../puppeteer/puppeteer-plugin.js';
|
|
3
3
|
import { getGeneratorDefaultOptions } from './utils.js';
|
|
4
|
+
function applySessionHints(base, fingerprint) {
|
|
5
|
+
if (!fingerprint)
|
|
6
|
+
return base;
|
|
7
|
+
return {
|
|
8
|
+
...base,
|
|
9
|
+
...(fingerprint.browser ? { browsers: [{ name: fingerprint.browser }] } : {}),
|
|
10
|
+
...(fingerprint.platform ? { operatingSystems: [fingerprint.platform] } : {}),
|
|
11
|
+
...(fingerprint.device ? { devices: [fingerprint.device] } : {}),
|
|
12
|
+
};
|
|
13
|
+
}
|
|
4
14
|
/**
|
|
5
15
|
* @internal
|
|
6
16
|
*/
|
|
7
17
|
export function createFingerprintPreLaunchHook(browserPool) {
|
|
8
18
|
const { fingerprintGenerator, fingerprintCache, fingerprintOptions: { fingerprintGeneratorOptions }, } = browserPool;
|
|
9
19
|
return (_pageId, launchContext) => {
|
|
20
|
+
// Remote browsers may have their own fingerprinting — skip local fingerprint injection
|
|
21
|
+
if (launchContext.isRemote)
|
|
22
|
+
return;
|
|
10
23
|
const { useIncognitoPages } = launchContext;
|
|
11
|
-
const
|
|
24
|
+
const session = launchContext.session;
|
|
25
|
+
const cacheKey = session?.id ?? launchContext.proxyUrl;
|
|
12
26
|
const { launchOptions } = launchContext;
|
|
13
|
-
// If no options are passed we try to pass best default options as possible to match browser and OS.
|
|
14
|
-
const fingerprintGeneratorFinalOptions = fingerprintGeneratorOptions || getGeneratorDefaultOptions(launchContext);
|
|
15
27
|
let fingerprint;
|
|
16
28
|
if (cacheKey && fingerprintCache?.has(cacheKey)) {
|
|
17
29
|
fingerprint = fingerprintCache.get(cacheKey);
|
|
18
30
|
}
|
|
19
|
-
else if (cacheKey) {
|
|
20
|
-
fingerprint = fingerprintGenerator.getFingerprint(fingerprintGeneratorFinalOptions);
|
|
21
|
-
fingerprintCache?.set(cacheKey, fingerprint);
|
|
22
|
-
}
|
|
23
31
|
else {
|
|
24
|
-
|
|
32
|
+
const baseOptions = fingerprintGeneratorOptions || getGeneratorDefaultOptions(launchContext);
|
|
33
|
+
const finalOptions = applySessionHints(baseOptions, session?.fingerprint);
|
|
34
|
+
fingerprint = fingerprintGenerator.getFingerprint(finalOptions);
|
|
35
|
+
if (cacheKey)
|
|
36
|
+
fingerprintCache?.set(cacheKey, fingerprint);
|
|
25
37
|
}
|
|
26
|
-
|
|
38
|
+
// `fingerprint` is a declared field, so it cannot go through `extend()` (which rejects reserved names)
|
|
39
|
+
launchContext.fingerprint = fingerprint;
|
|
27
40
|
if (useIncognitoPages) {
|
|
28
41
|
return;
|
|
29
42
|
}
|
|
@@ -41,6 +54,8 @@ export function createFingerprintPreLaunchHook(browserPool) {
|
|
|
41
54
|
export function createPrePageCreateHook() {
|
|
42
55
|
return (_pageId, browserController, pageOptions) => {
|
|
43
56
|
const { launchContext, browserPlugin } = browserController;
|
|
57
|
+
if (launchContext.isRemote)
|
|
58
|
+
return;
|
|
44
59
|
const { fingerprint } = launchContext.fingerprint;
|
|
45
60
|
if (launchContext.useIncognitoPages && browserPlugin instanceof PlaywrightPlugin && pageOptions) {
|
|
46
61
|
pageOptions.userAgent ??= fingerprint.navigator.userAgent;
|
|
@@ -57,6 +72,8 @@ export function createPrePageCreateHook() {
|
|
|
57
72
|
export function createPostPageCreateHook(fingerprintInjector) {
|
|
58
73
|
return async (page, browserController) => {
|
|
59
74
|
const { browserPlugin, launchContext } = browserController;
|
|
75
|
+
if (launchContext.isRemote)
|
|
76
|
+
return;
|
|
60
77
|
const fingerprint = launchContext.fingerprint;
|
|
61
78
|
// TODO this will require refactoring, we should use common API instead of branching based on plugin type,
|
|
62
79
|
// and there should be no public methods specific to some browser.
|
|
@@ -79,4 +96,3 @@ export function createPostPageCreateHook(fingerprintInjector) {
|
|
|
79
96
|
}
|
|
80
97
|
};
|
|
81
98
|
}
|
|
82
|
-
//# sourceMappingURL=hooks.js.map
|