@crawlee/puppeteer 3.0.0-alpha.2 → 3.0.0-alpha.22

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.
@@ -0,0 +1,225 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.removeInterceptRequestHandler = exports.addInterceptRequestHandler = void 0;
4
+ const tslib_1 = require("tslib");
5
+ const events_1 = require("events");
6
+ const ow_1 = tslib_1.__importDefault(require("ow"));
7
+ const log_1 = tslib_1.__importDefault(require("@apify/log"));
8
+ // We use weak maps here so that the content gets discarded after page gets closed.
9
+ const pageInterceptRequestHandlersMap = new WeakMap(); // Maps page to an array of request interception handlers.
10
+ const pageInterceptRequestMasterHandlerMap = new WeakMap(); // Maps page to master request interception handler.
11
+ const pageInterceptedRequestsMap = new WeakMap(); // Maps page to a set of its pending intercepted requests.
12
+ /**
13
+ * Enables observation of changes of internal state to be able to queue other actions based on it.
14
+ * @ignore
15
+ */
16
+ class ObservableSet extends events_1.EventEmitter {
17
+ constructor() {
18
+ super(...arguments);
19
+ Object.defineProperty(this, "set", {
20
+ enumerable: true,
21
+ configurable: true,
22
+ writable: true,
23
+ value: new Set()
24
+ });
25
+ }
26
+ add(value) {
27
+ this.set.add(value);
28
+ this.emit('add', value);
29
+ return this.set;
30
+ }
31
+ delete(value) {
32
+ const success = this.set.delete(value);
33
+ this.emit('delete', value);
34
+ return success;
35
+ }
36
+ get size() {
37
+ return this.set.size;
38
+ }
39
+ }
40
+ /**
41
+ * Makes all request headers capitalized to more look like in browser
42
+ */
43
+ function browserifyHeaders(headers) {
44
+ const finalHeaders = {};
45
+ // eslint-disable-next-line prefer-const
46
+ for (let [key, value] of Object.entries(headers)) {
47
+ key = key.toLowerCase()
48
+ .split('-')
49
+ .map((str) => str.charAt(0).toUpperCase() + str.slice(1))
50
+ .join('-');
51
+ finalHeaders[key] = value;
52
+ }
53
+ return finalHeaders;
54
+ }
55
+ /**
56
+ * Executes an array for given intercept request handlers for a given request object.
57
+ *
58
+ * @param request Puppeteer's Request object.
59
+ * @param interceptRequestHandlers An array of intercept request handlers.
60
+ * @ignore
61
+ */
62
+ async function handleRequest(request, interceptRequestHandlers) {
63
+ // If there are no intercept handlers, it means that request interception is not enabled (anymore)
64
+ // and therefore .abort() .respond() and .continue() would throw and crash the process.
65
+ if (!interceptRequestHandlers?.length)
66
+ return;
67
+ let wasAborted = false;
68
+ let wasResponded = false;
69
+ let wasContinued = false;
70
+ const accumulatedOverrides = {
71
+ headers: browserifyHeaders(request.headers()),
72
+ };
73
+ const originalContinue = request.continue.bind(request);
74
+ request.continue = async (overrides = {}) => {
75
+ wasContinued = true;
76
+ const headers = browserifyHeaders({ ...accumulatedOverrides.headers, ...overrides.headers });
77
+ Object.assign(accumulatedOverrides, overrides, { headers });
78
+ };
79
+ const { abort, respond } = request;
80
+ request.abort = async (...args) => {
81
+ wasAborted = true;
82
+ return abort.call(request, ...args);
83
+ };
84
+ request.respond = async (...args) => {
85
+ wasResponded = true;
86
+ return respond.call(request, ...args);
87
+ };
88
+ for (const handler of interceptRequestHandlers) {
89
+ wasContinued = false;
90
+ await handler(request);
91
+ // Check that one of the functions was called.
92
+ if (!wasAborted && !wasResponded && !wasContinued) {
93
+ throw new Error('Intercept request handler must call one of request.continue|respond|abort() methods!');
94
+ }
95
+ // If request was aborted or responded then we can finish immediately.
96
+ if (wasAborted || wasResponded)
97
+ return;
98
+ }
99
+ return originalContinue(accumulatedOverrides);
100
+ }
101
+ /**
102
+ * Adds request interception handler in similar to `page.on('request', handler);` but in addition to that
103
+ * supports multiple parallel handlers.
104
+ *
105
+ * All the handlers are executed sequentially in the order as they were added.
106
+ * Each of the handlers must call one of `request.continue()`, `request.abort()` and `request.respond()`.
107
+ * In addition to that any of the handlers may modify the request object (method, postData, headers)
108
+ * by passing its overrides to `request.continue()`.
109
+ * If multiple handlers modify same property then the last one wins. Headers are merged separately so you can
110
+ * override only a value of specific header.
111
+ *
112
+ * If one the handlers calls `request.abort()` or `request.respond()` then request is not propagated further
113
+ * to any of the remaining handlers.
114
+ *
115
+ *
116
+ * **Example usage:**
117
+ *
118
+ * ```javascript
119
+ * // Replace images with placeholder.
120
+ * await addInterceptRequestHandler(page, (request) => {
121
+ * if (request.resourceType() === 'image') {
122
+ * return request.respond({
123
+ * statusCode: 200,
124
+ * contentType: 'image/jpeg',
125
+ * body: placeholderImageBuffer,
126
+ * });
127
+ * }
128
+ * return request.continue();
129
+ * });
130
+ *
131
+ * // Abort all the scripts.
132
+ * await addInterceptRequestHandler(page, (request) => {
133
+ * if (request.resourceType() === 'script') return request.abort();
134
+ * return request.continue();
135
+ * });
136
+ *
137
+ * // Change requests to post.
138
+ * await addInterceptRequestHandler(page, (request) => {
139
+ * return request.continue({
140
+ * method: 'POST',
141
+ * });
142
+ * });
143
+ *
144
+ * await page.goto('http://example.com');
145
+ * ```
146
+ *
147
+ * @param page Puppeteer [`Page`](https://pptr.dev/#?product=Puppeteer&show=api-class-page) object.
148
+ * @param handler Request interception handler.
149
+ */
150
+ async function addInterceptRequestHandler(page, handler) {
151
+ (0, ow_1.default)(page, ow_1.default.object.hasKeys('goto', 'evaluate'));
152
+ (0, ow_1.default)(handler, ow_1.default.function);
153
+ if (!pageInterceptRequestHandlersMap.has(page)) {
154
+ pageInterceptRequestHandlersMap.set(page, []);
155
+ }
156
+ if (!pageInterceptedRequestsMap.has(page)) {
157
+ pageInterceptedRequestsMap.set(page, new ObservableSet());
158
+ }
159
+ const handlersArray = pageInterceptRequestHandlersMap.get(page);
160
+ handlersArray.push(handler);
161
+ // First handler was just added at this point so we need to set up request interception.
162
+ if (handlersArray.length === 1) {
163
+ await page.setRequestInterception(true);
164
+ // This is a handler that gets set in page.on('request', ...) and that executes all the user
165
+ // added custom handlers.
166
+ const masterHandler = async (request) => {
167
+ const interceptedRequests = pageInterceptedRequestsMap.get(page);
168
+ interceptedRequests.add(request);
169
+ const interceptHandlers = pageInterceptRequestHandlersMap.get(page);
170
+ try {
171
+ await handleRequest(request, interceptHandlers);
172
+ }
173
+ finally {
174
+ interceptedRequests.delete(request);
175
+ }
176
+ };
177
+ pageInterceptRequestMasterHandlerMap.set(page, masterHandler);
178
+ page.on('request', masterHandler);
179
+ }
180
+ }
181
+ exports.addInterceptRequestHandler = addInterceptRequestHandler;
182
+ /**
183
+ * Removes request interception handler for given page.
184
+ *
185
+ * @param page Puppeteer [`Page`](https://pptr.dev/#?product=Puppeteer&show=api-class-page) object.
186
+ * @param handler Request interception handler.
187
+ */
188
+ async function removeInterceptRequestHandler(page, handler) {
189
+ (0, ow_1.default)(page, ow_1.default.object.hasKeys('goto', 'evaluate'));
190
+ (0, ow_1.default)(handler, ow_1.default.function);
191
+ const handlersArray = pageInterceptRequestHandlersMap
192
+ .get(page)
193
+ .filter((item) => item !== handler);
194
+ pageInterceptRequestHandlersMap.set(page, handlersArray);
195
+ if (handlersArray.length === 0) {
196
+ const interceptedRequestsInProgress = pageInterceptedRequestsMap.get(page);
197
+ // Since handlers can be async, we can't simply turn off request interception
198
+ // when there are no handlers, because some handlers could still
199
+ // be in progress and request.abort|respond|continue() would throw.
200
+ if (interceptedRequestsInProgress.size === 0) {
201
+ await disableRequestInterception(page);
202
+ }
203
+ else {
204
+ const onDelete = async () => {
205
+ if (interceptedRequestsInProgress.size === 0) {
206
+ try {
207
+ await disableRequestInterception(page);
208
+ interceptedRequestsInProgress.removeListener('delete', onDelete);
209
+ }
210
+ catch (error) {
211
+ log_1.default.debug('Error while disabling request interception', { error });
212
+ }
213
+ }
214
+ };
215
+ interceptedRequestsInProgress.on('delete', onDelete);
216
+ }
217
+ }
218
+ }
219
+ exports.removeInterceptRequestHandler = removeInterceptRequestHandler;
220
+ async function disableRequestInterception(page) {
221
+ await page.setRequestInterception(false);
222
+ const requestHandler = pageInterceptRequestMasterHandlerMap.get(page);
223
+ page.off('request', requestHandler);
224
+ }
225
+ //# sourceMappingURL=puppeteer_request_interception.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"puppeteer_request_interception.js","sourceRoot":"","sources":["../../../src/internals/utils/puppeteer_request_interception.ts"],"names":[],"mappings":";;;;AAAA,mCAAsC;AACtC,oDAAoB;AAGpB,6DAA6B;AAE7B,mFAAmF;AACnF,MAAM,+BAA+B,GAAsC,IAAI,OAAO,EAAE,CAAC,CAAC,0DAA0D;AACpJ,MAAM,oCAAoC,GAAG,IAAI,OAAO,EAAE,CAAC,CAAC,oDAAoD;AAChH,MAAM,0BAA0B,GAAG,IAAI,OAAO,EAAE,CAAC,CAAC,0DAA0D;AAE5G;;;GAGG;AACH,MAAM,aAAiB,SAAQ,qBAAY;IAA3C;;QACI;;;;mBAAM,IAAI,GAAG,EAAK;WAAC;IAiBvB,CAAC;IAfG,GAAG,CAAC,KAAQ;QACR,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;QACpB,IAAI,CAAC,IAAI,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC;QACxB,OAAO,IAAI,CAAC,GAAG,CAAC;IACpB,CAAC;IAED,MAAM,CAAC,KAAQ;QACX,MAAM,OAAO,GAAG,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;QACvC,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,KAAK,CAAC,CAAC;QAC3B,OAAO,OAAO,CAAC;IACnB,CAAC;IAED,IAAI,IAAI;QACJ,OAAO,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC;IACzB,CAAC;CACJ;AAID;;GAEG;AACH,SAAS,iBAAiB,CAAC,OAA+B;IACtD,MAAM,YAAY,GAAuB,EAAE,CAAC;IAC5C,wCAAwC;IACxC,KAAK,IAAI,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE;QAC9C,GAAG,GAAG,GAAG,CAAC,WAAW,EAAE;aAClB,KAAK,CAAC,GAAG,CAAC;aACV,GAAG,CAAC,CAAC,GAAG,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MAAM,KAAK,CAAC,EAAE;QAC5B,MAAM,6BAA6B,GAAG,0BAA0B,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;QAC3E,6EAA6E;QAC7E,gEAAgE;QAChE,mEAAmE;QACnE,IAAI,6BAA6B,CAAC,IAAI,KAAK,CAAC,EAAE;YAC1C,MAAM,0BAA0B,CAAC,IAAI,CAAC,CAAC;SAC1C;aAAM;YACH,MAAM,QAAQ,GAAG,KAAK,IAAI,EAAE;gBACxB,IAAI,6BAA6B,CAAC,IAAI,KAAK,CAAC,EAAE;oBAC1C,IAAI;wBACA,MAAM,0BAA0B,CAAC,IAAI,CAAC,CAAC;wBACvC,6BAA6B,CAAC,cAAc,CAAC,QAAQ,EAAE,QAAQ,CAAC,CAAC;qBACpE;oBAAC,OAAO,KAAK,EAAE;wBACZ,aAAG,CAAC,KAAK,CAAC,4CAA4C,EAAE,EAAE,KAAK,EAAE,CAAC,CAAC;qBACtE;iBACJ;YACL,CAAC,CAAC;YACF,6BAA6B,CAAC,EAAE,CAAC,QAAQ,EAAE,QAAQ,CAAC,CAAC;SACxD;KACJ;AACL,CAAC;AA/BD,sEA+BC;AAED,KAAK,UAAU,0BAA0B,CAAC,IAAU;IAChD,MAAM,IAAI,CAAC,sBAAsB,CAAC,KAAK,CAAC,CAAC;IACzC,MAAM,cAAc,GAAG,oCAAoC,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;IACtE,IAAI,CAAC,GAAG,CAAC,SAAS,EAAE,cAAc,CAAC,CAAC;AACxC,CAAC"}
@@ -0,0 +1,314 @@
1
+ /**
2
+ * A namespace that contains various utilities for
3
+ * [Puppeteer](https://github.com/puppeteer/puppeteer) - the headless Chrome Node API.
4
+ *
5
+ * **Example usage:**
6
+ *
7
+ * ```javascript
8
+ * const Apify = require('apify');
9
+ * const { puppeteer } = Actor.utils;
10
+ *
11
+ * // Open https://www.example.com in Puppeteer
12
+ * const browser = await Actor.launchPuppeteer();
13
+ * const page = await browser.newPage();
14
+ * await page.goto('https://www.example.com');
15
+ *
16
+ * // Inject jQuery into a page
17
+ * await puppeteer.injectJQuery(page);
18
+ * ```
19
+ * @module puppeteerUtils
20
+ */
21
+ import { Page, HTTPResponse, ResponseForRequest } from 'puppeteer';
22
+ import { Request, storage } from '@crawlee/core';
23
+ import { Dictionary } from '@crawlee/utils';
24
+ import { enqueueLinksByClickingElements, EnqueueLinksByClickingElementsOptions } from '../enqueue-links/click-elements';
25
+ import { addInterceptRequestHandler, InterceptHandler, removeInterceptRequestHandler } from './puppeteer_request_interception';
26
+ import { PuppeteerCrawlingContext } from '../puppeteer-crawler';
27
+ export interface DirectNavigationOptions {
28
+ /**
29
+ * Maximum operation time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The
30
+ * default value can be changed by using the browserContext.setDefaultNavigationTimeout(timeout),
31
+ * browserContext.setDefaultTimeout(timeout), page.setDefaultNavigationTimeout(timeout) or
32
+ * page.setDefaultTimeout(timeout) methods.
33
+ */
34
+ timeout?: number;
35
+ /**
36
+ * When to consider operation succeeded, defaults to `load`. Events can be either:
37
+ * - `'domcontentloaded'` - consider operation to be finished when the `DOMContentLoaded` event is fired.
38
+ * - `'load'` - consider operation to be finished when the `load` event is fired.
39
+ * - `'networkidle'` - consider operation to be finished when there are no network connections for at least `500` ms.
40
+ */
41
+ waitUntil?: 'domcontentloaded' | 'load' | 'networkidle';
42
+ /**
43
+ * Referer header value. If provided it will take preference over the referer header value set by page.setExtraHTTPHeaders(headers).
44
+ */
45
+ referer?: string;
46
+ }
47
+ export interface InjectFileOptions {
48
+ /**
49
+ * Enables the injected script to survive page navigations and reloads without need to be re-injected manually.
50
+ * This does not mean, however, that internal state will be preserved. Just that it will be automatically
51
+ * re-injected on each navigation before any other scripts get the chance to execute.
52
+ */
53
+ surviveNavigations?: boolean;
54
+ }
55
+ export interface BlockRequestsOptions {
56
+ /**
57
+ * The patterns of URLs to block from being loaded by the browser.
58
+ * Only `*` can be used as a wildcard. It is also automatically added to the beginning
59
+ * and end of the pattern. This limitation is enforced by the DevTools protocol.
60
+ * `.png` is the same as `*.png*`.
61
+ */
62
+ urlPatterns?: string[];
63
+ /**
64
+ * If you just want to append to the default blocked patterns, use this property.
65
+ */
66
+ extraUrlPatterns?: string[];
67
+ }
68
+ export interface CompiledScriptParams {
69
+ page: Page;
70
+ request: Request;
71
+ }
72
+ export declare type CompiledScriptFunction = (params: CompiledScriptParams) => Promise<unknown>;
73
+ /**
74
+ * Injects a JavaScript file into a Puppeteer page.
75
+ * Unlike Puppeteer's `addScriptTag` function, this function works on pages
76
+ * with arbitrary Cross-Origin Resource Sharing (CORS) policies.
77
+ *
78
+ * File contents are cached for up to 10 files to limit file system access.
79
+ *
80
+ * @param page Puppeteer [`Page`](https://pptr.dev/#?product=Puppeteer&show=api-class-page) object.
81
+ * @param filePath File path
82
+ * @param [options]
83
+ */
84
+ export declare function injectFile(page: Page, filePath: string, options?: InjectFileOptions): Promise<unknown>;
85
+ /**
86
+ * Injects the [jQuery](https://jquery.com/) library into a Puppeteer page.
87
+ * jQuery is often useful for various web scraping and crawling tasks.
88
+ * For example, it can help extract text from HTML elements using CSS selectors.
89
+ *
90
+ * Beware that the injected jQuery object will be set to the `window.$` variable and thus it might cause conflicts with
91
+ * other libraries included by the page that use the same variable name (e.g. another version of jQuery).
92
+ * This can affect functionality of page's scripts.
93
+ *
94
+ * The injected jQuery will survive page navigations and reloads.
95
+ *
96
+ * **Example usage:**
97
+ * ```javascript
98
+ * await Actor.utils.puppeteer.injectJQuery(page);
99
+ * const title = await page.evaluate(() => {
100
+ * return $('head title').text();
101
+ * });
102
+ * ```
103
+ *
104
+ * Note that `injectJQuery()` does not affect the Puppeteer's
105
+ * [`page.$()`](https://pptr.dev/#?product=Puppeteer&show=api-pageselector)
106
+ * function in any way.
107
+ *
108
+ * @param page Puppeteer [`Page`](https://pptr.dev/#?product=Puppeteer&show=api-class-page) object.
109
+ */
110
+ export declare function injectJQuery(page: Page): Promise<unknown>;
111
+ /**
112
+ * Forces the Puppeteer browser tab to block loading URLs that match a provided pattern.
113
+ * This is useful to speed up crawling of websites, since it reduces the amount
114
+ * of data that needs to be downloaded from the web, but it may break some websites
115
+ * or unexpectedly prevent loading of resources.
116
+ *
117
+ * By default, the function will block all URLs including the following patterns:
118
+ *
119
+ * ```json
120
+ * [".css", ".jpg", ".jpeg", ".png", ".svg", ".gif", ".woff", ".pdf", ".zip"]
121
+ * ```
122
+ *
123
+ * If you want to extend this list further, use the `extraUrlPatterns` option,
124
+ * which will keep blocking the default patterns, as well as add your custom ones.
125
+ * If you would like to block only specific patterns, use the `urlPatterns` option,
126
+ * which will override the defaults and block only URLs with your custom patterns.
127
+ *
128
+ * This function does not use Puppeteer's request interception and therefore does not interfere
129
+ * with browser cache. It's also faster than blocking requests using interception,
130
+ * because the blocking happens directly in the browser without the round-trip to Node.js,
131
+ * but it does not provide the extra benefits of request interception.
132
+ *
133
+ * The function will never block main document loads and their respective redirects.
134
+ *
135
+ * **Example usage**
136
+ * ```javascript
137
+ * const Apify = require('apify');
138
+ *
139
+ * const browser = await Actor.launchPuppeteer();
140
+ * const page = await browser.newPage();
141
+ *
142
+ * // Block all requests to URLs that include `adsbygoogle.js` and also all defaults.
143
+ * await Actor.utils.puppeteer.blockRequests(page, {
144
+ * extraUrlPatterns: ['adsbygoogle.js'],
145
+ * });
146
+ *
147
+ * await page.goto('https://cnn.com');
148
+ * ```
149
+ *
150
+ * @param page Puppeteer [`Page`](https://pptr.dev/#?product=Puppeteer&show=api-class-page) object.
151
+ * @param [options]
152
+ */
153
+ export declare function blockRequests(page: Page, options?: BlockRequestsOptions): Promise<void>;
154
+ /**
155
+ * `blockResources()` has a high impact on performance in recent versions of Puppeteer.
156
+ * Until this resolves, please use `Actor.utils.puppeteer.blockRequests()`.
157
+ * @deprecated
158
+ */
159
+ export declare const blockResources: (page: Page, resourceTypes?: string[]) => Promise<void>;
160
+ /**
161
+ * *NOTE:* In recent versions of Puppeteer using this function entirely disables browser cache which resolves in sub-optimal
162
+ * performance. Until this resolves, we suggest just relying on the in-browser cache unless absolutely necessary.
163
+ *
164
+ * Enables caching of intercepted responses into a provided object. Automatically enables request interception in Puppeteer.
165
+ * *IMPORTANT*: Caching responses stores them to memory, so too loose rules could cause memory leaks for longer running crawlers.
166
+ * This issue should be resolved or atleast mitigated in future iterations of this feature.
167
+ * @param page
168
+ * Puppeteer [`Page`](https://pptr.dev/#?product=Puppeteer&show=api-class-page) object.
169
+ * @param cache
170
+ * Object in which responses are stored
171
+ * @param responseUrlRules
172
+ * List of rules that are used to check if the response should be cached.
173
+ * String rules are compared as page.url().includes(rule) while RegExp rules are evaluated as rule.test(page.url()).
174
+ * @deprecated
175
+ */
176
+ export declare function cacheResponses(page: Page, cache: Dictionary<Partial<ResponseForRequest>>, responseUrlRules: (string | RegExp)[]): Promise<void>;
177
+ /**
178
+ * Compiles a Puppeteer script into an async function that may be executed at any time
179
+ * by providing it with the following object:
180
+ * ```
181
+ * {
182
+ * page: Page,
183
+ * request: Request,
184
+ * }
185
+ * ```
186
+ * Where `page` is a Puppeteer [`Page`](https://pptr.dev/#?product=Puppeteer&show=api-class-page)
187
+ * and `request` is a {@link Request}.
188
+ *
189
+ * The function is compiled by using the `scriptString` parameter as the function's body,
190
+ * so any limitations to function bodies apply. Return value of the compiled function
191
+ * is the return value of the function body = the `scriptString` parameter.
192
+ *
193
+ * As a security measure, no globals such as `process` or `require` are accessible
194
+ * from within the function body. Note that the function does not provide a safe
195
+ * sandbox and even though globals are not easily accessible, malicious code may
196
+ * still execute in the main process via prototype manipulation. Therefore you
197
+ * should only use this function to execute sanitized or safe code.
198
+ *
199
+ * Custom context may also be provided using the `context` parameter. To improve security,
200
+ * make sure to only pass the really necessary objects to the context. Preferably making
201
+ * secured copies beforehand.
202
+ *
203
+ */
204
+ export declare function compileScript(scriptString: string, context?: Dictionary): CompiledScriptFunction;
205
+ /**
206
+ * Extended version of Puppeteer's `page.goto()` allowing to perform requests with HTTP method other than GET,
207
+ * with custom headers and POST payload. URL, method, headers and payload are taken from
208
+ * request parameter that must be an instance of Request class.
209
+ *
210
+ * *NOTE:* In recent versions of Puppeteer using requests other than GET, overriding headers and adding payloads disables
211
+ * browser cache which degrades performance.
212
+ *
213
+ * @param page Puppeteer [`Page`](https://pptr.dev/#?product=Puppeteer&show=api-class-page) object.
214
+ * @param request
215
+ * @param [gotoOptions] Custom options for `page.goto()`.
216
+ */
217
+ export declare function gotoExtended(page: Page, request: Request, gotoOptions?: DirectNavigationOptions): Promise<HTTPResponse | null>;
218
+ export interface InfiniteScrollOptions {
219
+ /**
220
+ * How many seconds to scroll for. If 0, will scroll until bottom of page.
221
+ * @default 1
222
+ */
223
+ timeoutSecs?: number;
224
+ /**
225
+ * How many seconds to wait for no new content to load before exit.
226
+ * @default 4
227
+ */
228
+ waitForSecs?: number;
229
+ /**
230
+ * If true, it will scroll up a bit after each scroll down. This is required on some websites for the scroll to work.
231
+ * @default false
232
+ */
233
+ scrollDownAndUp?: boolean;
234
+ /**
235
+ * Optionally checks and clicks a button if it appears while scrolling. This is required on some websites for the scroll to work.
236
+ */
237
+ buttonSelector?: string;
238
+ /**
239
+ * This function is called after every scroll and stops the scrolling process if it returns `true`. The function can be `async`.
240
+ */
241
+ stopScrollCallback?: () => unknown | Promise<unknown>;
242
+ }
243
+ /**
244
+ * Scrolls to the bottom of a page, or until it times out.
245
+ * Loads dynamic content when it hits the bottom of a page, and then continues scrolling.
246
+ * @param page Puppeteer [`Page`](https://pptr.dev/#?product=Puppeteer&show=api-class-page) object.
247
+ * @param [options]
248
+ */
249
+ export declare function infiniteScroll(page: Page, options?: InfiniteScrollOptions): Promise<void>;
250
+ export interface SaveSnapshotOptions {
251
+ /**
252
+ * Key under which the screenshot and HTML will be saved. `.jpg` will be appended for screenshot and `.html` for HTML.
253
+ * @default 'SNAPSHOT'
254
+ */
255
+ key?: string;
256
+ /**
257
+ * The quality of the image, between 0-100. Higher quality images have bigger size and require more storage.
258
+ * @default 50
259
+ */
260
+ screenshotQuality?: number;
261
+ /**
262
+ * If true, it will save a full screenshot of the current page as a record with `key` appended by `.jpg`.
263
+ * @default true
264
+ */
265
+ saveScreenshot?: boolean;
266
+ /**
267
+ * If true, it will save a full HTML of the current page as a record with `key` appended by `.html`.
268
+ * @default true
269
+ */
270
+ saveHtml?: boolean;
271
+ /**
272
+ * Name or id of the Key-Value store where snapshot is saved. By default it is saved to default Key-Value store.
273
+ * @default null
274
+ */
275
+ keyValueStoreName?: string | null;
276
+ }
277
+ /**
278
+ * Saves a full screenshot and HTML of the current page into a Key-Value store.
279
+ * @param page Puppeteer [`Page`](https://pptr.dev/#?product=Puppeteer&show=api-class-page) object.
280
+ * @param [options]
281
+ */
282
+ export declare function saveSnapshot(page: Page, options?: SaveSnapshotOptions): Promise<void>;
283
+ export interface PuppeteerContextUtils {
284
+ injectFile(filePath: string, options?: InjectFileOptions): Promise<unknown>;
285
+ injectJQuery(): Promise<unknown>;
286
+ enqueueLinksByClickingElements(options: Omit<EnqueueLinksByClickingElementsOptions, 'page' | 'requestQueue'>): Promise<storage.BatchAddRequestsResult>;
287
+ blockRequests(options?: BlockRequestsOptions): Promise<void>;
288
+ blockResources(resourceTypes?: string[]): Promise<void>;
289
+ cacheResponses(cache: Dictionary<Partial<ResponseForRequest>>, responseUrlRules: (string | RegExp)[]): Promise<void>;
290
+ compileScript(scriptString: string, ctx?: Dictionary): CompiledScriptFunction;
291
+ addInterceptRequestHandler(handler: InterceptHandler): Promise<void>;
292
+ removeInterceptRequestHandler(handler: InterceptHandler): Promise<void>;
293
+ infiniteScroll(options?: InfiniteScrollOptions): Promise<void>;
294
+ saveSnapshot(options?: SaveSnapshotOptions): Promise<void>;
295
+ }
296
+ /** @internal */
297
+ export declare function registerUtilsToContext(context: PuppeteerCrawlingContext): void;
298
+ export { enqueueLinksByClickingElements, addInterceptRequestHandler, removeInterceptRequestHandler, };
299
+ /** @internal */
300
+ export declare const puppeteerUtils: {
301
+ injectFile: typeof injectFile;
302
+ injectJQuery: typeof injectJQuery;
303
+ enqueueLinksByClickingElements: typeof enqueueLinksByClickingElements;
304
+ blockRequests: typeof blockRequests;
305
+ blockResources: (page: Page, resourceTypes?: string[]) => Promise<void>;
306
+ cacheResponses: typeof cacheResponses;
307
+ compileScript: typeof compileScript;
308
+ gotoExtended: typeof gotoExtended;
309
+ addInterceptRequestHandler: typeof addInterceptRequestHandler;
310
+ removeInterceptRequestHandler: typeof removeInterceptRequestHandler;
311
+ infiniteScroll: typeof infiniteScroll;
312
+ saveSnapshot: typeof saveSnapshot;
313
+ };
314
+ //# sourceMappingURL=puppeteer_utils.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"puppeteer_utils.d.ts","sourceRoot":"","sources":["../../../src/internals/utils/puppeteer_utils.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AAOH,OAAO,EAAE,IAAI,EAAE,YAAY,EAAE,kBAAkB,EAAmC,MAAM,WAAW,CAAC;AAEpG,OAAO,EAAiB,OAAO,EAAE,OAAO,EAAc,MAAM,eAAe,CAAC;AAC5E,OAAO,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAC5C,OAAO,EAAE,8BAA8B,EAAE,qCAAqC,EAAE,MAAM,iCAAiC,CAAC;AACxH,OAAO,EAAE,0BAA0B,EAAE,gBAAgB,EAAE,6BAA6B,EAAE,MAAM,kCAAkC,CAAC;AAC/H,OAAO,EAAE,wBAAwB,EAAE,MAAM,sBAAsB,CAAC;AAUhE,MAAM,WAAW,uBAAuB;IACpC;;;;;OAKG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC;IAEjB;;;;;OAKG;IACH,SAAS,CAAC,EAAE,kBAAkB,GAAG,MAAM,GAAG,aAAa,CAAC;IAExD;;OAEG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC;CACpB;AAED,MAAM,WAAW,iBAAiB;IAC9B;;;;OAIG;IACH,kBAAkB,CAAC,EAAE,OAAO,CAAC;CAChC;AAED,MAAM,WAAW,oBAAoB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