Crawlee—A web scraping and browser automation library for Node.js to build reliable crawlers. In JavaScript and TypeScript. Extract data for AI, LLMs, RAG, or GPTs. Download HTML, PDF, JPG, PNG, and other files from websites. Works with Puppeteer, Playwright, Cheerio, JSDOM, and raw HTTP. Both headful and headless mode. With proxy rotation.
TypeScript apifyautomationcrawlercrawlingheadlessheadless-chromejavascriptnodejsnpmplaywrightpuppeteerscraperscrapingtypescriptweb-crawlerweb-crawlingweb-scraping
Bump version, update CI, fix engines [skip ci]
Ondra Urban905fffcfc5df
diff --git a/.travis.yml b/.travis.ymlindex 0af89e9f1..7d925bf1c 100644--- a/.travis.yml+++ b/.travis.yml@@ -26,16 +26,10 @@ jobs:- script: .travis/check-user-agent.jsinclude:- stage: test- name: Lint&Docs+ name: Lint&User-Agentnode_js: '10'script:- - "(cd website && npm install --no-package-lock)"- - npm run lint && node .travis/check-docs.js- - stage: test- name: Check User-Agent- node_js: '10'- script:- - node .travis/check-user-agent.js+ - npm run lint && node .travis/check-user-agent.js- stage: deployif: (branch = master AND type != pull_request) OR tag =~ /^v\d+\.\d+\.\d+$/script: skipdiff --git a/.travis/check-docs.js b/.travis/check-docs.jsdeleted file mode 100644index 1dac68edb..000000000--- a/.travis/check-docs.js+++ /dev/null@@ -1,14 +0,0 @@-const { execSync } = require('child_process');--console.log('Checking if documentation is updated.');-execSync('npm run build-docs', { stdio: 'inherit'});-execSync('npm run build-readme', { stdio: 'inherit'});--console.log('Checking if all changes are committed.');-const gitStatus = execSync('git status --porcelain --branch', { encoding: 'utf8' });-const statusLines = gitStatus.split('\n');-console.log(gitStatus);-if (statusLines.length > 1 && statusLines[1].length) {- console.error('You have uncommitted changes in the documentation. Please build the docs, review and commit changes.');- process.exit(1);-}diff --git a/docs/api/Apify.md b/docs/api/Apify.mddeleted file mode 100644index 9dfd7461e..000000000--- a/docs/api/Apify.md+++ /dev/null@@ -1,745 +0,0 @@-----id: apify-title: Apify------<a name="apify"></a>--The following section describes all functions and properties provided by the `apify` package, except individual classes and namespaces that have their-separate, detailed, documentation pages accessible from the left sidebar. To learn how Apify SDK works, we suggest following the-[Getting Started](/docs/guides/getting-started) tutorial.-------<a name="addwebhook"></a>--## `Apify.addWebhook(options)`--**Returns**: `Promise<object>` - The return value is the Webhook object. For more information, see the-[Get webhook](https://apify.com/docs/api/v2#/reference/webhooks/webhook-object/get-webhook) API endpoint.--Creates an ad-hoc webhook for the current actor run, which lets you receive a notification when the actor run finished or failed. For more information-about Apify actor webhooks, please see the [documentation](https://docs.apify.com/webhooks).--Note that webhooks are only supported for actors running on the Apify platform. In local environment, the function will print a warning and have no-effect.--**Params**--- **`options`**: `Object`-- - **`.eventTypes`**: `Array<string>` - Array of event types, which you can set for actor run, see the- [actor run events](https://docs.apify.com/webhooks/events#actor-run) in the Apify doc.- - **`.requestUrl`**: `string` - URL which will be requested using HTTP POST request, when actor run will reach the set event type.- - **`[.payloadTemplate]`**: `string` - Payload template is a JSON-like string that describes the structure of the webhook POST request payload.- It uses JSON syntax, extended with a double curly braces syntax for injecting variables `{{variable}}`. Those variables are resolved at the- time of the webhook's dispatch, and a list of available variables with their descriptions is available in the- [Apify webhook documentation](https://docs.apify.com/webhooks).-- When omitted, the default payload template will be used. [See the docs for the default payload template](https://docs.apify.com/webhooks).-- - **`[.idempotencyKey]`**: `string` - Idempotency key enables you to ensure that a webhook will not be added multiple times in case of an actor- restart or other situation that would cause the `addWebhook()` function to be called again. We suggest using the actor run ID as the- idempotency key. You can get the run ID by calling [`Apify.getEnv()`](/docs/api/apify#getenv) function.-------<a name="call"></a>--## `Apify.call(actId, [input], [options])`--**Returns**: [`Promise<ActorRun>`](/docs/typedefs/actor-run)--Runs an actor on the Apify platform using the current user account (determined by the `APIFY_TOKEN` environment variable), waits for the actor to-finish and fetches its output.--By passing the `waitSecs` option you can reduce the maximum amount of time to wait for the run to finish. If the value is less than or equal to zero,-the function returns immediately after the run is started.--The result of the function is an [`ActorRun`](/docs/typedefs/actor-run) object that contains details about the actor run and its output (if any). If-the actor run fails, the function throws the [`ApifyCallError`](/docs/api/apify-call-error) exception.--If you want to run an actor task rather than an actor, please use the [`Apify.callTask()`](/docs/api/apify#calltask) function instead.--For more information about actors, read the [documentation](https://docs.apify.com/actor).--**Example usage:**--```javascript-const run = await Apify.call('apify/hello-world', { myInput: 123 });-console.log(`Received message: ${run.output.body.message}`);-```--Internally, the `call()` function invokes the [Run actor](https://apify.com/docs/api/v2#/reference/actors/run-collection/run-actor) and several other-API endpoints to obtain the output.--**Throws**:--- [`ApifyCallError`](/docs/api/apify-call-error) If the run did not succeed, e.g. if it failed or timed out.--**Params**--- **`actId`**: `string` - Either `username/actor-name` or actor ID.-- **`[input]`**: `object` - Input for the actor. If it is an object, it will be stringified to JSON and its content type set to- `application/json; charset=utf-8`. Otherwise the `options.contentType` parameter must be provided.-- **`[options]`**: `Object` <code> = {}</code> - Object with the settings below:- - **`[.contentType]`**: `string` - Content type for the `input`. If not specified, `input` is expected to be an object that will be stringified- to JSON and content type set to `application/json; charset=utf-8`. If `options.contentType` is specified, then `input` must be a `String` or- `Buffer`.- - **`[.token]`**: `string` - User API token that is used to run the actor. By default, it is taken from the `APIFY_TOKEN` environment variable.- - **`[.memoryMbytes]`**: `number` - Memory in megabytes which will be allocated for the new actor run. If not provided, the run uses memory of- the default actor run configuration.- - **`[.timeoutSecs]`**: `number` - Timeout for the actor run in seconds. Zero value means there is no timeout. If not provided, the run uses- timeout of the default actor run configuration.- - **`[.build]`**: `string` - Tag or number of the actor build to run (e.g. `beta` or `1.2.345`). If not provided, the run uses build tag or- number from the default actor run configuration (typically `latest`).- - **`[.waitSecs]`**: `string` - Maximum time to wait for the actor run to finish, in seconds. If the limit is reached, the returned promise is- resolved to a run object that will have status `READY` or `RUNNING` and it will not contain the actor run output. If `waitSecs` is null or- undefined, the function waits for the actor to finish (default behavior).- - **`[.fetchOutput]`**: `boolean` <code> = true</code> - If `false` then the function does not fetch output of the actor.- - **`[.disableBodyParser]`**: `boolean` <code> = false</code> - If `true` then the function will not attempt to parse the actor's output and- will return it in a raw `Buffer`.- - **`[.webhooks]`**: `Array<object>` - Specifies optional webhooks associated with the actor run, which can be used to receive a notification- e.g. when the actor finished or failed, see [ad hook webhooks documentation](https://docs.apify.com/webhooks/ad-hoc-webhooks) for detailed- description.-------<a name="calltask"></a>--## `Apify.callTask(taskId, [input], [options])`--**Returns**: [`Promise<ActorRun>`](/docs/typedefs/actor-run)--Runs an actor task on the Apify platform using the current user account (determined by the `APIFY_TOKEN` environment variable), waits for the task to-finish and fetches its output.--By passing the `waitSecs` option you can reduce the maximum amount of time to wait for the run to finish. If the value is less than or equal to zero,-the function returns immediately after the run is started.--The result of the function is an [`ActorRun`](/docs/typedefs/actor-run) object that contains details about the actor run and its output (if any). If-the actor run failed, the function fails with [`ApifyCallError`](/docs/api/apify-call-error) exception.--Note that an actor task is a saved input configuration and options for an actor. If you want to run an actor directly rather than an actor task,-please use the [`Apify.call()`](/docs/api/apify#call) function instead.--For more information about actor tasks, read the [documentation](https://docs.apify.com/tasks).--**Example usage:**--```javascript-const run = await Apify.callTask('bob/some-task');-console.log(`Received message: ${run.output.body.message}`);-```--Internally, the `callTask()` function calls the [Run task](https://apify.com/docs/api/v2#/reference/actor-tasks/run-collection/run-task) and several-other API endpoints to obtain the output.--**Throws**:--- [`ApifyCallError`](/docs/api/apify-call-error) If the run did not succeed, e.g. if it failed or timed out.--**Params**--- **`taskId`**: `string` - Either `username/task-name` or task ID.-- **`[input]`**: `object` - Input overrides for the actor task. If it is an object, it will be stringified to JSON and its content type set to- `application/json; charset=utf-8`. Otherwise the `options.contentType` parameter must be provided. Provided input will be merged with actor task- input.-- **`[options]`**: `Object` <code> = {}</code> - Object with the settings below:- - **`[.contentType]`**: `string` - Content type for the `input`. If not specified, `input` is expected to be an object that will be stringified- to JSON and content type set to `application/json; charset=utf-8`. If `options.contentType` is specified, then `input` must be a `String` or- `Buffer`.- - **`[.token]`**: `string` - User API token that is used to run the actor. By default, it is taken from the `APIFY_TOKEN` environment variable.- - **`[.memoryMbytes]`**: `number` - Memory in megabytes which will be allocated for the new actor task run. If not provided, the run uses memory- of the default actor run configuration.- - **`[.timeoutSecs]`**: `number` - Timeout for the actor task run in seconds. Zero value means there is no timeout. If not provided, the run- uses timeout of the default actor run configuration.- - **`[.build]`**: `string` - Tag or number of the actor build to run (e.g. `beta` or `1.2.345`). If not provided, the run uses build tag or- number from the default actor run configuration (typically `latest`).- - **`[.waitSecs]`**: `string` - Maximum time to wait for the actor task run to finish, in seconds. If the limit is reached, the returned promise- is resolved to a run object that will have status `READY` or `RUNNING` and it will not contain the actor run output. If `waitSecs` is null or- undefined, the function waits for the actor task to finish (default behavior).- - **`[.webhooks]`**: `Array<object>` - Specifies optional webhooks associated with the actor run, which can be used to receive a notification- e.g. when the actor finished or failed, see [ad hook webhooks documentation](https://docs.apify.com/webhooks/ad-hoc-webhooks) for detailed- description.-------<a name="client"></a>--## `Apify.client`--Gets the default instance of the `ApifyClient` class provided <a href="https://docs.apify.com/api/apify-client-js/latest"-target="_blank">apify-client</a> by the NPM package. The instance is created automatically by the Apify SDK and it is configured using the-`APIFY_API_BASE_URL`, `APIFY_USER_ID` and `APIFY_TOKEN` environment variables.--The instance is used for all underlying calls to the Apify API in functions such as [`Apify.getValue()`](/docs/api/apify#getvalue) or-[`Apify.call()`](/docs/api/apify#call). The settings of the client can be globally altered by calling the-<a href="https://docs.apify.com/api/apify-client-js/latest#ApifyClient-setOptions"-target="_blank">`Apify.client.setOptions()`</a> function. Beware that altering these settings might have unintended effects on the entire Apify SDK-package.-------<a name="events"></a>--## `Apify.events`--Gets an instance of a Node.js' [EventEmitter](https://nodejs.org/api/events.html#events_class_eventemitter) class that emits various events from the-SDK or the Apify platform. The event emitter is initialized by calling the [`Apify.main()`](/docs/api/apify#main) function.--**Example usage:**--```javascript-Apify.events.on('cpuInfo', data => {- if (data.isCpuOverloaded) console.log('Oh no, the CPU is overloaded!');-});-```--The following table shows all currently emitted events:--<table>- <thead>- <tr>- <th>Event name</th>- <th>Data</th>- </thead>- <tbody>- <tr>- <td><code>cpuInfo</code></td>- <td><code>{ "isCpuOverloaded": Boolean }</code></td>- </tr>- <tr>- <td colspan="2">- The event is emitted approximately every second- and it indicates whether the actor is using the maximum of available CPU resources.- If that's the case, the actor should not add more workload.- For example, this event is used by the [`AutoscaledPool`](/docs/api/autoscaled-pool) class.- </td>- </tr>- <tr>- <td><code>migrating</code></td>- <td>None</td>- </tr>- <tr>- <td colspan="2">- Emitted when the actor running on the Apify platform is going to be migrated to another worker server soon.- You can use it to persist the state of the actor and abort the run, to speed up migration.- For example, this is used by the [`RequestList`](/docs/api/request-list) class.- </td>- </tr>- <tr>- <td><code>persistState</code></td>- <td><code>{ "isMigrating": Boolean }</code></td>- </tr>- <tr>- <td colspan="2">- Emitted in regular intervals (by default 60 seconds) to notify all components of Apify SDK that it is time to persist- their state, in order to avoid repeating all work when the actor restarts.- This event is automatically emitted together with the <code>migrating</code> event,- in which case the <code>isMigrating</code> flag is set to <code>true</code>. Otherwise the flag is <code>false</code>.- <br><br>- Note that the <code>persistState</code> event is provided merely for user convenience,- you can achieve the same effect using <code>setInterval()</code> and listening for the <code>migrating</code> event.- </td>- </tr>- </tbody>-</table>-------<a name="getapifyproxyurl"></a>--## `Apify.getApifyProxyUrl([options])`--**Returns**: `string` - Returns the proxy URL, e.g. `http://auto:[email protected]:8000`.--Constructs an Apify Proxy URL using the specified settings. The proxy URL can be used from Apify actors, web browsers or any other HTTP proxy-enabled-applications.--For more information, see the [Apify Proxy](https://my.apify.com/proxy) page in the app or the [documentation](https://docs.apify.com/proxy).--**Params**--- **`[options]`**: `Object` - Object with the props below:- - **`[.password]`**: `string` - User's password for the proxy. By default, it is taken from the `APIFY_PROXY_PASSWORD` environment variable,- which is automatically set by the system when running the actors on the Apify cloud, or when using the- [Apify CLI](https://github.com/apifytech/apify-cli) package and the user previously logged in (called `apify login`).- - **`[.groups]`**: `Array<string>` - Array of Apify Proxy groups to be used. If not provided, the proxy will select the groups automatically.- - **`[.session]`**: `string` - Apify Proxy session identifier to be used by the Chrome browser. All HTTP requests going through the proxy with- the same session identifier will use the same target proxy server (i.e. the same IP address), unless using Residential proxies. The identifier- can only contain the following characters: `0-9`, `a-z`, `A-Z`, `"."`, `"_"` and `"~"`.- - **`[.country]`**: `string` - If set and relevant proxies are available in your Apify account, all proxied requests will use IP addresses that- are geolocated to the specified country. For example `GB` for IPs from Great Britain. Note that online services often have their own rules for- handling geolocation and thus the country selection is a best attempt at geolocation, rather than a guaranteed hit. This parameter is- optional, by default, each proxied request is assigned an IP address from a random country. The country code needs to be a two letter ISO- country code. See the- [full list of available country codes](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2#Officially_assigned_code_elements). This parameter is- optional, by default, the proxy uses all available proxy servers from all countries.-------<a name="getenv"></a>--## `Apify.getEnv()`--**Returns**: [`ApifyEnv`](/docs/typedefs/apify-env)--Returns a new [`ApifyEnv`](/docs/typedefs/apify-env) object which contains information parsed from all the `APIFY_XXX` environment variables.--For the list of the `APIFY_XXX` environment variables, see [Actor documentation](https://docs.apify.com/actor/run#environment-variables). If some of-the variables are not defined or are invalid, the corresponding value in the resulting object will be null.-------<a name="getinput"></a>--## `Apify.getInput()`--**Returns**: `Promise<(object|string|Buffer|null)>` - Returns a promise that resolves to an object, string or-[`Buffer`](https://nodejs.org/api/buffer.html), depending on the MIME content type of the record, or `null` if the record is missing.--Gets the actor input value from the default [`KeyValueStore`](/docs/api/key-value-store) associated with the current actor run.--This is just a convenient shortcut for [`keyValueStore.getValue('INPUT')`](keyvaluestore#getvalue). For example, calling the following code:--```javascript-const input = await Apify.getInput();-```--is equivalent to:--```javascript-const store = await Apify.openKeyValueStore();-await store.getValue('INPUT');-```--For more information, see [`Apify.openKeyValueStore()`](/docs/api/apify#openkeyvaluestore) and-[`KeyValueStore.getValue()`](/docs/api/key-value-store#getvalue).-------<a name="getmemoryinfo"></a>--## `Apify.getMemoryInfo()`--**Returns**: [`Promise<MemoryInfo>`](/docs/typedefs/memory-info)--Returns memory statistics of the process and the system, see [`MemoryInfo`](/docs/typedefs/memory-info).--If the process runs inside of Docker, the `getMemoryInfo` gets container memory limits, otherwise it gets system memory limits.--Beware that the function is quite inefficient because it spawns a new process. Therefore you shouldn't call it too often, like more than once per-second.-------<a name="getvalue"></a>--## `Apify.getValue(key)`--**Returns**: `Promise<(object|string|Buffer|null)>` - Returns a promise that resolves to an object, string or-[`Buffer`](https://nodejs.org/api/buffer.html), depending on the MIME content type of the record, or `null` if the record is missing.--Gets a value from the default [`KeyValueStore`](/docs/api/key-value-store) associated with the current actor run.--This is just a convenient shortcut for [`KeyValueStore.getValue()`](/docs/api/key-value-store#getvalue). For example, calling the following code:--```javascript-const value = await Apify.getValue('my-key');-```--is equivalent to:--```javascript-const store = await Apify.openKeyValueStore();-const value = await store.getValue('my-key');-```--To store the value to the default-key value store, you can use the [`Apify.setValue()`](/docs/api/apify#setvalue) function.--For more information, see [`Apify.openKeyValueStore()`](/docs/api/apify#openkeyvaluestore) and-[`KeyValueStore.getValue()`](/docs/api/key-value-store#getvalue).--**Params**--- **`key`**: `string` - Unique record key.-------<a name="isathome"></a>--## `Apify.isAtHome()`--**Returns**: `boolean`--Returns `true` when code is running on Apify platform and `false` otherwise (for example locally).-------<a name="launchpuppeteer"></a>--## `Apify.launchPuppeteer([options])`--**Returns**: `Promise<Browser>` - Promise that resolves to Puppeteer's `Browser` instance.--Launches headless Chrome using Puppeteer pre-configured to work within the Apify platform. The function has the same argument and the return value as-`puppeteer.launch()`. See <a href="https://github.com/GoogleChrome/puppeteer/blob/master/docs/api.md#puppeteerlaunchoptions" target="_blank">-Puppeteer documentation</a> for more details.--The `launchPuppeteer()` function alters the following Puppeteer options:--<ul>- <li>- Passes the setting from the <code>APIFY_HEADLESS</code> environment variable to the <code>headless</code> option,- unless it was already defined by the caller or <code>APIFY_XVFB</code> environment variable is set to <code>1</code>.- Note that Apify Actor cloud platform automatically sets <code>APIFY_HEADLESS=1</code> to all running actors.- </li>- <li>- Takes the <code>proxyUrl</code> option, validates it and adds it to <code>args</code> as <code>--proxy-server=XXX</code>.- The proxy URL must define a port number and have one of the following schemes: <code>http://</code>,- <code>https://</code>, <code>socks4://</code> or <code>socks5://</code>.- If the proxy is HTTP (i.e. has the <code>http://</code> scheme) and contains username or password,- the <code>launchPuppeteer</code> functions sets up an anonymous proxy HTTP- to make the proxy work with headless Chrome. For more information, read the- <a href="https://blog.apify.com/how-to-make-headless-chrome-and-puppeteer-use-a-proxy-server-with-authentication-249a21a79212"- target="_blank">blog post about proxy-chain library</a>.- </li>- <li>- If <code>options.useApifyProxy</code> is <code>true</code> then the function generates a URL of- [Apify Proxy](https://docs.apify.com/proxy)- based on <code>options.apifyProxyGroups</code> and <code>options.apifyProxySession</code> and passes it as <code>options.proxyUrl</code>.- </li>- <li>- The function adds <code>--no-sandbox</code> to <code>args</code> to enable running- headless Chrome in a Docker container on the Apify platform.- </li>- <li>- Sets <code>defaultViewport</code> Puppeteer option (if not already set)- to a more reasonable default for screenshots and debugging.- You can set <code>options.defaultViewport</code> to <code>null</code> if you prefer to let Puppeteer- choose the default viewport size.- </li>-</ul>--To use this function, you need to have the [puppeteer](https://www.npmjs.com/package/puppeteer) NPM package installed in your project. When running on-the Apify cloud, you can achieve that simply by using the `apify/actor-node-chrome` base Docker image for your actor - see-[Apify Actor documentation](https://docs.apify.com/actor/build#base-images) for details.--For an example of usage, see the [Synchronous run Example](../examples/synchronousrun) or the-[Puppeteer proxy Example](../examples/puppeteerwithproxy)--**Params**--- **`[options]`**: [`LaunchPuppeteerOptions`](/docs/typedefs/launch-puppeteer-options) - Optional settings passed to `puppeteer.launch()`. In- addition to [Puppeteer's options](https://pptr.dev/#?product=Puppeteer&show=api-puppeteerlaunchoptions) the object may contain our own- [`LaunchPuppeteerOptions`](/docs/typedefs/launch-puppeteer-options) that enable additional features.-------<a name="main"></a>--## `Apify.main(userFunc)`--Runs the main user function that performs the job of the actor and terminates the process when the user function finishes.--**The `Apify.main()` function is optional** and is provided merely for your convenience. It is mainly useful when you're running your code as an actor-on the [Apify platform](https://apify.com/actors). However, if you want to use Apify SDK tools directly inside your existing projects, e.g. running in-an [Express](https://expressjs.com/) server, on [Google Cloud functions](https://cloud.google.com/functions) or-[AWS Lambda](https://aws.amazon.com/lambda/), it's better to avoid it since the function terminates the main process when it finishes!--The `Apify.main()` function performs the following actions:--<ol>- <li>When running on the Apify platform (i.e. <code>APIFY_IS_AT_HOME</code> environment variable is set),- it sets up a connection to listen for platform events.- For example, to get a notification about an imminent migration to another server.- See [`Apify.events`](/docs/api/apify#events) for details.- </li>- <li>It checks that either <code>APIFY_TOKEN</code> or <code>APIFY_LOCAL_STORAGE_DIR</code> environment variable- is defined. If not, the functions sets <code>APIFY_LOCAL_STORAGE_DIR</code> to <code>./apify_storage</code>- inside the current working directory. This is to simplify running code examples.- </li>- <li>It invokes the user function passed as the <code>userFunc</code> parameter.</li>- <li>If the user function returned a promise, waits for it to resolve.</li>- <li>If the user function throws an exception or some other error is encountered,- prints error details to console so that they are stored to the log.</li>- <li>Exits the Node.js process, with zero exit code on success and non-zero on errors.</li>-</ol>--The user function can be synchronous:--```javascript-Apify.main(() => {- // My synchronous function that returns immediately- console.log('Hello world from actor!');-});-```--If the user function returns a promise, it is considered asynchronous:--```javascript-const { requestAsBrowser } = require('some-request-library');--Apify.main(() => {- // My asynchronous function that returns a promise- return request('http://www.example.com').then(html => {- console.log(html);- });-});-```--To simplify your code, you can take advantage of the `async`/`await` keywords:--```javascript-const request = require('some-request-library');--Apify.main(async () => {- // My asynchronous function- const html = await request('http://www.example.com');- console.log(html);-});-```--**Params**--- **`userFunc`**: [`UserFunc`](/docs/typedefs/user-func) - User function to be executed. If it returns a promise, the promise will be awaited. The- user function is called with no arguments.-------<a name="metamorph"></a>--## `Apify.metamorph(targetActorId, [input], [options])`--**Returns**: `Promise<void>`--Transforms this actor run to an actor run of a given actor. The system stops the current container and starts the new container instead. All the-default storages are preserved and the new input is stored under the `INPUT-METAMORPH-1` key in the same default key-value store.--**Params**--- **`targetActorId`**: `string` - Either `username/actor-name` or actor ID of an actor to which we want to metamorph.-- **`[input]`**: `object` - Input for the actor. If it is an object, it will be stringified to JSON and its content type set to- `application/json; charset=utf-8`. Otherwise the `options.contentType` parameter must be provided.-- **`[options]`**: `Object` <code> = {}</code> - Object with the settings below:- - **`[.contentType]`**: `string` - Content type for the `input`. If not specified, `input` is expected to be an object that will be stringified- to JSON and content type set to `application/json; charset=utf-8`. If `options.contentType` is specified, then `input` must be a `String` or- `Buffer`.- - **`[.build]`**: `string` - Tag or number of the target actor build to metamorph into (e.g. `beta` or `1.2.345`). If not provided, the run uses- build tag or number from the default actor run configuration (typically `latest`).-------<a name="opendataset"></a>--## `Apify.openDataset([datasetIdOrName], [options])`--**Returns**: [`Promise<Dataset>`](/docs/api/dataset)--Opens a dataset and returns a promise resolving to an instance of the [`Dataset`](/docs/api/dataset) class.--Datasets are used to store structured data where each object stored has the same attributes, such as online store products or real estate offers. The-actual data is stored either on the local filesystem or in the cloud.--For more details and code examples, see the [`Dataset`](/docs/api/dataset) class.--**Params**--- **`[datasetIdOrName]`**: `string` - ID or name of the dataset to be opened. If `null` or `undefined`, the function returns the default dataset- associated with the actor run.-- **`[options]`**: `Object`- - **`[.forceCloud]`**: `boolean` <code> = false</code> - If set to `true` then the function uses cloud storage usage even if the- `APIFY_LOCAL_STORAGE_DIR` environment variable is set. This way it is possible to combine local and cloud storage.-------<a name="openkeyvaluestore"></a>--## `Apify.openKeyValueStore([storeIdOrName], [options])`--**Returns**: [`Promise<KeyValueStore>`](/docs/api/key-value-store)--Opens a key-value store and returns a promise resolving to an instance of the [`KeyValueStore`](/docs/api/key-value-store) class.--Key-value stores are used to store records or files, along with their MIME content type. The records are stored and retrieved using a unique key. The-actual data is stored either on a local filesystem or in the Apify cloud.--For more details and code examples, see the [`KeyValueStore`](/docs/api/key-value-store) class.--**Params**--- **`[storeIdOrName]`**: `string` - ID or name of the key-value store to be opened. If `null` or `undefined`, the function returns the default- key-value store associated with the actor run.-- **`[options]`**: `object`- - **`[.forceCloud]`**: `boolean` <code> = false</code> - If set to `true` then the function uses cloud storage usage even if the- `APIFY_LOCAL_STORAGE_DIR` environment variable is set. This way it is possible to combine local and cloud storage.-------<a name="openrequestlist"></a>--## `Apify.openRequestList(listName, sources, [options])`--**Returns**: [`Promise<RequestList>`](/docs/api/request-list)--Opens a request list and returns a promise resolving to an instance of the [`RequestList`](/docs/api/request-list) class that is already initialized.--[`RequestList`](/docs/api/request-list) represents a list of URLs to crawl, which is always stored in memory. To enable picking up where left off-after a process restart, the request list sources are persisted to the key value store at initialization of the list. Then, while crawling, a small-state object is regularly persisted to keep track of the crawling status.--For more details and code examples, see the [`RequestList`](/docs/api/request-list) class.--**Example usage:**--```javascript-const sources = ['https://www.example.com', 'https://www.google.com', 'https://www.bing.com'];--const requestList = await Apify.openRequestList('my-name', sources);-```--**Params**--- **`listName`**: `string` | `null` - Name of the request list to be opened. Setting a name enables the `RequestList`'s state to be persisted in the- key value store. This is useful in case of a restart or migration. Since `RequestList` is only stored in memory, a restart or migration wipes it- clean. Setting a name will enable the `RequestList`'s state to survive those situations and continue where it left off.-- The name will be used as a prefix in key value store, producing keys such as `NAME-REQUEST_LIST_STATE` and `NAME-REQUEST_LIST_SOURCES`.-- If `null`, the list will not be persisted and will only be stored in memory. Process restart will then cause the list to be crawled again from the- beginning. We suggest always using a name.--- **`sources`**: [`Array<(RequestOptions|Request|string)>`](/docs/typedefs/request-options) - An array of sources of URLs for the- [`RequestList`](/docs/api/request-list). It can be either an array of strings, plain objects that define at least the `url` property, or an array- of [`Request`](/docs/api/request) instances.-- **IMPORTANT:** The `sources` array will be consumed (left empty) after [`RequestList`](/docs/api/request-list) initializes. This is a measure to- prevent memory leaks in situations when millions of sources are added.--Additionally, the `requestsFromUrl` property may be used instead of `url`, which will instruct [`RequestList`](/docs/api/request-list) to download the-source URLs from a given remote location. The URLs will be parsed from the received response. In this case you can limit the URLs using `regex`-parameter containing regular expression pattern for URLs to be included.--For details, see the [`RequestListOptions.sources`](/docs/typedefs/request-list-options#sources)--- **`[options]`**: [`RequestListOptions`](/docs/typedefs/request-list-options) - The [`RequestList`](/docs/api/request-list) options. Note that the- `listName` parameter supersedes the [`RequestListOptions.persistStateKey`](/docs/typedefs/request-list-options#persiststatekey) and- [`RequestListOptions.persistRequestsKey`](/docs/typedefs/request-list-options#persistrequestskey) options and the `sources` parameter supersedes- the [`RequestListOptions.sources`](/docs/typedefs/request-list-options#sources) option.-------<a name="openrequestqueue"></a>--## `Apify.openRequestQueue([queueIdOrName], [options])`--**Returns**: [`Promise<RequestQueue>`](/docs/api/request-queue)--Opens a request queue and returns a promise resolving to an instance of the [`RequestQueue`](/docs/api/request-queue) class.--[`RequestQueue`](/docs/api/request-queue) represents a queue of URLs to crawl, which is stored either on local filesystem or in the cloud. The queue-is used for deep crawling of websites, where you start with several URLs and then recursively follow links to other pages. The data structure supports-both breadth-first and depth-first crawling orders.--For more details and code examples, see the [`RequestQueue`](/docs/api/request-queue) class.--**Params**--- **`[queueIdOrName]`**: `string` - ID or name of the request queue to be opened. If `null` or `undefined`, the function returns the default request- queue associated with the actor run.-- **`[options]`**: `object`- - **`[.forceCloud]`**: `boolean` <code> = false</code> - If set to `true` then the function uses cloud storage usage even if the- `APIFY_LOCAL_STORAGE_DIR` environment variable is set. This way it is possible to combine local and cloud storage.-------<a name="opensessionpool"></a>--## `Apify.openSessionPool(sessionPoolOptions)`--**Returns**: [`Promise<SessionPool>`](/docs/api/session-pool)--Opens a SessionPool and returns a promise resolving to an instance of the [`SessionPool`](/docs/api/session-pool) class that is already initialized.--For more details and code examples, see the [`SessionPool`](/docs/api/session-pool) class.--**Params**--- **`sessionPoolOptions`**: [`SessionPoolOptions`](/docs/typedefs/session-pool-options)-------<a name="pushdata"></a>--## `Apify.pushData(item)`--**Returns**: `Promise<void>`--Stores an object or an array of objects to the default [`Dataset`](/docs/api/dataset) of the current actor run.--This is just a convenient shortcut for [`Dataset.pushData()`](/docs/api/dataset#pushdata). For example, calling the following code:--```javascript-await Apify.pushData({ myValue: 123 });-```--is equivalent to:--```javascript-const dataset = await Apify.openDataset();-await dataset.pushData({ myValue: 123 });-```--For more information, see [`Apify.openDataset()`](/docs/api/apify#opendataset) and [`Dataset.pushData()`](/docs/api/dataset#pushdata)--**IMPORTANT**: Make sure to use the `await` keyword when calling `pushData()`, otherwise the actor process might finish before the data are stored!--**Params**--- **`item`**: `object` - Object or array of objects containing data to be stored in the default dataset. The objects must be serializable to JSON- and the JSON representation of each object must be smaller than 9MB.-------<a name="setvalue"></a>--## `Apify.setValue(key, value, [options])`--**Returns**: `Promise<void>`--Stores or deletes a value in the default [`KeyValueStore`](/docs/api/key-value-store) associated with the current actor run.--This is just a convenient shortcut for [`KeyValueStore.setValue()`](/docs/api/key-value-store#setvalue). For example, calling the following code:--```javascript-await Apify.setValue('OUTPUT', { foo: 'bar' });-```--is equivalent to:--```javascript-const store = await Apify.openKeyValueStore();-await store.setValue('OUTPUT', { foo: 'bar' });-```--To get a value from the default-key value store, you can use the [`Apify.getValue()`](/docs/api/apify#getvalue) function.--For more information, see [`Apify.openKeyValueStore()`](/docs/api/apify#openkeyvaluestore) and-[`KeyValueStore.getValue()`](/docs/api/key-value-store#getvalue).--**Params**--- **`key`**: `string` - Unique record key.-- **`value`**: `object` - Record data, which can be one of the following values:- <ul>- <li>If `null`, the record in the key-value store is deleted.</li>- <li>If no `options.contentType` is specified, `value` can be any JavaScript object and it will be stringified to JSON.</li>- <li>If `options.contentType` is specified, `value` is considered raw data and it must be a `String`- or [`Buffer`](https://nodejs.org/api/buffer.html).</li>- </ul>- For any other value an error will be thrown.-- **`[options]`**: `Object`- - **`[.contentType]`**: `string` - Specifies a custom MIME content type of the record.-----diff --git a/docs/api/ApifyCallError.md b/docs/api/ApifyCallError.mddeleted file mode 100644index 1d4b3b8f7..000000000--- a/docs/api/ApifyCallError.md+++ /dev/null@@ -1,45 +0,0 @@-----id: apify-call-error-title: ApifyCallError------<a name="apifycallerror"></a>--The class represents exceptions thrown by the [`Apify.call()`](/docs/api/apify#call) function.--## Properties--### `message`--**Type**: `string`--Error message-------### `run`--**Type**: [`ActorRun`](/docs/typedefs/actor-run)--Object representing the failed actor run.-------### `name`--**Type**: `string`--Contains `"ApifyCallError"`-------<a name="exports.apifycallerror"></a>--## `new ApifyCallError(run, [message])`--**Params**--- **`run`**: [`ActorRun`](/docs/typedefs/actor-run)-- **`[message]`**: `string` <code> = "The actor invoked by Apify.call() did not succeed"</code>-----diff --git a/docs/api/AutoscaledPool.md b/docs/api/AutoscaledPool.mddeleted file mode 100644index b7db8d54a..000000000--- a/docs/api/AutoscaledPool.md+++ /dev/null@@ -1,198 +0,0 @@-----id: autoscaled-pool-title: AutoscaledPool------<a name="autoscaledpool"></a>--Manages a pool of asynchronous resource-intensive tasks that are executed in parallel. The pool only starts new tasks if there is enough free CPU and-memory available and the Javascript event loop is not blocked.--The information about the CPU and memory usage is obtained by the [`Snapshotter`](/docs/api/snapshotter) class, which makes regular snapshots of-system resources that may be either local or from the Apify cloud infrastructure in case the process is running on the Apify platform. Meaningful data-gathered from these snapshots is provided to `AutoscaledPool` by the [`SystemStatus`](/docs/api/system-status) class.--Before running the pool, you need to implement the following three functions:-[`AutoscaledPoolOptions.runTaskFunction()`](/docs/typedefs/autoscaled-pool-options#runtaskfunction),-[`AutoscaledPoolOptions.isTaskReadyFunction()`](/docs/typedefs/autoscaled-pool-options#istaskreadyfunction) and-[`AutoscaledPoolOptions.isFinishedFunction()`](/docs/typedefs/autoscaled-pool-options#isfinishedfunction).--The auto-scaled pool is started by calling the [`AutoscaledPool.run()`](/docs/api/autoscaled-pool#run) function. The pool periodically queries the-[`AutoscaledPoolOptions.isTaskReadyFunction()`](/docs/typedefs/autoscaled-pool-options#istaskreadyfunction) function for more tasks, managing optimal-concurrency, until the function resolves to `false`. The pool then queries the-[`AutoscaledPoolOptions.isFinishedFunction()`](/docs/typedefs/autoscaled-pool-options#isfinishedfunction). If it resolves to `true`, the run finishes-after all running tasks complete. If it resolves to `false`, it assumes there will be more tasks available later and keeps periodically querying for-tasks. If any of the tasks throws then the [`AutoscaledPool.run()`](/docs/api/autoscaled-pool#run) function rejects the promise with an error.--The pool evaluates whether it should start a new task every time one of the tasks finishes and also in the interval set by the-`options.maybeRunIntervalSecs` parameter.--**Example usage:**--```javascript-const pool = new Apify.AutoscaledPool({- maxConcurrency: 50,- runTaskFunction: async () => {- // Run some resource-intensive asynchronous operation here.- },- isTaskReadyFunction: async () => {- // Tell the pool whether more tasks are ready to be processed.- // Return true or false- },- isFinishedFunction: async () => {- // Tell the pool whether it should finish- // or wait for more tasks to become available.- // Return true or false- },-});--await pool.run();-```-------<a name="autoscaledpool"></a>--## `new AutoscaledPool(options)`--**Params**--- **`options`**: [`AutoscaledPoolOptions`](/docs/typedefs/autoscaled-pool-options) - All `AutoscaledPool` configuration options.-------<a name="minconcurrency"></a>--## `autoscaledPool.minConcurrency`--**Returns**: `number`--Gets the minimum number of tasks running in parallel.-------<a name="minconcurrency"></a>--## `autoscaledPool.minConcurrency`--Sets the minimum number of tasks running in parallel.--_WARNING:_ If you set this value too high with respect to the available system memory and CPU, your code might run extremely slow or crash. If you're-not sure, just keep the default value and the concurrency will scale up automatically.--**Params**--- **`value`**: `number`-------<a name="maxconcurrency"></a>--## `autoscaledPool.maxConcurrency`--**Returns**: `number`--Gets the maximum number of tasks running in parallel.-------<a name="maxconcurrency"></a>--## `autoscaledPool.maxConcurrency`--Sets the maximum number of tasks running in parallel.--**Params**--- **`value`**: `number`-------<a name="desiredconcurrency"></a>--## `autoscaledPool.desiredConcurrency`--**Returns**: `number`--Gets the desired concurrency for the pool, which is an estimated number of parallel tasks that the system can currently support.-------<a name="desiredconcurrency"></a>--## `autoscaledPool.desiredConcurrency`--Sets the desired concurrency for the pool, i.e. the number of tasks that should be running in parallel if there's large enough supply of tasks.--**Params**--- **`value`**: `number`-------<a name="currentconcurrency"></a>--## `autoscaledPool.currentConcurrency`--**Returns**: `number`--Gets the the number of parallel tasks currently running in the pool.-------<a name="run"></a>--## `autoscaledPool.run()`--**Returns**: `Promise<void>`--Runs the auto-scaled pool. Returns a promise that gets resolved or rejected once all the tasks are finished or one of them fails.-------<a name="abort"></a>--## `autoscaledPool.abort()`--**Returns**: `Promise<void>`--Aborts the run of the auto-scaled pool and destroys it. The promise returned from the [`AutoscaledPool.run()`](/docs/api/autoscaled-pool#run) function-will immediately resolve, no more new tasks will be spawned and all running tasks will be left in their current state.--Due to the nature of the tasks, auto-scaled pool cannot reliably guarantee abortion of all the running tasks, therefore, no abortion is attempted and-some of the tasks may finish, while others may not. Essentially, auto-scaled pool doesn't care about their state after the invocation of `.abort()`,-but that does not mean that some parts of their asynchronous chains of commands will not execute.-------<a name="pause"></a>--## `autoscaledPool.pause([timeoutSecs])`--**Returns**: `Promise<void>`--Prevents the auto-scaled pool from starting new tasks, but allows the running ones to finish (unlike abort, which terminates them). Used together with-[`AutoscaledPool.resume()`](/docs/api/autoscaled-pool#resume)--The function's promise will resolve once all running tasks have completed and the pool is effectively idle. If the `timeoutSecs` argument is provided,-the promise will reject with a timeout error after the `timeoutSecs` seconds.--The promise returned from the [`AutoscaledPool.run()`](/docs/api/autoscaled-pool#run) function will not resolve when `.pause()` is invoked (unlike-abort, which resolves it).--**Params**--- **`[timeoutSecs]`**: `number`-------<a name="resume"></a>--## `autoscaledPool.resume()`--Resumes the operation of the autoscaled-pool by allowing more tasks to be run. Used together with-[`AutoscaledPool.pause()`](/docs/api/autoscaled-pool#pause)--Tasks will automatically start running again in `options.maybeRunIntervalSecs`.-----diff --git a/docs/api/BasicCrawler.md b/docs/api/BasicCrawler.mddeleted file mode 100644index 4b538192b..000000000--- a/docs/api/BasicCrawler.md+++ /dev/null@@ -1,90 +0,0 @@-----id: basic-crawler-title: BasicCrawler------<a name="basiccrawler"></a>--Provides a simple framework for parallel crawling of web pages. The URLs to crawl are fed either from a static list of URLs or from a dynamic queue of-URLs enabling recursive crawling of websites.--`BasicCrawler` is a low-level tool that requires the user to implement the page download and data extraction functionality themselves. If you want a-crawler that already facilitates this functionality, please consider using [`PuppeteerCrawler`](/docs/api/puppeteer-crawler) or-[`CheerioCrawler`](/docs/api/cheerio-crawler).--`BasicCrawler` invokes the user-provided [`BasicCrawlerOptions.handleRequestFunction`](/docs/typedefs/basic-crawler-options#handlerequestfunction) for-each [`Request`](/docs/api/request) object, which represents a single URL to crawl. The [`Request`](/docs/api/request) objects are fed from the-[`RequestList`](/docs/api/request-list) or the [`RequestQueue`](/docs/api/request-queue) instances provided by the-[`BasicCrawlerOptions.requestList`](/docs/typedefs/basic-crawler-options#requestlist) or-[`BasicCrawlerOptions.requestQueue`](/docs/typedefs/basic-crawler-options#requestqueue) constructor options, respectively.--If both [`BasicCrawlerOptions.requestList`](/docs/typedefs/basic-crawler-options#requestlist) and-[`BasicCrawlerOptions.requestQueue`](/docs/typedefs/basic-crawler-options#requestqueue) options are used, the instance first processes URLs from the-[`RequestList`](/docs/api/request-list) and automatically enqueues all of them to [`RequestQueue`](/docs/api/request-queue) before it starts their-processing. This ensures that a single URL is not crawled multiple times.--The crawler finishes if there are no more [`Request`](/docs/api/request) objects to crawl.--New requests are only dispatched when there is enough free CPU and memory available, using the functionality provided by the-[`AutoscaledPool`](/docs/api/autoscaled-pool) class. All [`AutoscaledPool`](/docs/api/autoscaled-pool) configuration options can be passed to the-`autoscaledPoolOptions` parameter of the `BasicCrawler` constructor. For user convenience, the `minConcurrency` and `maxConcurrency`-[`AutoscaledPool`](/docs/api/autoscaled-pool) options are available directly in the `BasicCrawler` constructor.--**Example usage:**--```javascript-// Prepare a list of URLs to crawl-const requestList = new Apify.RequestList({- sources: [{ url: 'http://www.example.com/page-1' }, { url: 'http://www.example.com/page-2' }],-});-await requestList.initialize();--// Crawl the URLs-const crawler = new Apify.BasicCrawler({- requestList,- handleRequestFunction: async ({ request }) => {- // 'request' contains an instance of the Request class- // Here we simply fetch the HTML of the page and store it to a dataset- const { body } = await Apify.utils.requestAsBrowser(request);- await Apify.pushData({- url: request.url,- html: body,- });- },-});--await crawler.run();-```--## Properties--### `autoscaledPool`--**Type**: [`AutoscaledPool`](/docs/api/autoscaled-pool)--A reference to the underlying [`AutoscaledPool`](/docs/api/autoscaled-pool) class that manages the concurrency of the crawler. Note that this property-is only initialized after calling the [`BasicCrawler.run()`](/docs/api/basic-crawler#run) function. You can use it to change the concurrency settings-on the fly, to pause the crawler by calling [`AutoscaledPool.pause()`](/docs/api/autoscaled-pool#pause) or to abort it by calling-[`AutoscaledPool.abort()`](/docs/api/autoscaled-pool#abort).-------<a name="basiccrawler"></a>--## `new BasicCrawler(options)`--**Params**--- **`options`**: [`BasicCrawlerOptions`](/docs/typedefs/basic-crawler-options) - All `BasicCrawler` parameters are passed via an options object.-------<a name="run"></a>--## `basicCrawler.run()`--**Returns**: `Promise<void>`--Runs the crawler. Returns a promise that gets resolved once all the requests are processed.-----diff --git a/docs/api/CheerioCrawler.md b/docs/api/CheerioCrawler.mddeleted file mode 100644index d3df7ad1f..000000000--- a/docs/api/CheerioCrawler.md+++ /dev/null@@ -1,113 +0,0 @@-----id: cheerio-crawler-title: CheerioCrawler------<a name="cheeriocrawler"></a>--Provides a framework for the parallel crawling of web pages using plain HTTP requests and [cheerio](https://www.npmjs.com/package/cheerio) HTML-parser. The URLs to crawl are fed either from a static list of URLs or from a dynamic queue of URLs enabling recursive crawling of websites.--Since `CheerioCrawler` uses raw HTTP requests to download web pages, it is very fast and efficient on data bandwidth. However, if the target website-requires JavaScript to display the content, you might need to use [`PuppeteerCrawler`](/docs/api/puppeteer-crawler) instead, because it loads the-pages using full-featured headless Chrome browser.--`CheerioCrawler` downloads each URL using a plain HTTP request, parses the HTML content using [Cheerio](https://www.npmjs.com/package/cheerio) and-then invokes the user-provided [`CheerioCrawlerOptions.handlePageFunction`](/docs/typedefs/cheerio-crawler-options#handlepagefunction) to extract page-data using a [jQuery](https://jquery.com/)-like interface to the parsed HTML DOM.--The source URLs are represented using [`Request`](/docs/api/request) objects that are fed from [`RequestList`](/docs/api/request-list) or-[`RequestQueue`](/docs/api/request-queue) instances provided by the-[`CheerioCrawlerOptions.requestList`](/docs/typedefs/cheerio-crawler-options#requestlist) or-[`CheerioCrawlerOptions.requestQueue`](/docs/typedefs/cheerio-crawler-options#requestqueue) constructor options, respectively.--If both [`CheerioCrawlerOptions.requestList`](/docs/typedefs/cheerio-crawler-options#requestlist) and-[`CheerioCrawlerOptions.requestQueue`](/docs/typedefs/cheerio-crawler-options#requestqueue) are used, the instance first processes URLs from the-[`RequestList`](/docs/api/request-list) and automatically enqueues all of them to [`RequestQueue`](/docs/api/request-queue) before it starts their-processing. This ensures that a single URL is not crawled multiple times.--The crawler finishes when there are no more [`Request`](/docs/api/request) objects to crawl.--`CheerioCrawler` downloads the web pages using the [`utils.requestAsBrowser()`](/docs/api/utils#requestasbrowser) utility function. You can use the-`requestOptions` parameter to pass additional options to this function.--By default, `CheerioCrawler` only processes web pages with the `text/html` and `application/xhtml+xml` MIME content types (as reported by the-`Content-Type` HTTP header), and skips pages with other content types. If you want the crawler to process other content types, use the-[`CheerioCrawlerOptions.additionalMimeTypes`](/docs/typedefs/cheerio-crawler-options#additionalmimetypes) constructor option. Beware that the parsing-behavior differs for HTML, XML, JSON and other types of content. For details, see-[`CheerioCrawlerOptions.handlePageFunction`](/docs/typedefs/cheerio-crawler-options#handlepagefunction).--New requests are only dispatched when there is enough free CPU and memory available, using the functionality provided by the-[`AutoscaledPool`](/docs/api/autoscaled-pool) class. All [`AutoscaledPool`](/docs/api/autoscaled-pool) configuration options can be passed to the-`autoscaledPoolOptions` parameter of the `CheerioCrawler` constructor. For user convenience, the `minConcurrency` and `maxConcurrency`-[`AutoscaledPool`](/docs/api/autoscaled-pool) options are available directly in the `CheerioCrawler` constructor.--**Example usage:**--```javascript-// Prepare a list of URLs to crawl-const requestList = new Apify.RequestList({- sources: [{ url: 'http://www.example.com/page-1' }, { url: 'http://www.example.com/page-2' }],-});-await requestList.initialize();--// Crawl the URLs-const crawler = new Apify.CheerioCrawler({- requestList,- handlePageFunction: async ({ request, response, body, contentType, $ }) => {- const data = [];-- // Do some data extraction from the page with Cheerio.- $('.some-collection').each((index, el) => {- data.push({- title: $(el)- .find('.some-title')- .text(),- });- });-- // Save the data to dataset.- await Apify.pushData({- url: request.url,- html: body,- data,- });- },-});--await crawler.run();-```--## Properties--### `autoscaledPool`--**Type**: [`AutoscaledPool`](/docs/api/autoscaled-pool)--A reference to the underlying [`AutoscaledPool`](/docs/api/autoscaled-pool) class that manages the concurrency of the crawler. Note that this property-is only initialized after calling the [`CheerioCrawler.run()`](/docs/api/cheerio-crawler#run) function. You can use it to change the concurrency-settings on the fly, to pause the crawler by calling [`AutoscaledPool.pause()`](/docs/api/autoscaled-pool#pause) or to abort it by calling-[`AutoscaledPool.abort()`](/docs/api/autoscaled-pool#abort).-------<a name="cheeriocrawler"></a>--## `new CheerioCrawler(options)`--**Params**--- **`options`**: [`CheerioCrawlerOptions`](/docs/typedefs/cheerio-crawler-options) - All `CheerioCrawler` parameters are passed via an options- object.-------<a name="run"></a>--## `cheerioCrawler.run()`--**Returns**: `Promise<void>`--Runs the crawler. Returns promise that gets resolved once all the requests got processed.-----diff --git a/docs/api/CookieParseError.md b/docs/api/CookieParseError.mddeleted file mode 100644index 73d38c734..000000000--- a/docs/api/CookieParseError.md+++ /dev/null@@ -1,18 +0,0 @@-----id: cookie-parse-error-title: CookieParseError------<a name="cookieparseerror"></a>-------<a name="exports.cookieparseerror"></a>--## `new CookieParseError(cookieHeaderString)`--**Params**--- **`cookieHeaderString`**: `string`-----diff --git a/docs/api/Dataset.md b/docs/api/Dataset.mddeleted file mode 100644index c5c336e0e..000000000--- a/docs/api/Dataset.md+++ /dev/null@@ -1,255 +0,0 @@-----id: dataset-title: Dataset------<a name="dataset"></a>--The `Dataset` class represents a store for structured data where each object stored has the same attributes, such as online store products or real-estate offers. You can imagine it as a table, where each object is a row and its attributes are columns. Dataset is an append-only storage - you can-only add new records to it but you cannot modify or remove existing records. Typically it is used to store crawling results.--Do not instantiate this class directly, use the [`Apify.openDataset()`](/docs/api/apify#opendataset) function instead.--`Dataset` stores its data either on local disk or in the Apify cloud, depending on whether the `APIFY_LOCAL_STORAGE_DIR` or `APIFY_TOKEN` environment-variables are set.--If the `APIFY_LOCAL_STORAGE_DIR` environment variable is set, the data is stored in the local directory in the following files:--```-{APIFY_LOCAL_STORAGE_DIR}/datasets/{DATASET_ID}/{INDEX}.json-```--Note that `{DATASET_ID}` is the name or ID of the dataset. The default dataset has ID: `default`, unless you override it by setting the-`APIFY_DEFAULT_DATASET_ID` environment variable. Each dataset item is stored as a separate JSON file, where `{INDEX}` is a zero-based index of the-item in the dataset.--If the `APIFY_TOKEN` environment variable is set but `APIFY_LOCAL_STORAGE_DIR` not, the data is stored in the-[Apify Dataset](https://docs.apify.com/storage/dataset) cloud storage. Note that you can force usage of the cloud storage also by passing the-`forceCloud` option to [`Apify.openDataset()`](/docs/api/apify#opendataset) function, even if the `APIFY_LOCAL_STORAGE_DIR` variable is set.--**Example usage:**--```javascript-// Write a single row to the default dataset-await Apify.pushData({ col1: 123, col2: 'val2' });--// Open a named dataset-const dataset = await Apify.openDataset('some-name');--// Write a single row-await dataset.pushData({ foo: 'bar' });--// Write multiple rows-await dataset.pushData([{ foo: 'bar2', col2: 'val2' }, { col3: 123 }]);-```-------<a name="exports.dataset"></a>--## `new Dataset(datasetId, datasetName)`--**Params**--- **`datasetId`**: `string`-- **`datasetName`**: `string`-------<a name="pushdata"></a>--## `dataset.pushData(data)`--**Returns**: `Promise<void>`--Stores an object or an array of objects to the dataset. The function returns a promise that resolves when the operation finishes. It has no result,-but throws on invalid args or other errors.--**IMPORTANT**: Make sure to use the `await` keyword when calling `pushData()`, otherwise the actor process might finish before the data is stored!--The size of the data is limited by the receiving API and therefore `pushData()` will only allow objects whose JSON representation is smaller than 9MB.-When an array is passed, none of the included objects may be larger than 9MB, but the array itself may be of any size.--The function internally chunks the array into separate items and pushes them sequentially. The chunking process is stable (keeps order of data), but-it does not provide a transaction safety mechanism. Therefore, in the event of an uploading error (after several automatic retries), the function's-Promise will reject and the dataset will be left in a state where some of the items have already been saved to the dataset while other items from the-source array were not. To overcome this limitation, the developer may, for example, read the last item saved in the dataset and re-attempt the save of-the data from this item onwards to prevent duplicates.--**Params**--- **`data`**: `object` | `Array<object>` - Object or array of objects containing data to be stored in the default dataset. The objects must be- serializable to JSON and the JSON representation of each object must be smaller than 9MB.-------<a name="getdata"></a>--## `dataset.getData([options])`--**Returns**: [`Promise<DatasetContent>`](/docs/typedefs/dataset-content)--Returns {DatasetContent} object holding the items in the dataset based on the provided parameters.--**NOTE**: If using dataset with local disk storage, the `format` option must be `json` and the following options are not supported: `unwind`,-`disableBodyParser`, `attachment`, `bom` and `simplified`. If you try to use them, you will receive an error.--**Params**--- **`[options]`**: `Object` - All `getData()` parameters are passed via an options object with the following keys:- - **`[.format]`**: `string` <code> = "'json'"</code> - Format of the `items` property, possible values are: `json`, `csv`,- `xlsx`, `html`, `xml` and `rss`.- - **`[.offset]`**: `number` <code> = 0</code> - Number of array elements that should be skipped at the start.- - **`[.limit]`**: `number` <code> = 250000</code> - Maximum number of array elements to return.- - **`[.desc]`**: `boolean` <code> = false</code> - If `true` then the objects are sorted by `createdAt` in descending order. Otherwise they are- sorted in ascending order.- - **`[.fields]`**: `Array<string>` - An array of field names that will be included in the result. If omitted, all fields are included in the- results.- - **`[.unwind]`**: `string` - Specifies a name of the field in the result objects that will be used to unwind the resulting objects. By default,- the results are returned as they are.- - **`[.disableBodyParser]`**: `boolean` <code> = false</code> - If `true` then response from API will not be parsed.- - **`[.attachment]`**: `boolean` <code> = false</code> - If `true` then the response will define the `Content-Disposition: attachment` HTTP- header, forcing a web browser to download the file rather than to display it. By default, this header is not present.- - **`[.delimiter]`**: `string` <code> = "','"</code> - A delimiter character for CSV files, only used if `format` is `csv`.- - **`[.bom]`**: `boolean` - All responses are encoded in UTF-8 encoding. By default, the CSV files are prefixed with the UTF-8 Byte Order Mark- (BOM), while JSON, JSONL, XML, HTML and RSS files are not. If you want to override this default behavior, set `bom` option to `true` to- include the BOM, or set `bom` to `false` to skip it.- - **`[.xmlRoot]`**: `string` <code> = "'results'"</code> - Overrides the default root element name of the XML output. By- default, the root element is `results`.- - **`[.xmlRow]`**: `string` <code> = "'page'"</code> - Overrides the default element name that wraps each page or page- function result object in XML output. By default, the element name is `page` or `result`, depending on the value of the `simplified` option.- - **`[.skipHeaderRow]`**: `boolean` <code> = false</code> - If set to `true` then header row in CSV format is skipped.- - **`[.clean]`**: `boolean` <code> = false</code> - If `true` then the function returns only non-empty items and skips hidden fields (i.e.- fields starting with `#` character). Note that the `clean` parameter is a shortcut for `skipHidden: true` and `skipEmpty: true` options.- - **`[.skipHidden]`**: `boolean` <code> = false</code> - If `true` then the function doesn't return hidden fields (fields starting with "#"- character).- - **`[.skipEmpty]`**: `boolean` <code> = false</code> - If `true` then the function doesn't return empty items. Note that in this case the- returned number of items might be lower than limit parameter and pagination must be done using the `limit` value.- - **`[.simplified]`**: `boolean` - If `true` then function applies the `fields: ['url','pageFunctionResult','errorInfo']` and- `unwind: 'pageFunctionResult'` options. This feature is used to emulate simplified results provided by Apify API version 1 used for the legacy- Apify Crawler and it's not recommended to use it in new integrations.- - **`[.skipFailedPages]`**: `boolean` - If `true` then, the all the items with errorInfo property will be skipped from the output. This feature- is here to emulate functionality of Apify API version 1 used for the legacy Apify Crawler product and it's not recommended to use it in new- integrations.-------<a name="getinfo"></a>--## `dataset.getInfo()`--**Returns**: `Promise<object>`--Returns an object containing general information about the dataset.--The function returns the same object as the Apify API Client's-[getDataset](https://docs.apify.com/api/apify-client-js/latest#ApifyClient-datasets-getDataset) function, which in turn calls the-[Get dataset](https://apify.com/docs/api/v2#/reference/datasets/dataset/get-dataset) API endpoint.--**Example:**--```-{- id: "WkzbQMuFYuamGv3YF",- name: "my-dataset",- userId: "wRsJZtadYvn4mBZmm",- createdAt: new Date("2015-12-12T07:34:14.202Z"),- modifiedAt: new Date("2015-12-13T08:36:13.202Z"),- accessedAt: new Date("2015-12-14T08:36:13.202Z"),- itemCount: 14,- cleanItemCount: 10-}-```-------<a name="foreach"></a>--## `dataset.forEach(iteratee, [options], [index])`--**Returns**: `Promise<void>`--Iterates over dataset items, yielding each in turn to an `iteratee` function. Each invocation of `iteratee` is called with two arguments:-`(item, index)`.--If the `iteratee` function returns a Promise then it is awaited before the next call. If it throws an error, the iteration is aborted and the-`forEach` function throws the error.--**Example usage**--```javascript-const dataset = await Apify.openDataset('my-results');-await dataset.forEach(async (item, index) => {- console.log(`Item at ${index}: ${JSON.stringify(item)}`);-});-```--**Params**--- **`iteratee`**: [`DatasetConsumer`](/docs/typedefs/dataset-consumer) - A function that is called for every item in the dataset.-- **`[options]`**: `Object` - All `forEach()` parameters are passed via an options object with the following keys:- - **`[.desc]`**: `boolean` <code> = false</code> - If `true` then the objects are sorted by `createdAt` in descending order.- - **`[.fields]`**: `Array<string>` - If provided then returned objects will only contain specified keys.- - **`[.unwind]`**: `string` - If provided then objects will be unwound based on provided field.-- **`[index]`**: `number` <code> = 0</code> - Specifies the initial index number passed to the `iteratee` function.-------<a name="map"></a>--## `dataset.map(iteratee, [options])`--**Returns**: `Promise<Array<object>>`--Produces a new array of values by mapping each value in list through a transformation function `iteratee()`. Each invocation of `iteratee()` is called-with two arguments: `(element, index)`.--If `iteratee` returns a `Promise` then it's awaited before a next call.--**Params**--- **`iteratee`**: [`DatasetMapper`](/docs/typedefs/dataset-mapper)-- **`[options]`**: `Object` - All `map()` parameters are passed via an options object with the following keys:- - **`[.desc]`**: `boolean` <code> = false</code> - If `true` then the objects are sorted by createdAt in descending order.- - **`[.fields]`**: `Array<string>` - If provided then returned objects will only contain specified keys- - **`[.unwind]`**: `string` - If provided then objects will be unwound based on provided field.-------<a name="reduce"></a>--## `dataset.reduce(iteratee, memo, [options])`--**Returns**: `Promise<object>`--Reduces a list of values down to a single value.--Memo is the initial state of the reduction, and each successive step of it should be returned by `iteratee()`. The `iteratee()` is passed three-arguments: the `memo`, then the `value` and `index` of the iteration.--If no `memo` is passed to the initial invocation of reduce, the `iteratee()` is not invoked on the first element of the list. The first element is-instead passed as the memo in the invocation of the `iteratee()` on the next element in the list.--If `iteratee()` returns a `Promise` then it's awaited before a next call.--**Params**--- **`iteratee`**: [`DatasetReducer`](/docs/typedefs/dataset-reducer)-- **`memo`**: `object` - Initial state of the reduction.-- **`[options]`**: `Object` - All `reduce()` parameters are passed via an options object with the following keys:- - **`[.desc]`**: `boolean` <code> = false</code> - If `true` then the objects are sorted by createdAt in descending order.- - **`[.fields]`**: `Array<string>` - If provided then returned objects will only contain specified keys- - **`[.unwind]`**: `string` - If provided then objects will be unwound based on provided field.-------<a name="drop"></a>--## `dataset.drop()`--**Returns**: `Promise<void>`--Removes the dataset either from the Apify cloud storage or from the local directory, depending on the mode of operation.-----diff --git a/docs/api/KeyValueStore.md b/docs/api/KeyValueStore.mddeleted file mode 100644index 23b868115..000000000--- a/docs/api/KeyValueStore.md+++ /dev/null@@ -1,213 +0,0 @@-----id: key-value-store-title: KeyValueStore------<a name="keyvaluestore"></a>--The `KeyValueStore` class represents a key-value store, a simple data storage that is used for saving and reading data records or files. Each data-record is represented by a unique key and associated with a MIME content type. Key-value stores are ideal for saving screenshots, actor inputs and-outputs, web pages, PDFs or to persist the state of crawlers.--Do not instantiate this class directly, use the [`Apify.openKeyValueStore()`](/docs/api/apify#openkeyvaluestore) function instead.--Each actor run is associated with a default key-value store, which is created exclusively for the run. By convention, the actor input and output are-stored into the default key-value store under the `INPUT` and `OUTPUT` key, respectively. Typically, input and output are JSON files, although it can-be any other format. To access the default key-value store directly, you can use the [`Apify.getValue()`](/docs/api/apify#getvalue) and-[`Apify.setValue()`](/docs/api/apify#setvalue) convenience functions.--To access the input, you can also use the [`Apify.getInput()`](/docs/api/apify#getinput) convenience function.--`KeyValueStore` stores its data either on local disk or in the Apify cloud, depending on whether the-[`APIFY_LOCAL_STORAGE_DIR`](/docs/guides/environment-variables#APIFY_LOCAL_STORAGE_DIR) or-[`APIFY_TOKEN`](/docs/guides/environment-variables#APIFY_TOKEN) environment variables are set.--If the `APIFY_LOCAL_STORAGE_DIR` environment variable is set, the data is stored in the local directory in the following files:--```-{APIFY_LOCAL_STORAGE_DIR}/key_value_stores/{STORE_ID}/{INDEX}.{EXT}-```--Note that `{STORE_ID}` is the name or ID of the key-value store. The default key value store has ID: `default`, unless you override it by setting the-`APIFY_DEFAULT_KEY_VALUE_STORE_ID` environment variable. The `{KEY}` is the key of the record and `{EXT}` corresponds to the MIME content type of the-data value.--If the [`APIFY_TOKEN`](/docs/guides/environment-variables#APIFY_TOKEN) environment variable is set but-[`APIFY_LOCAL_STORAGE_DIR`](/docs/guides/environment-variables#APIFY_LOCAL_STORAGE_DIR) not, the data is stored in the-[Apify Key-value store](https://docs.apify.com/storage/key-value-store) cloud storage. Note that you can force usage of the cloud storage also by-passing the `forceCloud` option to [`Apify.openKeyValueStore()`](/docs/api/apify#openkeyvaluestore) function, even if the-[`APIFY_LOCAL_STORAGE_DIR`](/docs/guides/environment-variables#APIFY_LOCAL_STORAGE_DIR) variable is set.--**Example usage:**--```javascript-// Get actor input from the default key-value store-const input = await Apify.getInput();-const otherValue = Apify.getValue('my-key');--// Write actor output to the default key-value store.-await Apify.setValue('OUTPUT', { myResult: 123 });--// Open a named key-value store-const store = await Apify.openKeyValueStore('some-name');--// Write a record. JavaScript object is automatically converted to JSON,-// strings and binary buffers are stored as they are-await store.setValue('some-key', { foo: 'bar' });--// Read a record. Note that JSON is automatically parsed to a JavaScript object,-// text data returned as a string and other data is returned as binary buffer-const value = await store.getValue('some-key');--// Drop (delete) the store-await store.drop();-```-------<a name="exports.keyvaluestore"></a>--## `new KeyValueStore(storeId, storeName)`--**Params**--- **`storeId`**: `string`-- **`storeName`**: `string`-------<a name="getvalue"></a>--## `keyValueStore.getValue(key)`--**Returns**: `Promise<(object|Buffer|string|null)>` - Returns a promise that resolves to an object, string or-[`Buffer`](https://nodejs.org/api/buffer.html), depending on the MIME content type of the record.--Gets a value from the key-value store.--The function returns a `Promise` that resolves to the record value, whose JavaScript type depends on the MIME content type of the record. Records with-the `application/json` content type are automatically parsed and returned as a JavaScript object. Similarly, records with `text/plain` content types-are returned as a string. For all other content types, the value is returned as a raw [`Buffer`](https://nodejs.org/api/buffer.html) instance.--If the record does not exist, the function resolves to `null`.--To save or delete a value in the key-value store, use the [`KeyValueStore.setValue()`](/docs/api/key-value-store#setvalue) function.--**Example usage:**--```javascript-const store = await Apify.openKeyValueStore();-const buffer = await store.getValue('screenshot1.png');-```--**Params**--- **`key`**: `string` - Unique key of the record. It can be at most 256 characters long and only consist of the following characters: `a`-`z`,- `A`-`Z`, `0`-`9` and `!-_.'()`-------<a name="setvalue"></a>--## `keyValueStore.setValue(key, value, [options])`--**Returns**: `Promise<void>`--Saves or deletes a record in the key-value store. The function returns a promise that resolves once the record has been saved or deleted.--**Example usage:**--```javascript-const store = await Apify.openKeyValueStore();-await store.setValue('OUTPUT', { foo: 'bar' });-```--Beware that the key can be at most 256 characters long and only contain the following characters: `a-zA-Z0-9!-_.'()`--By default, `value` is converted to JSON and stored with the `application/json; charset=utf-8` MIME content type. To store the value with another-content type, pass it in the options as follows:--```javascript-const store = await Apify.openKeyValueStore('my-text-store');-await store.setValue('RESULTS', 'my text data', { contentType: 'text/plain' });-```--If you set custom content type, `value` must be either a string or [`Buffer`](https://nodejs.org/api/buffer.html), otherwise an error will be thrown.--If `value` is `null`, the record is deleted instead. Note that the `setValue()` function succeeds regardless whether the record existed or not.--To retrieve a value from the key-value store, use the [`KeyValueStore.getValue()`](/docs/api/key-value-store#getvalue) function.--**IMPORTANT:** Always make sure to use the `await` keyword when calling `setValue()`, otherwise the actor process might finish before the value is-stored!--**Params**--- **`key`**: `string` - Unique key of the record. It can be at most 256 characters long and only consist of the following characters: `a`-`z`,- `A`-`Z`, `0`-`9` and `!-_.'()`-- **`value`**: `Object` | `string` | `Buffer` | `null` - Record data, which can be one of the following values:- <ul>- <li>If `null`, the record in the key-value store is deleted.</li>- <li>If no `options.contentType` is specified, `value` can be any JavaScript object and it will be stringified to JSON.</li>- <li>If `options.contentType` is specified, `value` is considered raw data and it must be either a `String`- or [`Buffer`](https://nodejs.org/api/buffer.html).</li>- </ul>- For any other value an error will be thrown.-- **`[options]`**: `Object`- - **`[.contentType]`**: `string` - Specifies a custom MIME content type of the record.-------<a name="drop"></a>--## `keyValueStore.drop()`--**Returns**: `Promise<void>`--Removes the key-value store either from the Apify cloud storage or from the local directory, depending on the mode of operation.-------<a name="getpublicurl"></a>--## `keyValueStore.getPublicUrl(key)`--**Returns**: `string`--Returns a URL for the given key that may be used to publicly access the value in the remote key value store.--**Params**--- **`key`**: `string`-------<a name="foreachkey"></a>--## `keyValueStore.forEachKey(iteratee, [options])`--**Returns**: `Promise<void>`--Iterates over key value store keys, yielding each in turn to an `iteratee` function. Each invocation of `iteratee` is called with three arguments:-`(key, index, info)`, where `key` is the record key, `index` is a zero-based index of the key in the current iteration (regardless of-`options.exclusiveStartKey`) and `info` is an object that contains a single property `size` indicating size of the record in bytes.--If the `iteratee` function returns a Promise then it is awaited before the next call. If it throws an error, the iteration is aborted and the-`forEachKey` function throws the error.--**Example usage**--```javascript-const keyValueStore = await Apify.openKeyValueStore();-await keyValueStore.forEachKey(async (key, index, info) => {- console.log(`Key at ${index}: ${key} has size ${info.size}`);-});-```--**Params**--- **`iteratee`**: [`KeyConsumer`](/docs/typedefs/key-consumer) - A function that is called for every key in the key value store.-- **`[options]`**: `Object` - All `forEachKey()` parameters are passed via an options object with the following keys:- - **`[.exclusiveStartKey]`**: `string` - All keys up to this one (including) are skipped from the result.-----diff --git a/docs/api/LiveViewServer.md b/docs/api/LiveViewServer.mddeleted file mode 100644index 6af51a82a..000000000--- a/docs/api/LiveViewServer.md+++ /dev/null@@ -1,108 +0,0 @@-----id: live-view-server-title: LiveViewServer------<a name="liveviewserver"></a>--`LiveViewServer` enables serving of browser snapshots via web sockets. It includes its own client that provides a simple frontend to viewing the-captured snapshots. A snapshot consists of three pieces of information, the currently opened URL, the content of the page (HTML) and its screenshot.--```json-{- "pageUrl": "https://www.example.com",- "htmlContent": "<html><body> ....",- "screenshotIndex": 3,- "createdAt": "2019-04-18T11:50:40.060Z"-}-```--`LiveViewServer` is useful when you want to be able to inspect the current browser status on demand. When no client is connected, the webserver-consumes very low resources so it should have a close to zero impact on performance. Only once a client connects the server will start serving-snapshots. Once no longer needed, it can be disabled again in the client to remove any performance impact.--NOTE: Screenshot taking in browser typically takes around 300ms. So having the `LiveViewServer` always serve snapshots will have a significant impact-on performance.--When using [`PuppeteerPool`](/docs/api/puppeteer-pool), the `LiveViewServer` can be easily used just by providing the `useLiveView = true` option to-the [`PuppeteerPool`](/docs/api/puppeteer-pool). It can also be initiated via [`PuppeteerCrawler`](/docs/api/puppeteer-crawler)-`puppeteerPoolOptions`.--It will take snapshots of the first page of the latest browser. Taking snapshots of only a single page improves performance and stability dramatically-in high concurrency situations.--When running locally, it is often best to use a headful browser for debugging, since it provides a better view into the browser, including DevTools,-but `LiveViewServer` works too.-------<a name="liveviewserver"></a>--## `new LiveViewServer([options])`--**Params**--- **`[options]`**: `Object` - All `LiveViewServer` parameters are passed via an options object with the following keys:- - **`[.screenshotDirectoryPath]`**: `string` - By default, the screenshots are saved to the `live_view` directory in the Apify local storage- directory. Provide a different absolute path to change the settings.- - **`[.maxScreenshotFiles]`**: `number` <code> = 10</code> - Limits the number of screenshots stored by the server. This is to prevent using up- too much disk space.- - **`[.snapshotTimeoutSecs]`**: `number` <code> = 3</code> - If a snapshot is not made within the timeout, its creation will be aborted. This is- to prevent pages from being hung up by a stalled screenshot.- - **`[.maxSnapshotFrequencySecs]`**: `number` <code> = 2</code> - Use this parameter to further decrease the resource consumption of- `LiveViewServer` by limiting the frequency at which it'll serve snapshots.-------<a name="start"></a>--## `liveViewServer.start()`--**Returns**: `Promise<void>`--Starts the HTTP server with web socket connections enabled. Snapshots will not be created until a client has connected.-------<a name="stop"></a>--## `liveViewServer.stop()`--**Returns**: `Promise<void>`--Prevents the server from receiving more connections. Existing connections will not be terminated, but the server will not prevent a process exit.-------<a name="serve"></a>--## `liveViewServer.serve(page)`--**Returns**: `Promise<void>`--Serves a snapshot to all connected clients. Screenshots are not served directly, only their index number which is used by client to retrieve the-screenshot.--Will time out and throw in `options.snapshotTimeoutSecs`.--**Params**--- **`page`**: `Page`-------<a name="isrunning"></a>--## `liveViewServer.isRunning()`--**Returns**: `boolean`-------<a name="hasclients"></a>--## `liveViewServer.hasClients()`--**Returns**: `boolean`-----diff --git a/docs/api/PseudoUrl.md b/docs/api/PseudoUrl.mddeleted file mode 100644index 074cf2125..000000000--- a/docs/api/PseudoUrl.md+++ /dev/null@@ -1,98 +0,0 @@-----id: pseudo-url-title: PseudoUrl------<a name="pseudourl"></a>--Represents a pseudo-URL (PURL) - an URL pattern used by web crawlers to specify which URLs should the crawler visit. This class is used by the-[`utils.enqueueLinks()`](/docs/api/utils#enqueuelinks) function.--A PURL is simply a URL with special directives enclosed in `[]` brackets. Currently, the only supported directive is `[RegExp]`, which defines a-JavaScript-style regular expression to match against the URL.--The `PseudoUrl` class can be constructed either using a pseudo-URL string or a regular expression (an instance of the `RegExp` object). With a-pseudo-URL string, the matching is always case-insensitive. If you need case-sensitive matching, use an appropriate `RegExp` object.--For example, a PURL `http://www.example.com/pages/[(\w|-)*]` will match all of the following URLs:--<ul>- <li><code>http://www.example.com/pages/</code></li>- <li><code>http://www.example.com/pages/my-awesome-page</code></li>- <li><code>http://www.example.com/pages/something</code></li>-</ul>--Be careful to correctly escape special characters in the pseudo-URL string. If either `[` or `]` is part of the normal query string, it must be-encoded as `[\x5B]` or `[\x5D]`, respectively. For example, the following PURL:--```http-http://www.example.com/search?do[\x5B]load[\x5D]=1-```--will match the URL:--```http-http://www.example.com/search?do[load]=1-```--If the regular expression in the pseudo-URL contains a backslash character (\), you need to escape it with another back backslash, as shown in the-example below.--**Example usage:**--```javascript-// Using a pseudo-URL string-const purl = new Apify.PseudoUrl('http://www.example.com/pages/[(\\w|-)+]', {- userData: { foo: 'bar' },-});--// Using a regular expression-const purl2 = new Apify.PseudoUrl(/http:\/\/www\.example\.com\/pages\/(\w|-)+/);--if (purl.matches('http://www.example.com/pages/my-awesome-page')) console.log('Match!');-```-------<a name="pseudourl"></a>--## `new PseudoUrl(purl, requestTemplate)`--**Params**--- **`purl`**: `string` | `RegExp` - A pseudo-URL string or a regular expression object. Using a `RegExp` instance enables more granular control,- such as making the matching case sensitive.-- **`requestTemplate`**: [`RequestOptions`](/docs/typedefs/request-options) - Options for the new [`Request`](/docs/api/request) instances created- for matching URLs by the [`utils.enqueueLinks()`](/docs/api/utils#enqueuelinks) function.-------<a name="matches"></a>--## `pseudoUrl.matches(url)`--**Returns**: `boolean` - Returns `true` if given URL matches pseudo-URL.--Determines whether a URL matches this pseudo-URL pattern.--**Params**--- **`url`**: `string` - URL to be matched.-------<a name="createrequest"></a>--## `pseudoUrl.createRequest(urlOrProps)`--**Returns**: [`Request`](/docs/api/request)--Creates a Request object from a provided `requestTemplate` and a given URL or an object that specifies \$[`Request`](/docs/api/request) properties. In-case of a collision the properties will override the template, except for `userData`, which will be merged together, with the `userData` property-having preference over the template. This enables dynamic overriding of the template.--**Params**--- **`urlOrProps`**: `string` | `Object`-----diff --git a/docs/api/PuppeteerCrawler.md b/docs/api/PuppeteerCrawler.mddeleted file mode 100644index 8d9faa281..000000000--- a/docs/api/PuppeteerCrawler.md+++ /dev/null@@ -1,101 +0,0 @@-----id: puppeteer-crawler-title: PuppeteerCrawler------<a name="puppeteercrawler"></a>--Provides a simple framework for parallel crawling of web pages using headless Chrome with [Puppeteer](https://github.com/GoogleChrome/puppeteer). The-URLs to crawl are fed either from a static list of URLs or from a dynamic queue of URLs enabling recursive crawling of websites.--Since `PuppeteerCrawler` uses headless Chrome to download web pages and extract data, it is useful for crawling of websites that require to execute-JavaScript. If the target website doesn't need JavaScript, consider using [`CheerioCrawler`](/docs/api/cheerio-crawler), which downloads the pages-using raw HTTP requests and is about 10x faster.--The source URLs are represented using [`Request`](/docs/api/request) objects that are fed from [`RequestList`](/docs/api/request-list) or-[`RequestQueue`](/docs/api/request-queue) instances provided by the-[`PuppeteerCrawlerOptions.requestList`](/docs/typedefs/puppeteer-crawler-options#requestlist) or-[`PuppeteerCrawlerOptions.requestQueue`](/docs/typedefs/puppeteer-crawler-options#requestqueue) constructor options, respectively.--If both [`PuppeteerCrawlerOptions.requestList`](/docs/typedefs/puppeteer-crawler-options#requestlist) and-[`PuppeteerCrawlerOptions.requestQueue`](/docs/typedefs/puppeteer-crawler-options#requestqueue) are used, the instance first processes URLs from the-[`RequestList`](/docs/api/request-list) and automatically enqueues all of them to [`RequestQueue`](/docs/api/request-queue) before it starts their-processing. This ensures that a single URL is not crawled multiple times.--The crawler finishes when there are no more [`Request`](/docs/api/request) objects to crawl.--`PuppeteerCrawler` opens a new Chrome page (i.e. tab) for each [`Request`](/docs/api/request) object to crawl and then calls the function provided by-user as the [`PuppeteerCrawlerOptions.handlePageFunction`](/docs/typedefs/puppeteer-crawler-options#handlepagefunction) option.--New pages are only opened when there is enough free CPU and memory available, using the functionality provided by the-[`AutoscaledPool`](/docs/api/autoscaled-pool) class. All [`AutoscaledPool`](/docs/api/autoscaled-pool) configuration options can be passed to the-[`PuppeteerCrawlerOptions.autoscaledPoolOptions`](/docs/typedefs/puppeteer-crawler-options#autoscaledpooloptions) parameter of the `PuppeteerCrawler`-constructor. For user convenience, the `minConcurrency` and `maxConcurrency` [`AutoscaledPoolOptions`](/docs/typedefs/autoscaled-pool-options) are-available directly in the `PuppeteerCrawler` constructor.--Note that the pool of Puppeteer instances is internally managed by the [`PuppeteerPool`](/docs/api/puppeteer-pool) class. Many constructor options-such as [`PuppeteerPoolOptions.maxOpenPagesPerInstance`](/docs/typedefs/puppeteer-pool-options#maxopenpagesperinstance) or-[`PuppeteerPoolOptions.launchPuppeteerFunction`](/docs/typedefs/puppeteer-pool-options#launchpuppeteerfunction) are passed directly to the-[`PuppeteerPool`](/docs/api/puppeteer-pool) constructor.--**Example usage:**--```javascript-const crawler = new Apify.PuppeteerCrawler({- requestList,- handlePageFunction: async ({ page, request }) => {- // This function is called to extract data from a single web page- // 'page' is an instance of Puppeteer.Page with page.goto(request.url) already called- // 'request' is an instance of Request class with information about the page to load- await Apify.pushData({- title: await page.title(),- url: request.url,- succeeded: true,- });- },- handleFailedRequestFunction: async ({ request }) => {- // This function is called when the crawling of a request failed too many times- await Apify.pushData({- url: request.url,- succeeded: false,- errors: request.errorMessages,- });- },-});--await crawler.run();-```--## Properties--### `autoscaledPool`--**Type**: [`AutoscaledPool`](/docs/api/autoscaled-pool)--A reference to the underlying [`AutoscaledPool`](/docs/api/autoscaled-pool) class that manages the concurrency of the crawler. Note that this property-is only initialized after calling the [`PuppeteerCrawler.run()`](/docs/api/puppeteer-crawler#run) function. You can use it to change the concurrency-settings on the fly, to pause the crawler by calling [`AutoscaledPool.pause()`](/docs/api/autoscaled-pool#pause) or to abort it by calling-[`AutoscaledPool.abort()`](/docs/api/autoscaled-pool#abort).-------<a name="puppeteercrawler"></a>--## `new PuppeteerCrawler(options)`--**Params**--- **`options`**: [`PuppeteerCrawlerOptions`](/docs/typedefs/puppeteer-crawler-options) - All `PuppeteerCrawler` parameters are passed via an options- object.-------<a name="run"></a>--## `puppeteerCrawler.run()`--**Returns**: `Promise<void>`--Runs the crawler. Returns promise that gets resolved once all the requests got processed.-----diff --git a/docs/api/PuppeteerPool.md b/docs/api/PuppeteerPool.mddeleted file mode 100644index 9b3395461..000000000--- a/docs/api/PuppeteerPool.md+++ /dev/null@@ -1,122 +0,0 @@-----id: puppeteer-pool-title: PuppeteerPool------<a name="puppeteerpool"></a>--Manages a pool of Chrome browser instances controlled using [Puppeteer](https://github.com/GoogleChrome/puppeteer).--`PuppeteerPool` reuses Chrome instances and tabs using specific browser rotation and retirement policies. This is useful in order to facilitate-rotation of proxies, cookies or other settings in order to prevent detection of your web scraping bot, access web pages from various countries etc.--Additionally, the reuse of browser instances instances speeds up crawling, and the retirement of instances helps mitigate effects of memory leaks in-Chrome.--`PuppeteerPool` is internally used by the [`PuppeteerCrawler`](/docs/api/puppeteer-crawler) class.--**Example usage:**--```javascript-const puppeteerPool = new PuppeteerPool({- launchPuppeteerFunction: () => {- // Use a new proxy with a new IP address for each new Chrome instance- return Apify.launchPuppeteer({- useApifyProxy: true,- apifyProxySession: Math.random(),- });- },-});--const page1 = await puppeteerPool.newPage();-const page2 = await puppeteerPool.newPage();-const page3 = await puppeteerPool.newPage();--// ... do something with the pages ...--// Close all browsers.-await puppeteerPool.destroy();-```-------<a name="puppeteerpool"></a>--## `new PuppeteerPool([options])`--**Params**--- **`[options]`**: [`PuppeteerPoolOptions`](/docs/typedefs/puppeteer-pool-options) - All `PuppeteerPool` parameters are passed via an options- object.-------<a name="newpage"></a>--## `puppeteerPool.newPage()`--**Returns**: `Promise<Page>`--Produces a new page instance either by reusing an idle page that currently isn't processing any request or by spawning a new page (new browser tab) in-one of the available browsers when no idle pages are available.--To spawn a new browser tab for each page, set the `reusePages` constructor option to false.-------<a name="destroy"></a>--## `puppeteerPool.destroy()`--**Returns**: `Promise<void>`--Closes all open browsers.-------<a name="retire"></a>--## `puppeteerPool.retire(browser)`--**Returns**: `Promise<void>`--Manually retires a Puppeteer [`Browser`](https://pptr.dev/#?product=Puppeteer&show=api-class-browser) instance from the pool. The browser will-continue to process open pages so that they may gracefully finish. This is unlike `browser.close()` which will forcibly terminate the browser and all-open pages will be closed.--**Params**--- **`browser`**: `Browser`-------<a name="recyclepage"></a>--## `puppeteerPool.recyclePage(page)`--**Returns**: `Promise<void>`--Closes the page, unless the `reuseTabs` option is set to true. Then it would only flag the page for a future reuse, without actually closing it.--NOTE: LiveView snapshotting is tied to this function. When `useLiveView` option is set to true, a snapshot of the page will be taken just before-closing the page or flagging it for reuse.--**Params**--- **`page`**: `Page`-------<a name="serveliveviewsnapshot"></a>--## `puppeteerPool.serveLiveViewSnapshot(page)`--**Returns**: `Promise<void>`--Tells the connected LiveViewServer to serve a snapshot when available.--**Params**--- **`page`**: `Page`-----diff --git a/docs/api/Request.md b/docs/api/Request.mddeleted file mode 100644index a8f6a582b..000000000--- a/docs/api/Request.md+++ /dev/null@@ -1,162 +0,0 @@-----id: request-title: Request------<a name="request"></a>--Represents a URL to be crawled, optionally including HTTP method, headers, payload and other metadata. The `Request` object also stores information-about errors that occurred during processing of the request.--Each `Request` instance has the `uniqueKey` property, which can be either specified manually in the constructor or generated automatically from the-URL. Two requests with the same `uniqueKey` are considered as pointing to the same web resource. This behavior applies to all Apify SDK classes, such-as [`RequestList`](/docs/api/request-list), [`RequestQueue`](/docs/api/request-queue) or [`PuppeteerCrawler`](/docs/api/puppeteer-crawler).--Example use:--```javascript-const request = new Apify.Request({- url: 'http://www.example.com',- headers: { Accept: 'application/json' },-});--...--request.userData.foo = 'bar';-request.pushErrorMessage(new Error('Request failed!'));--...--const foo = request.userData.foo;-```--## Properties--### `id`--**Type**: `string`--Request ID-------### `url`--**Type**: `string`--URL of the web page to crawl.-------### `loadedUrl`--**Type**: `string`--An actually loaded URL after redirects, if present. HTTP redirects are guaranteed to be included.--When using [`PuppeteerCrawler`](/docs/api/puppeteer-crawler), meta tag and JavaScript redirects may, or may not be included, depending on their-nature. This generally means that redirects, which happen immediately will most likely be included, but delayed redirects will not.-------### `uniqueKey`--**Type**: `string`--A unique key identifying the request. Two requests with the same `uniqueKey` are considered as pointing to the same URL.-------### `method`--**Type**: `string`--HTTP method, e.g. `GET` or `POST`.-------### `payload`--**Type**: `string` | `Buffer`--HTTP request payload, e.g. for POST requests.-------### `noRetry`--**Type**: `boolean`--The `true` value indicates that the request will not be automatically retried on error.-------### `retryCount`--**Type**: `number`--Indicates the number of times the crawling of the request has been retried on error.-------### `errorMessages`--**Type**: `Array<string>`--An array of error messages from request processing.-------### `headers`--**Type**: `Object`--Object with HTTP headers. Key is header name, value is the value.-------### `userData`--**Type**: `object`--Custom user data assigned to the request.-------### `handledAt`--**Type**: `Date`--Indicates the time when the request has been processed. Is `null` if the request has not been crawled yet.-------<a name="request"></a>--## `new Request(options)`--**Params**--- **`options`**: [`RequestOptions`](/docs/typedefs/request-options) - `Request` parameters including the URL, HTTP method and headers, and others.-------<a name="pusherrormessage"></a>--## `request.pushErrorMessage(errorOrMessage, [options])`--Stores information about an error that occurred during processing of this request.--You should always use Error instances when throwing errors in JavaScript.--Nevertheless, to improve the debugging experience when using third party libraries that may not always throw an Error instance, the function performs-a type inspection of the passed argument and attempts to extract as much information as possible, since just throwing a bad type error makes any-debugging rather difficult.--**Params**--- **`errorOrMessage`**: `Error` | `string` - Error object or error message to be stored in the request.-- **`[options]`**: `Object`- - **`[.omitStack]`**: `boolean` <code> = false</code> - Only push the error message without stack trace when true.-----diff --git a/docs/api/RequestList.md b/docs/api/RequestList.mddeleted file mode 100644index 0ceca0ef2..000000000--- a/docs/api/RequestList.md+++ /dev/null@@ -1,191 +0,0 @@-----id: request-list-title: RequestList------<a name="requestlist"></a>--Represents a static list of URLs to crawl. The URLs can be provided either in code or parsed from a text file hosted on the web.--Each URL is represented using an instance of the [`Request`](/docs/api/request) class. The list can only contain unique URLs. More precisely, it can-only contain `Request` instances with distinct `uniqueKey` properties. By default, `uniqueKey` is generated from the URL, but it can also be-overridden. To add a single URL to the list multiple times, corresponding [`Request`](/docs/api/request) objects will need to have different-`uniqueKey` properties. You can use the `keepDuplicateUrls` option to do this for you when initializing the `RequestList` from sources.--Once you create an instance of `RequestList`, you need to call the [`RequestList.initialize()`](/docs/api/request-list#initialize) function before the-instance can be used. After that, no more URLs can be added to the list.--`RequestList` is used by [`BasicCrawler`](/docs/api/basic-crawler), [`CheerioCrawler`](/docs/api/cheerio-crawler) and-[`PuppeteerCrawler`](/docs/api/puppeteer-crawler) as a source of URLs to crawl. Unlike [`RequestQueue`](/docs/api/request-queue), `RequestList` is-static but it can contain even millions of URLs.--`RequestList` has an internal state where it stores information about which requests were already handled, which are in progress and which were-reclaimed. The state may be automatically persisted to the default [`KeyValueStore`](/docs/api/key-value-store) by setting the `persistStateKey`-option so that if the Node.js process is restarted, the crawling can continue where it left off. The automated persisting is launched upon receiving-the `persistState` event that is periodically emitted by [`Apify.events`](/docs/api/apify#events).--The internal state is closely tied to the provided sources (URLs). If the sources change on actor restart, the state will become corrupted and-`RequestList` will raise an exception. This typically happens when the sources is a list of URLs downloaded from the web. In such case, use the-`persistRequestsKey` option in conjunction with `persistStateKey`, to make the `RequestList` store the initial sources to the default key-value store-and load them after restart, which will prevent any issues that a live list of URLs might cause.--**Basic usage:**--```javascript-// Use a helper function to simplify request list initialization.-// State and sources are automatically persisted.-const requestList = await Apify.openRequestList('my-request-list', [- 'http://www.example.com/page-1',- { url: 'http://www.example.com/page-2', method: 'POST', userData: { foo: 'bar' } },- { requestsFromUrl: 'http://www.example.com/my-url-list.txt', userData: { isFromUrl: true } },-]);-```--**Advanced usage:**--```javascript-// Use the constructor to get more control over the initialization.-const requestList = new Apify.RequestList({- sources: [- // Separate requests- { url: 'http://www.example.com/page-1', method: 'GET', headers: { ... } },- { url: 'http://www.example.com/page-2', userData: { foo: 'bar' }},-- // Bulk load of URLs from file `http://www.example.com/my-url-list.txt`- // Note that all URLs must start with http:// or https://- { requestsFromUrl: 'http://www.example.com/my-url-list.txt', userData: { isFromUrl: true } },- ],-- // Persist only state in cases where the original sources are immutable to improve performance.- persistStateKey: 'my-state',-});--await requestList.initialize();-```-------<a name="exports.requestlist"></a>--## `new RequestList(options)`--**Params**--- **`options`**: [`RequestListOptions`](/docs/typedefs/request-list-options) - All `RequestList` configuration options-------<a name="initialize"></a>--## `requestList.initialize()`--**Returns**: `Promise<void>`--Loads all remote sources of URLs and potentially starts periodic state persistence. This function must be called before you can start using the-instance in a meaningful way.-------<a name="persiststate"></a>--## `requestList.persistState()`--**Returns**: `Promise<void>`--Persists the current state of the `RequestList` into the default [`KeyValueStore`](/docs/api/key-value-store). The state is persisted automatically in-regular intervals, but calling this method manually is useful in cases where you want to have the most current state available after you pause or stop-fetching its requests. For example after you pause or abort a crawl. Or just before a server migration.-------<a name="getstate"></a>--## `requestList.getState()`--**Returns**: [`RequestListState`](/docs/typedefs/request-list-state)--Returns an object representing the internal state of the `RequestList` instance. Note that the object's fields can change in future releases.-------<a name="isempty"></a>--## `requestList.isEmpty()`--**Returns**: `Promise<Boolean>`--Resolves to `true` if the next call to [`RequestList.fetchNextRequest()`](/docs/api/request-list#fetchnextrequest) function would return `null`,-otherwise it resolves to `false`. Note that even if the list is empty, there might be some pending requests currently being processed.-------<a name="isfinished"></a>--## `requestList.isFinished()`--**Returns**: `Promise<Boolean>`--Returns `true` if all requests were already handled and there are no more left.-------<a name="fetchnextrequest"></a>--## `requestList.fetchNextRequest()`--**Returns**: [`Promise<(Request|null)>`](/docs/api/request)--Gets the next [`Request`](/docs/api/request) to process. First, the function gets a request previously reclaimed using the-[`RequestList.reclaimRequest()`](/docs/api/request-list#reclaimrequest) function, if there is any. Otherwise it gets the next request from sources.--The function's `Promise` resolves to `null` if there are no more requests to process.-------<a name="markrequesthandled"></a>--## `requestList.markRequestHandled(request)`--**Returns**: `Promise<void>`--Marks request as handled after successful processing.--**Params**--- **`request`**: [`Request`](/docs/api/request)-------<a name="reclaimrequest"></a>--## `requestList.reclaimRequest(request)`--**Returns**: `Promise<void>`--Reclaims request to the list if its processing failed. The request will become available in the next `this.fetchNextRequest()`.--**Params**--- **`request`**: [`Request`](/docs/api/request)-------<a name="length"></a>--## `requestList.length()`--**Returns**: `number`--Returns the total number of unique requests present in the `RequestList`.-------<a name="handledcount"></a>--## `requestList.handledCount()`--**Returns**: `number`--Returns number of handled requests.-----diff --git a/docs/api/RequestQueue.md b/docs/api/RequestQueue.mddeleted file mode 100644index 8615c5043..000000000--- a/docs/api/RequestQueue.md+++ /dev/null@@ -1,246 +0,0 @@-----id: request-queue-title: RequestQueue------<a name="requestqueue"></a>--Represents a queue of URLs to crawl, which is used for deep crawling of websites where you start with several URLs and then recursively follow links-to other pages. The data structure supports both breadth-first and depth-first crawling orders.--Each URL is represented using an instance of the [`Request`](/docs/api/request) class. The queue can only contain unique URLs. More precisely, it can-only contain [`Request`](/docs/api/request) instances with distinct `uniqueKey` properties. By default, `uniqueKey` is generated from the URL, but it-can also be overridden. To add a single URL multiple times to the queue, corresponding [`Request`](/docs/api/request) objects will need to have-different `uniqueKey` properties.--Do not instantiate this class directly, use the [`Apify.openRequestQueue()`](/docs/api/apify#openrequestqueue) function instead.--`RequestQueue` is used by [`BasicCrawler`](/docs/api/basic-crawler), [`CheerioCrawler`](/docs/api/cheerio-crawler) and-[`PuppeteerCrawler`](/docs/api/puppeteer-crawler) as a source of URLs to crawl. Unlike [`RequestList`](/docs/api/request-list), `RequestQueue`-supports dynamic adding and removing of requests. On the other hand, the queue is not optimized for operations that add or remove a large number of-URLs in a batch.--`RequestQueue` stores its data either on local disk or in the Apify Cloud, depending on whether the `APIFY_LOCAL_STORAGE_DIR` or `APIFY_TOKEN`-environment variable is set.--If the `APIFY_LOCAL_STORAGE_DIR` environment variable is set, the queue data is stored in that local directory as follows:--```-{APIFY_LOCAL_STORAGE_DIR}/request_queues/{QUEUE_ID}/{STATE}/{NUMBER}.json-```--Note that `{QUEUE_ID}` is the name or ID of the request queue. The default queue has ID: `default`, unless you override it by setting the-`APIFY_DEFAULT_REQUEST_QUEUE_ID` environment variable. Each request in the queue is stored as a separate JSON file, where `{STATE}` is either-`handled` or `pending`, and `{NUMBER}` is an integer indicating the position of the request in the queue.--If the `APIFY_TOKEN` environment variable is set but `APIFY_LOCAL_STORAGE_DIR` not, the data is stored in the-[Apify Request Queue](https://docs.apify.com/storage/request-queue) cloud storage. Note that you can force usage of the cloud storage also by passing-the `forceCloud` option to [`Apify.openRequestQueue()`](/docs/api/apify#openrequestqueue) function, even if the `APIFY_LOCAL_STORAGE_DIR` variable is-set.--**Example usage:**--```javascript-// Open the default request queue associated with the actor run-const queue = await Apify.openRequestQueue();--// Open a named request queue-const queueWithName = await Apify.openRequestQueue('some-name');--// Enqueue few requests-await queue.addRequest({ url: 'http://example.com/aaa' });-await queue.addRequest({ url: 'http://example.com/bbb' });-await queue.addRequest({ url: 'http://example.com/foo/bar' }, { forefront: true });--// Get requests from queue-const request1 = await queue.fetchNextRequest();-const request2 = await queue.fetchNextRequest();-const request3 = await queue.fetchNextRequest();--// Mark a request as handled-await queue.markRequestHandled(request1);--// If processing of a request fails then reclaim it back to the queue, so that it's crawled again-await queue.reclaimRequest(request2);-```-------<a name="exports.requestqueue"></a>--## `new RequestQueue(queueId, [queueName], [clientKey])`--**Params**--- **`queueId`**: `string`-- **`[queueName]`**: `string`-- **`[clientKey]`**: `string`-------<a name="addrequest"></a>--## `requestQueue.addRequest(request, [options])`--**Returns**: [`Promise<QueueOperationInfo>`](/docs/typedefs/queue-operation-info)--Adds a request to the queue.--If a request with the same `uniqueKey` property is already present in the queue, it will not be updated. You can find out whether this happened from-the resulting [`QueueOperationInfo`](/docs/typedefs/queue-operation-info) object.--To add multiple requests to the queue by extracting links from a webpage, see the [`utils.enqueueLinks()`](/docs/api/utils#enqueuelinks) helper-function.--**Params**--- **`request`**: [`Request`](/docs/api/request) | [`RequestOptions`](/docs/typedefs/request-options) - [`Request`](/docs/api/request) object or- vanilla object with request data. Note that the function sets the `uniqueKey` and `id` fields to the passed object.-- **`[options]`**: `Object`- - **`[.forefront]`**: `boolean` <code> = false</code> - If `true`, the request will be added to the foremost position in the queue.-------<a name="getrequest"></a>--## `requestQueue.getRequest(requestId)`--**Returns**: [`Promise<(Request|null)>`](/docs/api/request) - Returns the request object, or `null` if it was not found.--Gets the request from the queue specified by ID.--**Params**--- **`requestId`**: `string` - ID of the request.-------<a name="fetchnextrequest"></a>--## `requestQueue.fetchNextRequest()`--**Returns**: [`Promise<(Request|null)>`](/docs/api/request) - Returns the request object or `null` if there are no more pending requests.--Returns a next request in the queue to be processed, or `null` if there are no more pending requests.--Once you successfully finish processing of the request, you need to call-[`RequestQueue.markRequestHandled()`](/docs/api/request-queue#markrequesthandled) to mark the request as handled in the queue. If there was some error-in processing the request, call [`RequestQueue.reclaimRequest()`](/docs/api/request-queue#reclaimrequest) instead, so that the queue will give the-request to some other consumer in another call to the `fetchNextRequest` function.--Note that the `null` return value doesn't mean the queue processing finished, it means there are currently no pending requests. To check whether all-requests in queue were finished, use [`RequestQueue.isFinished()`](/docs/api/request-queue#isfinished) instead.-------<a name="markrequesthandled"></a>--## `requestQueue.markRequestHandled(request)`--**Returns**: [`Promise<QueueOperationInfo>`](/docs/typedefs/queue-operation-info)--Marks a request that was previously returned by the [`RequestQueue.fetchNextRequest()`](/docs/api/request-queue#fetchnextrequest) function as handled-after successful processing. Handled requests will never again be returned by the `fetchNextRequest` function.--**Params**--- **`request`**: [`Request`](/docs/api/request)-------<a name="reclaimrequest"></a>--## `requestQueue.reclaimRequest(request, [options])`--**Returns**: [`Promise<QueueOperationInfo>`](/docs/typedefs/queue-operation-info)--Reclaims a failed request back to the queue, so that it can be returned for processed later again by another call to-[`RequestQueue.fetchNextRequest()`](/docs/api/request-queue#fetchnextrequest). The request record in the queue is updated using the provided `request`-parameter. For example, this lets you store the number of retries or error messages for the request.--**Params**--- **`request`**: [`Request`](/docs/api/request)-- **`[options]`**: `Object` - **`[.forefront]`**: `boolean` <code> = false</code> - If `true` then the request it placed to the beginning of the- queue, so that it's returned in the next call to [`RequestQueue.fetchNextRequest()`](/docs/api/request-queue#fetchnextrequest). By default, it's- put to the end of the queue.-------<a name="isempty"></a>--## `requestQueue.isEmpty()`--**Returns**: `Promise<boolean>`--Resolves to `true` if the next call to [`RequestQueue.fetchNextRequest()`](/docs/api/request-queue#fetchnextrequest) would return `null`, otherwise it-resolves to `false`. Note that even if the queue is empty, there might be some pending requests currently being processed. If you need to ensure that-there is no activity in the queue, use [`RequestQueue.isFinished()`](/docs/api/request-queue#isfinished).-------<a name="isfinished"></a>--## `requestQueue.isFinished()`--**Returns**: `Promise<boolean>`--Resolves to `true` if all requests were already handled and there are no more left. Due to the nature of distributed storage used by the queue, the-function might occasionally return a false negative, but it will never return a false positive.-------<a name="drop"></a>--## `requestQueue.drop()`--**Returns**: `Promise<void>`--Removes the queue either from the Apify Cloud storage or from the local directory, depending on the mode of operation.-------<a name="handledcount"></a>--## `requestQueue.handledCount()`--**Returns**: `Promise<number>`--Returns the number of handled requests.--This function is just a convenient shortcut for:--```javascript-const { handledRequestCount } = await queue.getInfo();-```-------<a name="getinfo"></a>--## `requestQueue.getInfo()`--**Returns**: `Promise<object>`--Returns an object containing general information about the request queue.--The function returns the same object as the Apify API Client's [getQueue](https://docs.apify.com/api/apify-client-js/latest#ApifyClient-requestQueues)-function, which in turn calls the [Get request queue](https://apify.com/docs/api/v2#/reference/request-queues/queue/get-request-queue) API endpoint.--**Example:**--```-{- id: "WkzbQMuFYuamGv3YF",- name: "my-queue",- userId: "wRsJZtadYvn4mBZmm",- createdAt: new Date("2015-12-12T07:34:14.202Z"),- modifiedAt: new Date("2015-12-13T08:36:13.202Z"),- accessedAt: new Date("2015-12-14T08:36:13.202Z"),- totalRequestCount: 25,- handledRequestCount: 5,- pendingRequestCount: 20,-}-```-----diff --git a/docs/api/Session.md b/docs/api/Session.mddeleted file mode 100644index 934a3d57c..000000000--- a/docs/api/Session.md+++ /dev/null@@ -1,184 +0,0 @@-----id: session-title: Session------<a name="session"></a>--Sessions are used to store information such as cookies and can be used for generating fingerprints and proxy sessions. You can imagine each session as-a specific user, with its own cookies, IP (via proxy) and potentially a unique browser fingerprint. Session internal state can be enriched with custom-user data for example some authorization tokens and specific headers in general.-------<a name="exports.session"></a>--## `new Session(options)`--Session configuration.--**Params**--- **`options`**: [`SessionOptions`](/docs/typedefs/session-options)-------<a name="isblocked"></a>--## `session.isBlocked()`--**Returns**: `boolean`--indicates whether the session is blocked. Session is blocked once it reaches the `maxErrorScore`.-------<a name="isexpired"></a>--## `session.isExpired()`--**Returns**: `boolean`--Indicates whether the session is expired. Session expiration is determined by the `maxAgeSecs`. Once the session is older than-`createdAt + maxAgeSecs` the session is considered expired.-------<a name="ismaxusagecountreached"></a>--## `session.isMaxUsageCountReached()`--**Returns**: `boolean`--Indicates whether the session is used maximum number of times. Session maximum usage count can be changed by `maxUsageCount` parameter.-------<a name="isusable"></a>--## `session.isUsable()`--**Returns**: `boolean`--Indicates whether the session can be used for next requests. Session is usable when it is not expired, not blocked and the maximum usage count has not-be reached.-------<a name="markgood"></a>--## `session.markGood()`--This method should be called after a successful session usage. It increases `usageCount` and potentially lowers the `errorScore` by the-`errorScoreDecrement`.-------<a name="getstate"></a>--## `session.getState()`--**Returns**: [`SessionState`](/docs/typedefs/session-state) - represents session internal state.--Gets session state for persistence in KeyValueStore.-------<a name="retire"></a>--## `session.retire()`--Marks session as blocked and emits event on the `SessionPool` This method should be used if the session usage was unsuccessful and you are sure that-it is because of the session configuration and not any external matters. For example when server returns 403 status code. If the session does not work-due to some external factors as server error such as 5XX you probably want to use `markBad` method.-------<a name="markbad"></a>--## `session.markBad()`--Increases usage and error count. Should be used when the session has been used unsuccessfully. For example because of timeouts.-------<a name="retireonblockedstatuscodes"></a>--## `session.retireOnBlockedStatusCodes(statusCode, [blockedStatusCodes])`--**Returns**: `boolean` - whether the session was retired.--With certain status codes: `401`, `403` or `429` we can be certain that the target website is blocking us. This function helps to do this conveniently-by retiring the session when such code is received. Optionally the default status codes can be extended in the second parameter.--**Params**--- **`statusCode`**: `number` - HTTP status code-- **`[blockedStatusCodes]`**: `Array<number>` - Custom HTTP status codes that means blocking on particular website.-------<a name="setcookiesfromresponse"></a>--## `session.setCookiesFromResponse(response)`--Saves cookies from an HTTP response to be used with the session. It expects an object with a `headers` property that's either an `Object` (typical-Node.js responses) or a `Function` (Puppeteer Response).--It then parses and saves the cookies from the `set-cookie` header, if available.--**Params**--- **`response`**: `PuppeteerResponse` | `IncomingMessage`-------<a name="setpuppeteercookies"></a>--## `session.setPuppeteerCookies(cookies, url)`--Saves an array with cookie objects to be used with the session. The objects should be in the format that-[Puppeteer uses](https://pptr.dev/#?product=Puppeteer&version=v2.0.0&show=api-pagecookiesurls), but you can also use this function to set cookies-manually:--```-[- { name: 'cookie1', value: 'my-cookie' },- { name: 'cookie2', value: 'your-cookie' }-]-```--**Params**--- **`cookies`**: `Array<PuppeteerCookie>`-- **`url`**: `string`-------<a name="getpuppeteercookies"></a>--## `session.getPuppeteerCookies(url)`--**Returns**: `Array<PuppeteerCookie>`--Returns cookies in a format compatible with puppeteer and ready to be used with `page.setCookie`.--**Params**--- **`url`**: `string` - website url. Only cookies stored for this url will be returned-------<a name="getcookiestring"></a>--## `session.getCookieString(url)`--**Returns**: `string` - - represents `Cookie` header.--Returns cookies saved with the session in the typical key1=value1; key2=value2 format, ready to be used in a cookie header or elsewhere.--**Params**--- **`url`**: `string`-----diff --git a/docs/api/SessionPool.md b/docs/api/SessionPool.mddeleted file mode 100644index 3b453727d..000000000--- a/docs/api/SessionPool.md+++ /dev/null@@ -1,132 +0,0 @@-----id: session-pool-title: SessionPool------<a name="sessionpool"></a>--Handles the sessions rotation, creation and persistence. Creates a pool of [`Session`](/docs/api/session) instances, that are randomly rotated. When-some session is marked as blocked. It is removed and new one is created instead. Learn more in the-[`Session management guide`](/docs/guides/session-management).--Session pool is by default persisted in default [`KeyValueStore`](/docs/api/key-value-store). If you want to have one pool for all runs you have to-specify [`SessionPoolOptions.persistStateKeyValueStoreId`](/docs/typedefs/session-pool-options#persiststatekeyvaluestoreid).--**Example usage:**--```javascript-const sessionPool = new SessionPool({- maxPoolSize: 25,- sessionOptions: {- maxAgeSecs: 10,- maxUsageCount: 150, // for example when you know that the site blocks after 150 requests.- },- persistStateKeyValueStoreId: 'my-key-value-store-for-sessions',- persistStateKey: 'my-session-pool',-});--// Now you have to initialize the `SessionPool`.-// If you already have a persisted state in the selected `KeyValueState`.-// The Session pool is recreated, otherwise it creates a new one.-// It also attaches listener to `Apify.events` so it is persisted periodically and not after every change.-await sessionPool.initialize();--// Get random session from the pool-const session1 = await sessionPool.getSession();-const session2 = await sessionPool.getSession();-const session3 = await sessionPool.getSession();--// Now you can mark the session either failed of successful--// Marks session as bad after unsuccessful usage -> it increases error count (soft retire)-session1.markBad();--// Marks as successful.-session2.markGood();--// Retires session -> session is removed from the pool-session3.retire();-```-------<a name="exports.sessionpool"></a>--## `new SessionPool([options])`--Session pool configuration.--**Params**--- **`[options]`**: [`SessionPoolOptions`](/docs/typedefs/session-pool-options) - All `SessionPool` configuration options.-------<a name="usablesessionscount"></a>--## `sessionPool.usableSessionsCount`--**Returns**: `number`--Gets count of usable sessions in the pool.-------<a name="retiredsessionscount"></a>--## `sessionPool.retiredSessionsCount`--**Returns**: `number`--Gets count of retired sessions in the pool.-------<a name="initialize"></a>--## `sessionPool.initialize()`--**Returns**: `Promise<void>`--Starts periodic state persistence and potentially loads SessionPool state from [`KeyValueStore`](/docs/api/key-value-store). This function must be-called before you can start using the instance in a meaningful way.-------<a name="getsession"></a>--## `sessionPool.getSession()`--**Returns**: [`Promise<Session>`](/docs/api/session)--Gets session. If there is space for new session, it creates and return new session. If the session pool is full, it picks a session from the pool, If-the picked session is usable it is returned, otherwise it creates and returns a new one.-------<a name="getstate"></a>--## `sessionPool.getState()`--Returns an object representing the internal state of the `SessionPool` instance. Note that the object's fields can change in future releases.-------<a name="persiststate"></a>--## `sessionPool.persistState()`--**Returns**: `Promise<void>`--Persists the current state of the `SessionPool` into the default [`KeyValueStore`](/docs/api/key-value-store). The state is persisted automatically in-regular intervals.-------<a name="teardown"></a>--## `sessionPool.teardown()`--Removes listener from `persistState` event. This function should be called after you are done with using the `SessionPool` instance.-----diff --git a/docs/api/Snapshotter.md b/docs/api/Snapshotter.mddeleted file mode 100644index a76aacf75..000000000--- a/docs/api/Snapshotter.md+++ /dev/null@@ -1,116 +0,0 @@-----id: snapshotter-title: Snapshotter------<a name="snapshotter"></a>--Creates snapshots of system resources at given intervals and marks the resource as either overloaded or not during the last interval. Keeps a history-of the snapshots. It tracks the following resources: Memory, EventLoop, API and CPU. The class is used by the-[`AutoscaledPool`](/docs/api/autoscaled-pool) class.--When running on the Apify platform, the CPU and memory statistics are provided by the platform, as collected from the running Docker container. When-running locally, `Snapshotter` makes its own statistics by querying the OS.--CPU becomes overloaded locally when its current use exceeds the `maxUsedCpuRatio` option or when Apify platform marks it as overloaded.--Memory becomes overloaded if its current use exceeds the `maxUsedMemoryRatio` option. It's computed using the total memory available to the container-when running on the Apify platform and a quarter of total system memory when running locally. Max total memory when running locally may be overridden-by using the `APIFY_MEMORY_MBYTES` environment variable.--Event loop becomes overloaded if it slows down by more than the `maxBlockedMillis` option.--Client becomes overloaded when rate limit errors (429 - Too Many Requests), typically received from the request queue, exceed the set limit within the-set interval.-------<a name="snapshotter"></a>--## `new Snapshotter([options])`--**Params**--- **`[options]`**: [`SnapshotterOptions`](/docs/typedefs/snapshotter-options) - All `Snapshotter` configuration options.-------<a name="start"></a>--## `snapshotter.start()`--**Returns**: `Promise<void>`--Starts capturing snapshots at configured intervals.-------<a name="stop"></a>--## `snapshotter.stop()`--**Returns**: `Promise<void>`--Stops all resource capturing.-------<a name="getmemorysample"></a>--## `snapshotter.getMemorySample([sampleDurationMillis])`--**Returns**: `Array<*>`--Returns a sample of latest memory snapshots, with the size of the sample defined by the sampleDurationMillis parameter. If omitted, it returns a full-snapshot history.--**Params**--- **`[sampleDurationMillis]`**: `number`-------<a name="geteventloopsample"></a>--## `snapshotter.getEventLoopSample([sampleDurationMillis])`--**Returns**: `Array<*>`--Returns a sample of latest event loop snapshots, with the size of the sample defined by the sampleDurationMillis parameter. If omitted, it returns a-full snapshot history.--**Params**--- **`[sampleDurationMillis]`**: `number`-------<a name="getcpusample"></a>--## `snapshotter.getCpuSample([sampleDurationMillis])`--**Returns**: `Array<*>`--Returns a sample of latest CPU snapshots, with the size of the sample defined by the sampleDurationMillis parameter. If omitted, it returns a full-snapshot history.--**Params**--- **`[sampleDurationMillis]`**: `number`-------<a name="getclientsample"></a>--## `snapshotter.getClientSample(sampleDurationMillis)`--**Returns**: `Array<*>`--Returns a sample of latest Client snapshots, with the size of the sample defined by the sampleDurationMillis parameter. If omitted, it returns a full-snapshot history.--**Params**--- **`sampleDurationMillis`**: `number`-----diff --git a/docs/api/SystemStatus.md b/docs/api/SystemStatus.mddeleted file mode 100644index e35db5b4c..000000000--- a/docs/api/SystemStatus.md+++ /dev/null@@ -1,75 +0,0 @@-----id: system-status-title: SystemStatus------<a name="systemstatus"></a>--Provides a simple interface to reading system status from a [`Snapshotter`](/docs/api/snapshotter) instance. It only exposes two functions-[`SystemStatus.getCurrentStatus()`](/docs/api/system-status#getcurrentstatus) and-[`SystemStatus.getHistoricalStatus()`](/docs/api/system-status#gethistoricalstatus). The system status is calculated using a weighted average of-overloaded messages in the snapshots, with the weights being the time intervals between the snapshots. Each resource is calculated separately and the-system is overloaded whenever at least one resource is overloaded. The class is used by the [`AutoscaledPool`](/docs/api/autoscaled-pool) class.--[`SystemStatus.getCurrentStatus()`](/docs/api/system-status#getcurrentstatus) returns a boolean that represents the current status of the system. The-length of the current timeframe in seconds is configurable by the `currentHistorySecs` option and represents the max age of snapshots to be considered-for the calculation.--[`SystemStatus.getHistoricalStatus()`](/docs/api/system-status#gethistoricalstatus) returns a boolean that represents the long-term status of the-system. It considers the full snapshot history available in the [`Snapshotter`](/docs/api/snapshotter) instance.-------<a name="systemstatus"></a>--## `new SystemStatus([options])`--**Params**--- **`[options]`**: [`SystemStatusOptions`](/docs/typedefs/system-status-options) - All `SystemStatus` configuration options.-------<a name="getcurrentstatus"></a>--## `systemStatus.getCurrentStatus()`--**Returns**: [`SystemInfo`](/docs/typedefs/system-info)--Returns an [`SystemInfo`](/docs/typedefs/system-info) object with the following structure:--```javascript-{- isSystemIdle: Boolean,- memInfo: Object,- eventLoopInfo: Object,- cpuInfo: Object-}-```--Where the `isSystemIdle` property is set to `false` if the system has been overloaded in the last `options.currentHistorySecs` seconds, and `true`-otherwise.-------<a name="gethistoricalstatus"></a>--## `systemStatus.getHistoricalStatus()`--**Returns**: [`SystemInfo`](/docs/typedefs/system-info)--Returns an [`SystemInfo`](/docs/typedefs/system-info) object with the following structure:--```javascript-{- isSystemIdle: Boolean,- memInfo: Object,- eventLoopInfo: Object,- cpuInfo: Object-}-```--Where the `isSystemIdle` property is set to `false` if the system has been overloaded in the full history of the-[`Snapshotter`](/docs/api/snapshotter) (which is configurable in the [`Snapshotter`](/docs/api/snapshotter)) and `true` otherwise.-----diff --git a/docs/api/log.md b/docs/api/log.mddeleted file mode 100644index 99140c3ab..000000000--- a/docs/api/log.md+++ /dev/null@@ -1,198 +0,0 @@-----id: log-title: utils.log------<a name="log"></a>--The log instance enables level aware logging of messages and we advise to use it instead of `console.log()` and its aliases in most development-scenarios.--A very useful use case for `log` is using `log.debug` liberally throughout the codebase to get useful logging messages only when appropriate log level-is set and keeping the console tidy in production environments.--The available logging levels are, in this order: `DEBUG`, `INFO`, `WARNING`, `ERROR`, `OFF` and can be referenced from the `log.LEVELS` constant, such-as `log.LEVELS.ERROR`.--To log messages to the system console, use the `log.level(message)` invocation, such as `log.debug('this is a debug message')`.--To prevent writing of messages above a certain log level to the console, simply set the appropriate level. The default log level is `INFO`, which-means that `DEBUG` messages will not be printed, unless enabled.--**Example:**--```-const Apify = require('apify');-const { log } = Apify.utils;--log.info('Information message', { someData: 123 }); // prints message-log.debug('Debug message', { debugData: 'hello' }); // doesn't print anything--log.setLevel(log.LEVELS.DEBUG);-log.debug('Debug message'); // prints message--log.setLevel(log.LEVELS.ERROR);-log.debug('Debug message'); // doesn't print anything-log.info('Info message'); // doesn't print anything--log.error('Error message', { errorDetails: 'This is bad!' }); // prints message-try {- throw new Error('Not good!');-} catch (e) {- log.exception(e, 'Exception occurred', { errorDetails: 'This is really bad!' }); // prints message-}--log.setOptions({ prefix: 'My actor' });-log.info('I am running!'); // prints "My actor: I am running"--const childLog = log.child({ prefix: 'Crawler' });-log.info('I am crawling!'); // prints "My actor:Crawler: I am crawling"-```--Another very useful way of setting the log level is by setting the `APIFY_LOG_LEVEL` environment variable, such as `APIFY_LOG_LEVEL=DEBUG`. This way,-no code changes are necessary to turn on your debug messages and start debugging right away.-------<a name="levels"></a>--## `log.LEVELS`--Map of available log levels that's useful for easy setting of appropriate log levels. Each log level is represented internally by a number. Eg.-`log.LEVELS.DEBUG === 5`.-------<a name="setlevel"></a>--## `log.setLevel(level)`--Sets the log level to the given value, preventing messages from less important log levels from being printed to the console. Use in conjunction with-the `log.LEVELS` constants such as--```-log.setLevel(log.LEVELS.DEBUG);-```--Default log level is INFO.--**Params**--- **`level`**: `number`-------<a name="getlevel"></a>--## `log.getLevel()`--Returns the currently selected logging level. This is useful for checking whether a message will actually be printed to the console before one-actually performs a resource intensive operation to construct the message, such as querying a DB for some metadata that need to be added. If the log-level is not high enough at the moment, it doesn't make sense to execute the query.-------<a name="setoptions"></a>--## `log.setOptions(options)`--Configures logger.--**Params**--- **`options`**: [`LoggerOptions`](/docs/typedefs/logger-options)-------<a name="child"></a>--## `log.child([options])`--Creates a new instance of logger that inherits settings from a parent logger.--**Params**--- **`[options]`**: [`LoggerOptions`](/docs/typedefs/logger-options) - Supports the same options as the `setOptions()` method.-------<a name="getoptions"></a>--## `log.getOptions()`--**Returns**: [`LoggerOptions`](/docs/typedefs/logger-options)--Returns the logger configuration.-------<a name="debug"></a>--## `log.debug(message, [data])`--Logs a `DEBUG` message. By default, it will not be written to the console. To see `DEBUG` messages in the console, set the log level to `DEBUG` either-using the `log.setLevel(log.LEVELS.DEBUG)` method or using the environment variable `APIFY_LOG_LEVEL=DEBUG`. Data are stringified and appended to the-message.--**Params**--- **`message`**: `string`-- **`[data]`**: `Object`-------<a name="info"></a>--## `log.info(message, [data])`--Logs an `INFO` message. `INFO` is the default log level so info messages will be always logged, unless the log level is changed. Data are stringified-and appended to the message.--**Params**--- **`message`**: `string`-- **`[data]`**: `Object`-------<a name="warning"></a>--## `log.warning(message, [data])`--Logs a `WARNING` level message. Data are stringified and appended to the message.--**Params**--- **`message`**: `string`-- **`[data]`**: `Object`-------<a name="error"></a>--## `log.error(message, [data])`--Logs an `ERROR` message. Use this method to log error messages that are not directly connected to an exception. For logging exceptions, use the-`log.exception` method.--**Params**--- **`message`**: `string`-- **`[data]`**: `Object`-------<a name="exception"></a>--## `log.exception(exception, [message], [data])`--Logs an `ERROR` level message with a nicely formatted exception. Note that the exception is the first parameter here and an additional message is only-optional.--**Params**--- **`exception`**: `Error`-- **`[message]`**: `string`-- **`[data]`**: `Object`-----diff --git a/docs/api/puppeteer.md b/docs/api/puppeteer.mddeleted file mode 100644index 6cc8962dc..000000000--- a/docs/api/puppeteer.md+++ /dev/null@@ -1,449 +0,0 @@-----id: puppeteer-title: utils.puppeteer------<a name="puppeteer"></a>--A namespace that contains various utilities for [Puppeteer](https://github.com/GoogleChrome/puppeteer) - the headless Chrome Node API.--**Example usage:**--```javascript-const Apify = require('apify');-const { puppeteer } = Apify.utils;--// Open https://www.example.com in Puppeteer-const browser = await Apify.launchPuppeteer();-const page = await browser.newPage();-await page.goto('https://www.example.com');--// Inject jQuery into a page-await puppeteer.injectJQuery(page);-```-------<a name="addinterceptrequesthandler"></a>--## `puppeteer.addInterceptRequestHandler`--**Returns**: `Promise<void>`--Adds request interception handler in similar to `page.on('request', handler);` but in addition to that supports multiple parallel handlers.--All the handlers are executed sequentially in the order as they were added. Each of the handlers must call one of `request.continue()`,-`request.abort()` and `request.respond()`. In addition to that any of the handlers may modify the request object (method, postData, headers) by-passing its overrides to `request.continue()`. If multiple handlers modify same property then the last one wins. Headers are merged separately so you-can override only a value of specific header.--If one the handlers calls `request.abort()` or `request.respond()` then request is not propagated further to any of the remaining handlers.--**Example usage:**--```javascript-// Replace images with placeholder.-await addInterceptRequestHandler(page, request => {- if (request.resourceType() === 'image') {- return request.respond({- statusCode: 200,- contentType: 'image/jpeg',- body: placeholderImageBuffer,- });- }- return request.continue();-});--// Abort all the scripts.-await addInterceptRequestHandler(page, request => {- if (request.resourceType() === 'script') return request.abort();- return request.continue();-});--// Change requests to post.-await addInterceptRequestHandler(page, request => {- return request.continue({- method: 'POST',- });-});--await page.goto('http://example.com');-```--**Params**--- **`page`**: `Page` - Puppeteer [`Page`](https://pptr.dev/#?product=Puppeteer&show=api-class-page) object.-- **`handler`**: [`InterceptHandler`](/docs/typedefs/intercept-handler) - Request interception handler.-------<a name="removeinterceptrequesthandler"></a>--## `puppeteer.removeInterceptRequestHandler`--**Returns**: `Promise<void>`--Removes request interception handler for given page.--**Params**--- **`page`**: `Page` - Puppeteer [`Page`](https://pptr.dev/#?product=Puppeteer&show=api-class-page) object.-- **`handler`**: [`InterceptHandler`](/docs/typedefs/intercept-handler) - Request interception handler.-------<a name="gotoextended"></a>--## `puppeteer.gotoExtended`--**Returns**: `Promise<(Response|null)>`--Extended version of Puppeteer's `page.goto()` allowing to perform requests with HTTP method other than GET, with custom headers and POST payload. URL,-method, headers and payload are taken from request parameter that must be an instance of Apify.Request class.--_NOTE:_ In recent versions of Puppeteer using requests other than GET, overriding headers and adding payloads disables browser cache which degrades-performance.--**Params**--- **`page`**: `Page` - Puppeteer [`Page`](https://pptr.dev/#?product=Puppeteer&show=api-class-page) object.-- **`request`**: [`Request`](/docs/api/request)-- **`gotoOptions`**: `DirectNavigationOptions` - Custom options for `page.goto()`.-------<a name="infinitescroll"></a>--## `puppeteer.infiniteScroll`--**Returns**: `Promise<void>`--Scrolls to the bottom of a page, or until it times out. Loads dynamic content when it hits the bottom of a page, and then continues scrolling.--**Params**--- **`page`**: `Page` - Puppeteer [`Page`](https://pptr.dev/#?product=Puppeteer&show=api-class-page) object.-- **`[options]`**: `Object`- - **`[.timeoutSecs]`**: `number` <code> = 0</code> - How many seconds to scroll for. If 0, will scroll until bottom of page.- - **`[.waitForSecs]`**: `number` <code> = 4</code> - How many seconds to wait for no new content to load before exit.-------<a name="savesnapshot"></a>--## `puppeteer.saveSnapshot`--**Returns**: `Promise<void>`--Saves a full screenshot and HTML of the current page into a Key-Value store.--**Params**--- **`page`**: `Page` - Puppeteer [`Page`](https://pptr.dev/#?product=Puppeteer&show=api-class-page) object.-- **`[options]`**: `Object`- - **`[.key]`**: `string` <code> = "SNAPSHOT"</code> - Key under which the screenshot and HTML will be saved. `.jpg` will be appended- for screenshot and `.html` for HTML.- - **`[.screenshotQuality]`**: `number` <code> = 50</code> - The quality of the image, between 0-100. Higher quality images have bigger size and- require more storage.- - **`[.saveScreenshot]`**: `boolean` <code> = true</code> - If true, it will save a full screenshot of the current page as a record with `key`- appended by `.jpg`.- - **`[.saveHtml]`**: `boolean` <code> = true</code> - If true, it will save a full HTML of the current page as a record with `key` appended by- `.html`.- - **`[.keyValueStoreName]`**: `string` <code> = null</code> - Name or id of the Key-Value store where snapshot is saved. By default it is saved- to default Key-Value store.-------<a name="enqueuelinksbyclickingelements"></a>--## `puppeteer.enqueueLinksByClickingElements(options)`--**Returns**: [`Promise<Array<QueueOperationInfo>>`](/docs/typedefs/queue-operation-info) - Promise that resolves to an array of-[`QueueOperationInfo`](/docs/typedefs/queue-operation-info) objects.--The function finds elements matching a specific CSS selector in a Puppeteer page, clicks all those elements using a mouse move and a left mouse button-click and intercepts all the navigation requests that are subsequently produced by the page. The intercepted requests, including their methods,-headers and payloads are then enqueued to a provided [`RequestQueue`](/docs/api/request-queue). This is useful to crawl JavaScript heavy pages where-links are not available in `href` elements, but rather navigations are triggered in click handlers. If you're looking to find URLs in `href`-attributes of the page, see [`utils.enqueueLinks()`](/docs/api/utils#enqueuelinks).--Optionally, the function allows you to filter the target links' URLs using an array of [`PseudoUrl`](/docs/api/pseudo-url) objects and override-settings of the enqueued [`Request`](/docs/api/request) objects.--**IMPORTANT**: To be able to do this, this function uses various mutations on the page, such as changing the Z-index of elements being clicked and-their visibility. Therefore, it is recommended to only use this function as the last operation in the page.--**USING HEADFUL BROWSER**: When using a headful browser, this function will only be able to click elements in the focused tab, effectively limiting-concurrency to 1. In headless mode, full concurrency can be achieved.--**PERFORMANCE**: Clicking elements with a mouse and intercepting requests is not a low level operation that takes nanoseconds. It's not very CPU-intensive, but it takes time. We strongly recommend limiting the scope of the clicking as much as possible by using a specific selector that targets-only the elements that you assume or know will produce a navigation. You can certainly click everything by using the `*` selector, but be prepared to-wait minutes to get results on a large and complex page.--**Example usage**--```javascript-const Apify = require('apify');--const browser = await Apify.launchPuppeteer();-const page = await browser.goto('https://www.example.com');-const requestQueue = await Apify.openRequestQueue();--await Apify.utils.enqueueLinksByClickingElements({- page,- requestQueue,- selector: 'a.product-detail',- pseudoUrls: [- 'https://www.example.com/handbags/[.*]'- 'https://www.example.com/purses/[.*]'- ],-});-```--**Params**--- **`options`**: `Object` - All `enqueueLinksByClickingElements()` parameters are passed via an options object with the following keys:-- - **`.page`**: `Page` - Puppeteer [`Page`](https://pptr.dev/#?product=Puppeteer&show=api-class-page) object.- - **`.requestQueue`**: [`RequestQueue`](/docs/api/request-queue) - A request queue to which the URLs will be enqueued.- - **`.selector`**: `string` - A CSS selector matching elements to be clicked on. Unlike in- [`utils.enqueueLinks()`](/docs/api/utils#enqueuelinks), there is no default value. This is to prevent suboptimal use of this function by using- it too broadly.- - **`[.pseudoUrls]`**: `Array<(string|RegExp|Object)>` - An array of [`PseudoUrl`](/docs/api/pseudo-url)s matching the URLs to be enqueued, or- an array of strings or RegExps or plain Objects from which the [`PseudoUrl`](/docs/api/pseudo-url)s can be constructed.-- The plain objects must include at least the `purl` property, which holds the pseudo-URL string or RegExp. All remaining keys will be used as the- `requestTemplate` argument of the [`PseudoUrl`](/docs/api/pseudo-url) constructor, which lets you specify special properties for the enqueued- [`Request`](/docs/api/request) objects.-- If `pseudoUrls` is an empty array, `null` or `undefined`, then the function enqueues all links found on the page.-- - **`[.transformRequestFunction]`**: [`RequestTransform`](/docs/typedefs/request-transform) - Just before a new [`Request`](/docs/api/request)- is constructed and enqueued to the [`RequestQueue`](/docs/api/request-queue), this function can be used to remove it or modify its contents- such as `userData`, `payload` or, most importantly `uniqueKey`. This is useful when you need to enqueue multiple `Requests` to the queue that- share the same URL, but differ in methods or payloads, or to dynamically update or create `userData`.-- For example: by adding `useExtendedUniqueKey: true` to the `request` object, `uniqueKey` will be computed from a combination of `url`, `method`- and `payload` which enables crawling of websites that navigate using form submits (POST requests).-- **Example:**-- ```javascript- {- transformRequestFunction: request => {- request.userData.foo = 'bar';- request.useExtendedUniqueKey = true;- return request;- };- }- ```-- - **`[.waitForPageIdleSecs]`**: `number` <code> = 1</code> - Clicking in the page triggers various asynchronous operations that lead to new URLs- being shown by the browser. It could be a simple JavaScript redirect or opening of a new tab in the browser. These events often happen only- some time after the actual click. Requests typically take milliseconds while new tabs open in hundreds of milliseconds.-- To be able to capture all those events, the `enqueueLinksByClickingElements()` function repeatedly waits for the `waitForPageIdleSecs`. By- repeatedly we mean that whenever a relevant event is triggered, the timer is restarted. As long as new events keep coming, the function will not- return, unless the below `maxWaitForPageIdleSecs` timeout is reached.-- You may want to reduce this for example when you're sure that your clicks do not open new tabs, or increase when you're not getting all the- expected URLs.-- - **`[.maxWaitForPageIdleSecs]`**: `number` <code> = 5</code> - This is the maximum period for which the function will keep tracking events,- even if more events keep coming. Its purpose is to prevent a deadlock in the page by periodic events, often unrelated to the clicking itself.- See `waitForPageIdleSecs` above for an explanation.-------<a name="injectfile"></a>--## `puppeteer.injectFile(page, filePath, [options])`--**Returns**: `Promise<*>`--Injects a JavaScript file into a Puppeteer page. Unlike Puppeteer's `addScriptTag` function, this function works on pages with arbitrary Cross-Origin-Resource Sharing (CORS) policies.--File contents are cached for up to 10 files to limit file system access.--**Params**--- **`page`**: `Page` - Puppeteer [`Page`](https://pptr.dev/#?product=Puppeteer&show=api-class-page) object.-- **`filePath`**: `string` - File path-- **`[options]`**: `Object`- - **`[.surviveNavigations]`**: `boolean` - Enables the injected script to survive page navigations and reloads without need to be re-injected- manually. This does not mean, however, that internal state will be preserved. Just that it will be automatically re-injected on each- navigation before any other scripts get the chance to execute.-------<a name="injectjquery"></a>--## `puppeteer.injectJQuery(page)`--**Returns**: `Promise<*>`--Injects the [jQuery](https://jquery.com/) library into a Puppeteer page. jQuery is often useful for various web scraping and crawling tasks. For-example, it can help extract text from HTML elements using CSS selectors.--Beware that the injected jQuery object will be set to the `window.$` variable and thus it might cause conflicts with other libraries included by the-page that use the same variable name (e.g. another version of jQuery). This can affect functionality of page's scripts.--The injected jQuery will survive page navigations and reloads.--**Example usage:**--```javascript-await Apify.utils.puppeteer.injectJQuery(page);-const title = await page.evaluate(() => {- return $('head title').text();-});-```--Note that `injectJQuery()` does not affect the Puppeteer's [`page.$()`](https://pptr.dev/#?product=Puppeteer&show=api-pageselector) function in any-way.--**Params**--- **`page`**: `Page` - Puppeteer [`Page`](https://pptr.dev/#?product=Puppeteer&show=api-class-page) object.-------<a name="injectunderscore"></a>--## `puppeteer.injectUnderscore(page)`--**Returns**: `Promise<*>`--Injects the [Underscore](https://underscorejs.org/) library into a Puppeteer page.--Beware that the injected Underscore object will be set to the `window._` variable and thus it might cause conflicts with libraries included by the-page that use the same variable name. This can affect functionality of page's scripts.--The injected Underscore will survive page navigations and reloads.--**Example usage:**--```javascript-await Apify.utils.puppeteer.injectUnderscore(page);-const escapedHtml = await page.evaluate(() => {- return _.escape('<h1>Hello</h1>');-});-```--**Params**--- **`page`**: `Page` - Puppeteer [Page](https://github.com/GoogleChrome/puppeteer/blob/master/docs/api.md#class-page) object.-------<a name="blockrequests"></a>--## `puppeteer.blockRequests(page, [options])`--**Returns**: `Promise<void>`--Forces the Puppeteer browser tab to block loading URLs that match a provided pattern. This is useful to speed up crawling of websites, since it-reduces the amount of data that needs to be downloaded from the web, but it may break some websites or unexpectedly prevent loading of resources.--By default, the function will block all URLs including the following patterns:--```json-[".css", ".jpg", ".jpeg", ".png", ".svg", ".gif", ".woff", ".pdf", ".zip"]-```--If you want to extend this list further, use the `extraUrlPatterns` option, which will keep blocking the default patterns, as well as add your custom-ones. If you would like to block only specific patterns, use the `urlPatterns` option, which will override the defaults and block only URLs with your-custom patterns.--This function does not use Puppeteer's request interception and therefore does not interfere with browser cache. It's also faster than blocking-requests using interception, because the blocking happens directly in the browser without the round-trip to Node.js, but it does not provide the extra-benefits of request interception.--The function will never block main document loads and their respective redirects.--**Example usage**--```javascript-const Apify = require('apify');--const browser = await Apify.launchPuppeteer();-const page = await browser.newPage();--// Block all requests to URLs that include `adsbygoogle.js` and also all defaults.-await Apify.utils.puppeteer.blockRequests(page, {- extraUrlPatterns: ['adsbygoogle.js'],-});--await page.goto('https://cnn.com');-```--**Params**--- **`page`**: `Page` - Puppeteer [`Page`](https://pptr.dev/#?product=Puppeteer&show=api-class-page) object.-- **`[options]`**: `Object`- - **`[.urlPatterns]`**: `Array<string>` - The patterns of URLs to block from being loaded by the browser. Only `*` can be used as a wildcard. It- is also automatically added to the beginning and end of the pattern. This limitation is enforced by the DevTools protocol. `.png` is the same- as `*.png*`.- - **`[.extraUrlPatterns]`**: `Array<string>` - If you just want to append to the default blocked patterns, use this property.-------<a name="cacheresponses"></a>--## ~~`puppeteer.cacheResponses(page, cache, responseUrlRules)`~~--**_Deprecated_**--**Returns**: `Promise<void>`--_NOTE:_ In recent versions of Puppeteer using this function entirely disables browser cache which resolves in sub-optimal performance. Until this-resolves, we suggest just relying on the in-browser cache unless absolutely necessary.--Enables caching of intercepted responses into a provided object. Automatically enables request interception in Puppeteer. _IMPORTANT_: Caching-responses stores them to memory, so too loose rules could cause memory leaks for longer running crawlers. This issue should be resolved or atleast-mitigated in future iterations of this feature.--**Params**--- **`page`**: `Page` - Puppeteer [`Page`](https://pptr.dev/#?product=Puppeteer&show=api-class-page) object.-- **`cache`**: `Object` - Object in which responses are stored-- **`responseUrlRules`**: `Array<(string|RegExp)>` - List of rules that are used to check if the response should be cached. String rules are- compared as page.url().includes(rule) while RegExp rules are evaluated as rule.test(page.url()).-------<a name="compilescript"></a>--## `puppeteer.compileScript(scriptString, context)`--**Returns**: `function` - `async ({ page, request }) => { scriptString }`--Compiles a Puppeteer script into an async function that may be executed at any time by providing it with the following object:--```-{- page: Page,- request: Request,-}-```--Where `page` is a Puppeteer [`Page`](https://pptr.dev/#?product=Puppeteer&show=api-class-page) and `request` is a [`Request`](/docs/api/request).--The function is compiled by using the `scriptString` parameter as the function's body, so any limitations to function bodies apply. Return value of-the compiled function is the return value of the function body = the `scriptString` parameter.--As a security measure, no globals such as `process` or `require` are accessible from within the function body. Note that the function does not provide-a safe sandbox and even though globals are not easily accessible, malicious code may still execute in the main process via prototype manipulation.-Therefore you should only use this function to execute sanitized or safe code.--Custom context may also be provided using the `context` parameter. To improve security, make sure to only pass the really necessary objects to the-context. Preferably making secured copies beforehand.--**Params**--- **`scriptString`**: `string`-- **`context`**: `Object`-----diff --git a/docs/api/social.md b/docs/api/social.mddeleted file mode 100644index c99d1ac58..000000000--- a/docs/api/social.md+++ /dev/null@@ -1,417 +0,0 @@-----id: social-title: utils.social------<a name="social"></a>--A namespace that contains various utilities to help you extract social handles from text, URLs and and HTML documents.--**Example usage:**--```javascript-const Apify = require('apify');--const emails = Apify.utils.social.emailsFromText('[email protected] [email protected]');-```-------<a name="linkedin_regex"></a>--## `social.LINKEDIN_REGEX`--Regular expression to exactly match a single LinkedIn profile URL. It has the following form: `/^...$/i` and matches URLs such as:--```-https://www.linkedin.com/in/alan-turing-en.linkedin.com/in/alan-turing-linkedin.com/in/alan-turing-```--The regular expression does NOT match URLs with additional subdirectories or query parameters, such as:--```-https://www.linkedin.com/in/linus-torvalds/latest-activity-```--Example usage:--```-if (Apify.utils.social.LINKEDIN_REGEX.test('https://www.linkedin.com/in/alan-turing')) {- console.log('Match!');-}-```-------<a name="linkedin_regex_global"></a>--## `social.LINKEDIN_REGEX_GLOBAL`--Regular expression to find multiple LinkedIn profile URLs in a text or HTML. It has the following form: `/.../ig` and matches URLs such as:--```-https://www.linkedin.com/in/alan-turing-en.linkedin.com/in/alan-turing-linkedin.com/in/alan-turing-```--If the profile URL contains subdirectories or query parameters, the regular expression extracts just the base part of the profile URL. For example,-from text such as:--```-https://www.linkedin.com/in/linus-torvalds/latest-activity-```--the expression extracts just the following base URL:--```-https://www.linkedin.com/in/linus-torvalds-```--Example usage:--```-const matches = text.match(Apify.utils.social.LINKEDIN_REGEX_GLOBAL);-if (matches) console.log(`${matches.length} LinkedIn profiles found!`);-```-------<a name="instagram_regex"></a>--## `social.INSTAGRAM_REGEX`--Regular expression to exactly match a single Instagram profile URL. It has the following form: `/^...$/i` and matches URLs such as:--```-https://www.instagram.com/old_prague-www.instagram.com/old_prague/-instagr.am/old_prague-```--The regular expression does NOT match URLs with additional subdirectories or query parameters, such as:--```-https://www.instagram.com/cristiano/followers-```--Example usage:--```-if (Apify.utils.social.INSTAGRAM_REGEX.test('https://www.instagram.com/old_prague')) {- console.log('Match!');-}-```-------<a name="instagram_regex_global"></a>--## `social.INSTAGRAM_REGEX_GLOBAL`--Regular expression to find multiple Instagram profile URLs in a text or HTML. It has the following form: `/.../ig` and matches URLs such as:--```-https://www.instagram.com/old_prague-www.instagram.com/old_prague/-instagr.am/old_prague-```--If the profile URL contains subdirectories or query parameters, the regular expression extracts just the base part of the profile URL. For example,-from text such as:--```-https://www.instagram.com/cristiano/followers-```--the expression extracts just the following base URL:--```-https://www.instagram.com/cristiano-```--Example usage:--```-const matches = text.match(Apify.utils.social.INSTAGRAM_REGEX_GLOBAL);-if (matches) console.log(`${matches.length} Instagram profiles found!`);-```-------<a name="twitter_regex"></a>--## `social.TWITTER_REGEX`--Regular expression to exactly match a single Twitter profile URL. It has the following form: `/^...$/i` and matches URLs such as:--```-https://www.twitter.com/apify-twitter.com/apify-```--The regular expression does NOT match URLs with additional subdirectories or query parameters, such as:--```-https://www.twitter.com/realdonaldtrump/following-```--Example usage:--```-if (Apify.utils.social.TWITTER_REGEX.test('https://www.twitter.com/apify')) {- console.log('Match!');-}-```-------<a name="twitter_regex_global"></a>--## `social.TWITTER_REGEX_GLOBAL`--Regular expression to find multiple Twitter profile URLs in a text or HTML. It has the following form: `/.../ig` and matches URLs such as:--```-https://www.twitter.com/apify-twitter.com/apify-```--If the profile URL contains subdirectories or query parameters, the regular expression extracts just the base part of the profile URL. For example,-from text such as:--```-https://www.twitter.com/realdonaldtrump/following-```--the expression extracts only the following base URL:--```-https://www.twitter.com/realdonaldtrump-```--Example usage:--```-const matches = text.match(Apify.utils.social.TWITTER_REGEX_STRING);-if (matches) console.log(`${matches.length} Twitter profiles found!`);-```-------<a name="facebook_regex"></a>--## `social.FACEBOOK_REGEX`--Regular expression to exactly match a single Facebook profile URL. It has the following form: `/^...$/i` and matches URLs such as:--```-https://www.facebook.com/apifytech-facebook.com/apifytech-fb.com/apifytech-https://www.facebook.com/profile.php?id=123456789-```--The regular expression does NOT match URLs with additional subdirectories or query parameters, such as:--```-https://www.facebook.com/apifytech/photos-```--Example usage:--```-if (Apify.utils.social.FACEBOOK_REGEX.test('https://www.facebook.com/apifytech')) {- console.log('Match!');-}-```-------<a name="facebook_regex_global"></a>--## `social.FACEBOOK_REGEX_GLOBAL`--Regular expression to find multiple Facebook profile URLs in a text or HTML. It has the following form: `/.../ig` and matches URLs such as:--```-https://www.facebook.com/apifytech-facebook.com/apifytech-fb.com/apifytech-```--If the profile URL contains subdirectories or query parameters, the regular expression extracts just the base part of the profile URL. For example,-from text such as:--```-https://www.facebook.com/apifytech/photos-```--the expression extracts only the following base URL:--```-https://www.facebook.com/apifytech-```--Example usage:--```-const matches = text.match(Apify.utils.social.FACEBOOK_REGEX_GLOBAL);-if (matches) console.log(`${matches.length} Facebook profiles found!`);-```-------<a name="youtube_regex"></a>--## `social.YOUTUBE_REGEX`--Regular expression to exactly match a single Youtube video URL. It has the following form: `/^...$/i` and matches URLs such as:--```-https://www.youtube.com/watch?v=kM7YfhfkiEE-https://youtu.be/kM7YfhfkiEE-```--Example usage:--```-if (Apify.utils.social.YOUTUBE_REGEX.test('https://www.youtube.com/watch?v=kM7YfhfkiEE')) {- console.log('Match!');-}-```-------<a name="youtube_regex_global"></a>--## `social.YOUTUBE_REGEX_GLOBAL`--Regular expression to find multiple Youtube video URLs in a text or HTML. It has the following form: `/.../ig` and matches URLs such as:--```-https://www.youtube.com/watch?v=kM7YfhfkiEE-https://youtu.be/kM7YfhfkiEE-```--Example usage:--```-const matches = text.match(Apify.utils.social.YOUTUBE_REGEX_GLOBAL);-if (matches) console.log(`${matches.length} Youtube videos found!`);-```-------<a name="email_regex"></a>--## `social.EMAIL_REGEX`--Regular expression to exactly match a single email address. It has the following form: `/^...$/i`.-------<a name="email_regex_global"></a>--## `social.EMAIL_REGEX_GLOBAL`--Regular expression to find multiple email addresses in a text. It has the following form: `/.../ig`.-------<a name="emailsfromtext"></a>--## `social.emailsFromText(text)`--**Returns**: `Array<string>` - Array of emails addresses found. If no emails are found, the function returns an empty array.--The function extracts email addresses from a plain text. Note that the function preserves the order of emails and keep duplicates.--**Params**--- **`text`**: `string` - Text to search in.-------<a name="emailsfromurls"></a>--## `social.emailsFromUrls(urls)`--**Returns**: `Array<string>` - Array of emails addresses found. If no emails are found, the function returns an empty array.--The function extracts email addresses from a list of URLs. Basically it looks for all `mailto:` URLs and returns valid email addresses from them. Note-that the function preserves the order of emails and keep duplicates.--**Params**--- **`urls`**: `Array<string>` - Array of URLs.-------<a name="phonesfromtext"></a>--## `social.phonesFromText(text)`--**Returns**: `Array<string>` - Array of phone numbers found. If no phone numbers are found, the function returns an empty array.--The function attempts to extract phone numbers from a text. Please note that the results might not be accurate, since phone numbers appear in a large-variety of formats and conventions. If you encounter some problems, please [file an issue](https://github.com/apifytech/apify-js/issues).--**Params**--- **`text`**: `string` - Text to search the phone numbers in.-------<a name="phonesfromurls"></a>--## `social.phonesFromUrls(urls)`--**Returns**: `Array<string>` - Array of phone numbers found. If no phone numbers are found, the function returns an empty array.--Finds phone number links in an array of URLs and extracts the phone numbers from them. Note that the phone number links look like `tel://123456789`,-`tel:/123456789` or `tel:123456789`.--**Params**--- **`urls`**: `Array<string>` - Array of URLs.-------<a name="parsehandlesfromhtml"></a>--## `social.parseHandlesFromHtml(html, data)`--**Returns**: [`SocialHandles`](/docs/typedefs/social-handles) - An object with the social handles.--The function attempts to extract emails, phone numbers and social profile URLs from a HTML document, specifically LinkedIn, Twitter, Instagram and-Facebook profile URLs. The function removes duplicates from the resulting arrays and sorts the items alphabetically.--Note that the `phones` field contains phone numbers extracted from the special phone links such as `[call us](tel:+1234556789)` (see-[`social.phonesFromUrls()`](/docs/api/social#phonesfromurls)) and potentially other sources with high certainty, while `phonesUncertain` contains-phone numbers extracted from the plain text, which might be very inaccurate.--**Example usage:**--```javascript-const Apify = require('apify');--const browser = await Apify.launchPuppeteer();-const page = await browser.newPage();-await page.goto('http://www.example.com');-const html = await page.content();--const result = Apify.utils.social.parseHandlesFromHtml(html);-console.log('Social handles:');-console.dir(result);-```--**Params**--- **`html`**: `string` - HTML text-- **`data`**: `Object` <code> = </code> - Optional object which will receive the `text` and `$` properties that contain text content of the HTML and- `cheerio` object, respectively. This is an optimization so that the caller doesn't need to parse the HTML document again, if needed.-----diff --git a/docs/api/utils.md b/docs/api/utils.mddeleted file mode 100644index 5f60846cd..000000000--- a/docs/api/utils.md+++ /dev/null@@ -1,264 +0,0 @@-----id: utils-title: utils------<a name="utils"></a>--A namespace that contains various utilities.--**Example usage:**--```javascript-const Apify = require('apify');--...--// Sleep 1.5 seconds-await Apify.utils.sleep(1500);-```-------<a name="url_no_commas_regex"></a>--## `utils.URL_NO_COMMAS_REGEX`--Default regular expression to match URLs in a string that may be plain text, JSON, CSV or other. It supports common URL characters and does not-support URLs containing commas or spaces. The URLs also may contain Unicode letters (not symbols).-------<a name="url_with_commas_regex"></a>--## `utils.URL_WITH_COMMAS_REGEX`--Regular expression that, in addition to the default regular expression `URL_NO_COMMAS_REGEX`, supports matching commas in URL path and query. Note,-however, that this may prevent parsing URLs from comma delimited lists, or the URLs may become malformed.-------<a name="enqueuelinks"></a>--## `utils.enqueueLinks(options)`--**Returns**: [`Promise<Array<QueueOperationInfo>>`](/docs/typedefs/queue-operation-info) - Promise that resolves to an array of-[`QueueOperationInfo`](/docs/typedefs/queue-operation-info) objects.--The function finds elements matching a specific CSS selector (HTML anchor (`<a>`) by default) either in a Puppeteer page, or in a Cheerio object-(parsed HTML), and enqueues the URLs in their `href` attributes to the provided [`RequestQueue`](/docs/api/request-queue). If you're looking to find-URLs in JavaScript heavy pages where links are not available in `href` elements, but rather navigations are triggered in click handlers see-[`puppeteer.enqueueLinksByClickingElements()`](/docs/api/puppeteer#enqueuelinksbyclickingelements).--Optionally, the function allows you to filter the target links' URLs using an array of [`PseudoUrl`](/docs/api/pseudo-url) objects and override-settings of the enqueued [`Request`](/docs/api/request) objects.--**Example usage**--```javascript-const Apify = require('apify');--const browser = await Apify.launchPuppeteer();-const page = await browser.goto('https://www.example.com');-const requestQueue = await Apify.openRequestQueue();--await Apify.utils.enqueueLinks({- page,- requestQueue,- selector: 'a.product-detail',- pseudoUrls: ['https://www.example.com/handbags/[.*]', 'https://www.example.com/purses/[.*]'],-});-```--**Params**--- **`options`**: `Object` - All `enqueueLinks()` parameters are passed via an options object with the following keys:-- - **`[.page]`**: `Page` - Puppeteer [`Page`](https://pptr.dev/#?product=Puppeteer&show=api-class-page) object. Either `page` or `$` option must- be provided.- - **`[.$]`**: `CheerioStatic` - [`Cheerio`](https://github.com/cheeriojs/cheerio) function with loaded HTML. Either `page` or `$` option must be- provided.- - **`.requestQueue`**: [`RequestQueue`](/docs/api/request-queue) - A request queue to which the URLs will be enqueued.- - **`[.selector]`**: `string` <code> = "'a'"</code> - A CSS selector matching links to be enqueued.- - **`[.baseUrl]`**: `string` - A base URL that will be used to resolve relative URLs when using Cheerio. Ignored when using Puppeteer, since the- relative URL resolution is done inside the browser automatically.- - **`[.pseudoUrls]`**: `Array<Object>` | `Array.<string>` - An array of [`PseudoUrl`](/docs/api/pseudo-url)s matching the URLs to be- enqueued, or an array of strings or RegExps or plain Objects from which the [`PseudoUrl`](/docs/api/pseudo-url)s can be constructed.-- The plain objects must include at least the `purl` property, which holds the pseudo-URL string or RegExp. All remaining keys will be used as the- `requestTemplate` argument of the [`PseudoUrl`](/docs/api/pseudo-url) constructor, which lets you specify special properties for the enqueued- [`Request`](/docs/api/request) objects.-- If `pseudoUrls` is an empty array, `null` or `undefined`, then the function enqueues all links found on the page.-- - **`[.transformRequestFunction]`**: [`RequestTransform`](/docs/typedefs/request-transform) - Just before a new [`Request`](/docs/api/request)- is constructed and enqueued to the [`RequestQueue`](/docs/api/request-queue), this function can be used to remove it or modify its contents- such as `userData`, `payload` or, most importantly `uniqueKey`. This is useful when you need to enqueue multiple `Requests` to the queue that- share the same URL, but differ in methods or payloads, or to dynamically update or create `userData`.-- For example: by adding `keepUrlFragment: true` to the `request` object, URL fragments will not be removed when `uniqueKey` is computed.-- **Example:**-- ```javascript- {- transformRequestFunction: request => {- request.userData.foo = 'bar';- request.keepUrlFragment = true;- return request;- };- }- ```-------<a name="requestasbrowser"></a>--## `utils.requestAsBrowser(options)`--**Returns**: `Promise<(IncomingMessage|Readable)>` - This will typically be a-[Node.js HTTP response stream](https://nodejs.org/api/http.html#http_class_http_incomingmessage), however, if returned from the cache it will be a-[response-like object](https://github.com/lukechilds/responselike) which behaves in the same way.--**IMPORTANT:** This function uses an insecure version of HTTP parser by default and also ignores SSL/TLS errors. This is very useful in scraping,-because it allows bypassing certain anti-scraping walls, but it also exposes some vulnerability. For other than scraping scenarios, please set-`useInsecureHttpParser: false` and `ignoreSslErrors: false`.--Sends a HTTP request that looks like a request sent by a web browser, fully emulating browser's HTTP headers.--This function is useful for web scraping of websites that send the full HTML in the first response. Thanks to this function, the target web server has-no simple way to find out the request hasn't been sent by a full web browser. Using a headless browser for such requests is an order of magnitude more-resource-intensive than this function. By default tt aborts all requests that returns 406 status codes or non-HTML content-types. You can override-this behavior by passing custom `abortFunction`.--Currently, the function sends requests the same way as Firefox web browser does. In the future, it might add support for other browsers too.--Internally, the function uses httpRequest function from the [@apify/httpRequest](https://github.com/apifytech/http-request) NPM package to perform the-request. All `options` not recognized by this function are passed to it, so see it for more details.--**Params**--- **`options`**: [`RequestAsBrowserOptions`](/docs/typedefs/request-as-browser-options) - All `requestAsBrowser` configuration options.-------<a name="isdocker"></a>--## `utils.isDocker(forceReset)`--**Returns**: `Promise<boolean>`--Returns a `Promise` that resolves to true if the code is running in a Docker container.--**Params**--- **`forceReset`**: `boolean`-------<a name="sleep"></a>--## `utils.sleep(millis)`--**Returns**: `Promise<void>`--Returns a `Promise` that resolves after a specific period of time. This is useful to implement waiting in your code, e.g. to prevent overloading of-target website or to avoid bot detection.--**Example usage:**--```-const Apify = require('apify');--...--// Sleep 1.5 seconds-await Apify.utils.sleep(1500);-```--**Params**--- **`millis`**: `number` - Period of time to sleep, in milliseconds. If not a positive number, the returned promise resolves immediately.-------<a name="downloadlistofurls"></a>--## `utils.downloadListOfUrls(options)`--**Returns**: `Promise<Array<string>>`--Returns a promise that resolves to an array of urls parsed from the resource available at the provided url. Optionally, custom regular expression and-encoding may be provided.--**Params**--- **`options`**: `Object`- - **`.url`**: `string` - URL to the file- - **`[.encoding]`**: `string` <code> = "'utf8'"</code> - The encoding of the file.- - **`[.urlRegExp]`**: `RegExp` <code> = URL_NO_COMMAS_REGEX</code> - Custom regular expression to identify the URLs in the file to extract. The- regular expression should be case-insensitive and have global flag set (i.e. `/something/gi`).-------<a name="extracturls"></a>--## `utils.extractUrls(options)`--**Returns**: `Array<string>`--Collects all URLs in an arbitrary string to an array, optionally using a custom regular expression.--**Params**--- **`options`**: `Object`- - **`.string`**: `string`- - **`[.urlRegExp]`**: `RegExp` <code> = Apify.utils.URL_NO_COMMAS_REGEX</code>-------<a name="getrandomuseragent"></a>--## `utils.getRandomUserAgent()`--**Returns**: `string`--Returns a randomly selected User-Agent header out of a list of the most common headers.-------<a name="htmltotext"></a>--## `utils.htmlToText(html)`--**Returns**: `string` - Plain text--The function converts a HTML document to a plain text.--The plain text generated by the function is similar to a text captured by pressing Ctrl+A and Ctrl+C on a page when loaded in a web browser. The-function doesn't aspire to preserve the formatting or to be perfectly correct with respect to HTML specifications. However, it attempts to generate-newlines and whitespaces in and around HTML elements to avoid merging distinct parts of text and thus enable extraction of data from the text (e.g.-phone numbers).--**Example usage**--```javascript-const text = htmlToText('<html><body>Some text</body></html>');-console.log(text);-```--Note that the function uses [cheerio](https://www.npmjs.com/package/cheerio) to parse the HTML. Optionally, to avoid duplicate parsing of HTML and-thus improve performance, you can pass an existing Cheerio object to the function instead of the HTML text. The HTML should be parsed with the-`decodeEntities` option set to `true`. For example:--```javascript-const cheerio = require('cheerio');-const html = '<html><body>Some text</body></html>';-const text = htmlToText(cheerio.load(html, { decodeEntities: true }));-```--**Params**--- **`html`**: `string` | `CheerioStatic` - HTML text or parsed HTML represented using a [cheerio](https://www.npmjs.com/package/cheerio) function.-----diff --git a/docs/examples/BasicCrawler.md b/docs/examples/BasicCrawler.mddeleted file mode 100644index 88cd6b850..000000000--- a/docs/examples/BasicCrawler.md+++ /dev/null@@ -1,59 +0,0 @@-----id: basic-crawler-title: Basic Crawler------This is the most basic example of the Apify SDK, which demonstrates some of its elementary tools, such as the-[`BasicCrawler`](/docs/api/basic-crawler) and [`RequestList`](/docs/api/request-list) classes. The script just downloads several web pages with plain-HTTP requests using the [`Apify.utils.requestAsBrowser()`](/docs/api/utils#requestasbrowser) convenience function and stores their raw HTML and URL to-the default dataset. In local configuration, the data will be stored as JSON files in `./apify_storage/datasets/default`.--To run this example on the Apify Platform, select the `Node.js 12 on Alpine Linux (apify/actor-node-basic)` base image on the source tab of your actor-configuration.--```javascript-const Apify = require('apify');--// Apify.main() function wraps the crawler logic (it is optional).-Apify.main(async () => {- // Create and initialize an instance of the RequestList class that contains- // a list of URLs to crawl. Here we use just a few hard-coded URLs.- const requestList = new Apify.RequestList({- sources: [- { url: 'http://www.google.com/' },- { url: 'http://www.example.com/' },- { url: 'http://www.bing.com/' },- { url: 'http://www.wikipedia.com/' },- ],- });- await requestList.initialize();-- // Create a BasicCrawler - the simplest crawler that enables- // users to implement the crawling logic themselves.- const crawler = new Apify.BasicCrawler({- // Let the crawler fetch URLs from our list.- requestList,-- // This function will be called for each URL to crawl.- // The 'request' option is an instance of the Request class, which contains- // information such as URL and HTTP method, as supplied by the RequestList.- handleRequestFunction: async ({ request }) => {- console.log(`Processing ${request.url}...`);-- // Fetch the page HTML- const { body } = await Apify.utils.requestAsBrowser(request);-- // Store the HTML and URL to the default dataset.- await Apify.pushData({- url: request.url,- html: body,- });- },- });-- // Run the crawler and wait for it to finish.- await crawler.run();-- console.log('Crawler finished.');-});-```diff --git a/docs/examples/CallActor.md b/docs/examples/CallActor.mddeleted file mode 100644index 06f855248..000000000--- a/docs/examples/CallActor.md+++ /dev/null@@ -1,48 +0,0 @@-----id: call-actor-title: Call Actor------This example demonstrates how to start an Apify actor using [`Apify.call()`](/docs/api/apify#call) and how to call Apify API using-[`Apify.client`](/docs/api/apify#client). The script extracts the current Bitcoin prices from [Kraken.com](https://www.kraken.com/) and sends them to-your email using the [`apify/send-mail`](https://apify.com/apify/send-mail) actor.--To make the example work, you'll need an [Apify Account](https://my.apify.com/). Go to-[Account - Integrations](https://my.apify.com/account#/integrations) page to obtain your API token and set it to the-[`APIFY_TOKEN`](/docs/guides/environment-variables#APIFY_TOKEN) environment variable, or run the script using the CLI. If you deploy this actor to the-Apify Cloud then you can set up a scheduler for early morning.--To run this example on the Apify Platform, select the `Node.js 12 + Chrome on Debian (apify/actor-node-chrome)` base image on the source tab of your-actor configuration.--```javascript-const Apify = require('apify');--Apify.main(async () => {- // Launch the web browser.- const browser = await Apify.launchPuppeteer();-- console.log('Obtaining email address...');- const user = await Apify.client.users.getUser();-- // Load Kraken.com charts and get last traded price of BTC- console.log('Extracting data from kraken.com...');- const page = await browser.newPage();- await page.goto('https://www.kraken.com/charts');- const tradedPricesHtml = await page.$eval('#ticker-top ul', el => el.outerHTML);-- // Send prices to your email. For that, you can use an actor we already- // have available on the platform under the name: apify/send-mail.- // The second parameter to the Apify.call() invocation is the actor's- // desired input. You can find the required input parameters by checking- // the actor's documentation page: https://apify.com/apify/send-mail- console.log(`Sending email to ${user.email}...`);- await Apify.call('apify/send-mail', {- to: user.email,- subject: 'Kraken.com BTC',- html: `<h1>Kraken.com BTC</h1>${tradedPricesHtml}`,- });-- console.log('Email sent. Good luck!');-});-```diff --git a/docs/examples/CheerioCrawler.md b/docs/examples/CheerioCrawler.mddeleted file mode 100644index d87f34d82..000000000--- a/docs/examples/CheerioCrawler.md+++ /dev/null@@ -1,89 +0,0 @@-----id: cheerio-crawler-title: Cheerio Crawler------This example demonstrates how to use [`CheerioCrawler`](/docs/api/cheerio-crawler) to crawl a list of URLs from an external file, load each URL using-a plain HTTP request, parse the HTML using [cheerio](https://www.npmjs.com/package/cheerio) and extract some data from it: the page title and all H1-tags.--To run this example on the Apify Platform, select the `Node.js 12 on Alpine Linux (apify/actor-node-basic)` base image on the source tab of your actor-configuration.--```javascript-const Apify = require('apify');--// Apify.utils contains various utilities, e.g. for logging.-// Here we turn off the logging of unimportant messages.-const { log } = Apify.utils;-log.setLevel(log.LEVELS.WARNING);--// A link to a list of Fortune 500 companies' websites available on GitHub.-const CSV_LINK = 'https://gist.githubusercontent.com/hrbrmstr/ae574201af3de035c684/raw/f1000.csv';--// Apify.main() function wraps the crawler logic (it is optional).-Apify.main(async () => {- // Create an instance of the RequestList class that contains a list of URLs to crawl.- // Here we download and parse the list of URLs from an external file.- const requestList = new Apify.RequestList({- sources: [{ requestsFromUrl: CSV_LINK }],- });- await requestList.initialize();-- // Create an instance of the CheerioCrawler class - a crawler- // that automatically loads the URLs and parses their HTML using the cheerio library.- const crawler = new Apify.CheerioCrawler({- // Let the crawler fetch URLs from our list.- requestList,-- // The crawler downloads and processes the web pages in parallel, with a concurrency- // automatically managed based on the available system memory and CPU (see AutoscaledPool class).- // Here we define some hard limits for the concurrency.- minConcurrency: 10,- maxConcurrency: 50,-- // On error, retry each page at most once.- maxRequestRetries: 1,-- // Increase the timeout for processing of each page.- handlePageTimeoutSecs: 60,-- // This function will be called for each URL to crawl.- // It accepts a single parameter, which is an object with the following fields:- // - request: an instance of the Request class with information such as URL and HTTP method- // - html: contains raw HTML of the page- // - $: the cheerio object containing parsed HTML- handlePageFunction: async ({ request, html, $ }) => {- console.log(`Processing ${request.url}...`);-- // Extract data from the page using cheerio.- const title = $('title').text();- const h1texts = [];- $('h1').each((index, el) => {- h1texts.push({- text: $(el).text(),- });- });-- // Store the results to the default dataset. In local configuration,- // the data will be stored as JSON files in ./apify_storage/datasets/default- await Apify.pushData({- url: request.url,- title,- h1texts,- html,- });- },-- // This function is called if the page processing failed more than maxRequestRetries+1 times.- handleFailedRequestFunction: async ({ request }) => {- console.log(`Request ${request.url} failed twice.`);- },- });-- // Run the crawler and wait for it to finish.- await crawler.run();-- console.log('Crawler finished.');-});-```diff --git a/docs/examples/Forms.md b/docs/examples/Forms.mddeleted file mode 100644index 4b56b4f60..000000000--- a/docs/examples/Forms.md+++ /dev/null@@ -1,49 +0,0 @@-----id: forms-title: Forms------This example demonstrates how to use [`PuppeteerCrawler`](/docs/api/puppeteer-crawler) to automatically fill and submit a search form to look up-repositories on [GitHub](https://news.ycombinator.com) using headless Chrome / Puppeteer. The actor first fills in the search term, repository owner,-start date and language of the repository, then submits the form and prints out the results. Finally, the results are saved either on the Apify-platform to the default [`Dataset`](/docs/api/dataset) or on the local machine as JSON files in `./apify_storage/datasets/default`.--To run this example on the Apify Platform, select the `Node.js 12 + Chrome on Debian (apify/actor-node-chrome)` base image on the source tab of your-actor configuration.--```javascript-const Apify = require('apify');--Apify.main(async () => {- // Launch the web browser.- const browser = await Apify.launchPuppeteer();-- // Create and navigate new page- console.log('Open target page');- const page = await browser.newPage();- await page.goto('https://github.com/search/advanced');-- // Fill form fields and select desired search options- console.log('Fill in search form');- await page.type('#adv_code_search input.js-advanced-search-input', 'apify-js');- await page.type('#search_from', 'apifytech');- await page.type('#search_date', '>2015');- await page.select('select#search_language', 'JavaScript');-- // Submit the form and wait for full load of next page- console.log('Submit search form');- await Promise.all([page.waitForNavigation(), page.click('#adv_code_search button[type="submit"]')]);-- // Obtain and print list of search results- const results = await page.$$eval('div.codesearch-results ul.repo-list li h3 a', nodes =>- nodes.map(node => ({- url: node.href,- name: node.innerText,- })),- );- console.log('Results:', results);-- // Store data in default dataset- await Apify.pushData(results);-});-```diff --git a/docs/examples/HelloWorld.md b/docs/examples/HelloWorld.mddeleted file mode 100644index abac63043..000000000--- a/docs/examples/HelloWorld.md+++ /dev/null@@ -1,32 +0,0 @@-----id: hello-world-title: Hello World------Run the following example to perform a recursive crawl of a website using Puppeteer.--To run this example on the Apify Platform, select the `Node.js 12 + Chrome on Debian (apify/actor-node-chrome)` base image on the source tab of your-actor configuration.--```javascript-const Apify = require('apify');--Apify.main(async () => {- const requestQueue = await Apify.openRequestQueue();- await requestQueue.addRequest({ url: 'https://www.iana.org/' });- const pseudoUrls = [new Apify.PseudoUrl('https://www.iana.org/[.*]')];-- const crawler = new Apify.PuppeteerCrawler({- requestQueue,- handlePageFunction: async ({ request, page }) => {- const title = await page.title();- console.log(`Title of ${request.url}: ${title}`);- await Apify.utils.enqueueLinks({ page, selector: 'a', pseudoUrls, requestQueue });- },- maxRequestsPerCrawl: 100,- maxConcurrency: 10,- });-- await crawler.run();-});-```diff --git a/docs/examples/PuppeteerCrawler.md b/docs/examples/PuppeteerCrawler.mddeleted file mode 100644index 49de57e68..000000000--- a/docs/examples/PuppeteerCrawler.md+++ /dev/null@@ -1,90 +0,0 @@-----id: puppeteer-crawler-title: Puppeteer Crawler------This example demonstrates how to use [`PuppeteerCrawler`](/docs/api/puppeteer-crawler) in combination with [`RequestQueue`](/docs/api/request-queue)-to recursively scrape the [Hacker News website](https://news.ycombinator.com) using headless Chrome / Puppeteer. The crawler starts with a single URL,-finds links to next pages, enqueues them and continues until no more desired links are available. The results are stored to the default dataset. In-local configuration, the results are stored as JSON files in `./apify_storage/datasets/default`--To run this example on the Apify Platform, select the `Node.js 12 + Chrome on Debian (apify/actor-node-chrome)` base image on the source tab of your-actor configuration.--```javascript-const Apify = require('apify');--Apify.main(async () => {- // Apify.openRequestQueue() is a factory to get a preconfigured RequestQueue instance.- // We add our first request to it - the initial page the crawler will visit.- const requestQueue = await Apify.openRequestQueue();- await requestQueue.addRequest({ url: 'https://news.ycombinator.com/' });-- // Create an instance of the PuppeteerCrawler class - a crawler- // that automatically loads the URLs in headless Chrome / Puppeteer.- const crawler = new Apify.PuppeteerCrawler({- requestQueue,-- // Here you can set options that are passed to the Apify.launchPuppeteer() function.- launchPuppeteerOptions: {- // For example, by adding "slowMo" you'll slow down Puppeteer operations to simplify debugging- // slowMo: 500,- },-- // Stop crawling after several pages- maxRequestsPerCrawl: 10,-- // This function will be called for each URL to crawl.- // Here you can write the Puppeteer scripts you are familiar with,- // with the exception that browsers and pages are automatically managed by the Apify SDK.- // The function accepts a single parameter, which is an object with the following fields:- // - request: an instance of the Request class with information such as URL and HTTP method- // - page: Puppeteer's Page object (see https://pptr.dev/#show=api-class-page)- handlePageFunction: async ({ request, page }) => {- console.log(`Processing ${request.url}...`);-- // A function to be evaluated by Puppeteer within the browser context.- const pageFunction = $posts => {- const data = [];-- // We're getting the title, rank and URL of each post on Hacker News.- $posts.forEach($post => {- data.push({- title: $post.querySelector('.title a').innerText,- rank: $post.querySelector('.rank').innerText,- href: $post.querySelector('.title a').href,- });- });-- return data;- };- const data = await page.$$eval('.athing', pageFunction);-- // Store the results to the default dataset.- await Apify.pushData(data);-- // Find a link to the next page and enqueue it if it exists.- const infos = await Apify.utils.enqueueLinks({- page,- requestQueue,- selector: '.morelink',- });-- if (infos.length === 0) console.log(`${request.url} is the last page!`);- },-- // This function is called if the page processing failed more than maxRequestRetries+1 times.- handleFailedRequestFunction: async ({ request }) => {- console.log(`Request ${request.url} failed too many times`);- await Apify.pushData({- '#debug': Apify.utils.createRequestDebugInfo(request),- });- },- });-- // Run the crawler and wait for it to finish.- await crawler.run();-- console.log('Crawler finished.');-});-```diff --git a/docs/examples/PuppeteerSitemap.md b/docs/examples/PuppeteerSitemap.mddeleted file mode 100644index 6805fca1b..000000000--- a/docs/examples/PuppeteerSitemap.md+++ /dev/null@@ -1,37 +0,0 @@-----id: puppeteer-sitemap-title: Puppeteer Sitemap------This example demonstrates how to use [`PuppeteerCrawler`](/docs/api/puppeteer-crawler) to crawl a list of web pages specified in a sitemap. The-crawler extracts page title and URL from each page and stores them as a record to the default dataset. In local configuration, the results are stored-as JSON files in `./apify_storage/datasets/default`--To run this example on the Apify Platform, select the `Node.js 12 + Chrome on Debian (apify/actor-node-chrome)` base image on the source tab of your-actor configuration.--```javascript-const Apify = require('apify');--Apify.main(async () => {- const requestList = new Apify.RequestList({- sources: [{ requestsFromUrl: 'https://edition.cnn.com/sitemaps/cnn/news.xml' }],- });- await requestList.initialize();-- const crawler = new Apify.PuppeteerCrawler({- requestList,- handlePageFunction: async ({ page, request }) => {- console.log(`Processing ${request.url}...`);- await Apify.pushData({- url: request.url,- title: await page.title(),- html: await page.content(),- });- },- });-- await crawler.run();- console.log('Done.');-});-```diff --git a/docs/examples/PuppeteerWithProxy.md b/docs/examples/PuppeteerWithProxy.mddeleted file mode 100644index 95bf403f8..000000000--- a/docs/examples/PuppeteerWithProxy.md+++ /dev/null@@ -1,39 +0,0 @@-----id: puppeteer-with-proxy-title: Puppeteer With Proxy------This example demonstrates how to load pages in headless Chrome / Puppeteer over [Apify Proxy](https://docs.apify.com/proxy). To make it work, you'll-need an Apify Account that has access to the proxy. The proxy password is available on the [Proxy](https://my.apify.com/proxy) page in the app. Just-set it to the [`APIFY_PROXY_PASSWORD`](../guides/environment-variables#APIFY_PROXY_PASSWORD) environment variable or run the script using the CLI.--To run this example on the Apify Platform, select the `Node.js 12 + Chrome on Debian (apify/actor-node-chrome)` base image on the source tab of your-actor configuration.--```javascript-const Apify = require('apify');--Apify.main(async () => {- // Apify.launchPuppeteer() is similar to Puppeteer's launch() function.- // It accepts the same parameters and returns a preconfigured Puppeteer.Browser instance.- // Moreover, it accepts several additional options, such as useApifyProxy.- const options = {- useApifyProxy: true,- };- const browser = await Apify.launchPuppeteer(options);-- console.log('Running Puppeteer script...');-- // Proceed with a plain Puppeteer script.- const page = await browser.newPage();- const url = 'https://en.wikipedia.org/wiki/Main_Page';- await page.goto(url);- const title = await page.title();-- console.log(`Page title: ${title}`);-- // Cleaning up after yourself is always good.- await browser.close();- console.log('Puppeteer closed.');-});-```diff --git a/docs/examples/Screenshots.md b/docs/examples/Screenshots.mddeleted file mode 100644index 6d3b13752..000000000--- a/docs/examples/Screenshots.md+++ /dev/null@@ -1,64 +0,0 @@-----id: screenshots-title: Screenshots------This example demonstrates how to read and write data to the default key-value store using [`Apify.getValue()`](/docs/api/apify#getValue) and-[`Apify.setValue()`](/docs/api/apify#setValue).--The script crawls a list of URLs using Puppeteer, captures a screenshot of each page and saves it to the store. The list of URLs is provided as actor-input that is also read from the store.--In local configuration, the input is stored in the default key-value store's directory as a JSON file at-`./apify_storage/key_value_stores/default/INPUT.json`. You need to create the file and set it with the following content:--```json-{ "sources": [{ "url": "https://www.google.com" }, { "url": "https://www.duckduckgo.com" }] }-```--On the Apify cloud, the input can be either set manually in the UI app or passed as the POST payload to the-[Run actor API call](https://apify.com/docs/api/v2#/reference/actors/run-collection/run-actor). For more details, see-[Input and output](https://docs.apify.com/actor/run#input-and-output) in the Apify Actor documentation.--To run this example on the Apify Platform, select the `Node.js 12 + Chrome on Debian (apify/actor-node-chrome)` base image on the source tab of your-actor configuration.--```javascript-const Apify = require('apify');--Apify.main(async () => {- // Read the actor input configuration containing the URLs for the screenshot.- // By convention, the input is present in the actor's default key-value store under the "INPUT" key.- const input = await Apify.getInput();- if (!input) throw new Error('Have you passed the correct INPUT ?');-- const { sources } = input;-- const requestList = new Apify.RequestList({ sources });- await requestList.initialize();-- const crawler = new Apify.PuppeteerCrawler({- requestList,- handlePageFunction: async ({ page, request }) => {- console.log(`Processing ${request.url}...`);-- // This is a Puppeteer function that takes a screenshot of the page and returns its buffer.- const screenshotBuffer = await page.screenshot();-- // The record key may only include the following characters: a-zA-Z0-9!-_.'()- const key = request.url.replace(/[:/]/g, '_');-- // Save the screenshot. Choosing the right content type will automatically- // assign the local file the right extension, in this case .png.- // The screenshots will be stored in ./apify_storage/key_value_stores/default/- await Apify.setValue(key, screenshotBuffer, { contentType: 'image/png' });- console.log(`Screenshot of ${request.url} saved.`);- },- });-- // Run crawler.- await crawler.run();-- console.log('Crawler finished.');-});-```diff --git a/docs/examples/SynchronousRun.md b/docs/examples/SynchronousRun.mddeleted file mode 100644index 82322b2a2..000000000--- a/docs/examples/SynchronousRun.md+++ /dev/null@@ -1,50 +0,0 @@-----id: synchronous-run-title: Synchronous Run------This example shows a quick actor that has a run time of just a few seconds. It opens a [web page](http://goldengatebridge75.org/news/webcam.html) that-contains a webcam stream from the Golden Gate Bridge, takes a screenshot of the page and saves it as output.--This actor can be invoked synchronously using a single HTTP request to directly obtain its output as a response, using the-[Run actor synchronously](https://apify.com/docs/api/v2#/reference/actors/run-actor-synchronously/without-input) Apify API endpoint. The example is-also shared as the [`apify/example-golden-gate-webcam`](https://apify.com/apify/example-golden-gate-webcam) actor in the Apify library, so you can-test it directly there simply by sending a POST request to--```http-https://api.apify.com/v2/acts/apify~example-golden-gate-webcam/run-sync?token=[YOUR_API_TOKEN]-```--To run this example on the Apify Platform, select the `Node.js 12 + Chrome on Debian (apify/actor-node-chrome)` base image on the source tab of your-actor configuration.--```javascript-const Apify = require('apify');--Apify.main(async () => {- // Launch web browser.- const browser = await Apify.launchPuppeteer({ headless: true });-- // Load http://goldengatebridge75.org/news/webcam.html and get an IFRAME with the webcam stream- console.log('Opening web page...');- const page = await browser.newPage();- await page.goto('http://goldengatebridge75.org/news/webcam.html');- const frames = await page.frames();- const iframeWithVideo = frames[1];-- // Wait for the webcam to load.- console.log('Waiting for the webcam image.');- const imageElementHandle = await iframeWithVideo.waitForSelector('.VideoColm img[src^="blob:"]');- // Wait a little more to give the browser a chance to display the image.- await page.waitFor(1000);-- // Get a screenshot of that image.- const imageBuffer = await imageElementHandle.screenshot();- console.log('Screenshot captured.');-- // Save the screenshot as the actor's output. By convention, similarly to "INPUT",- // the actor's output is stored in the default key-value store under the "OUTPUT" key.- await Apify.setValue('OUTPUT', imageBuffer, { contentType: 'image/jpeg' });- console.log('Actor finished.');-});-```diff --git a/docs/typedefs/AbortFunction.md b/docs/typedefs/AbortFunction.mddeleted file mode 100644index fa88a4f00..000000000--- a/docs/typedefs/AbortFunction.md+++ /dev/null@@ -1,14 +0,0 @@-----id: abort-function-title: AbortFunction------<a name="abortfunction"></a>--**Returns**: `boolean`--**Params**--- **`response`**: `IncomingMessage`-----diff --git a/docs/typedefs/ActorRun.md b/docs/typedefs/ActorRun.mddeleted file mode 100644index 9b8a3a96a..000000000--- a/docs/typedefs/ActorRun.md+++ /dev/null@@ -1,181 +0,0 @@-----id: actor-run-title: ActorRun------<a name="actorrun"></a>--Represents information about an actor run, as returned by the [`Apify.call()`](/docs/api/apify#call) or [`Apify.callTask()`](/docs/api/apify#calltask)-function. The object is almost equivalent to the JSON response of the-[Actor run](https://apify.com/docs/api/v2#/reference/actors/run-collection/run-actor) Apify API endpoint and extended with certain fields. For more-details, see [Runs.](https://docs.apify.com/actor/run)--## Properties--### `id`--**Type**: `string`--Actor run ID-------### `actId`--**Type**: `string`--Actor ID-------### `startedAt`--**Type**: `Date`--Time when the actor run started-------### `finishedAt`--**Type**: `Date`--Time when the actor run finished. Contains `null` for running actors.-------### `status`--**Type**: `string`--Status of the run. For possible values, see [Run lifecycle](https://docs.apify.com/actor/run#lifecycle) in Apify actor documentation.-------### `meta`--**Type**: `object`--Actor run meta-data. For example:--```-{- "origin": "API",- "clientIp": "1.2.3.4",- "userAgent": "ApifyClient/0.2.13 (Linux; Node/v8.11.3)"-}-```-------### `stats`--**Type**: `object`--An object containing various actor run statistics. For example:--```-{- "inputBodyLen": 22,- "restartCount": 0,- "workersUsed": 1,-}-```--Beware that object fields might change in future releases.-------### `options`--**Type**: `object`--Actor run options. For example:--```-{- "build": "latest",- "waitSecs": 0,- "memoryMbytes": 256,- "diskMbytes": 512-}-```-------### `buildId`--**Type**: `string`--ID of the actor build used for the run. For details, see [Builds](https://docs.apify.com/actor/build) in Apify actor documentation.-------### `buildNumber`--**Type**: `string`--Number of the actor build used for the run. For example, `0.0.10`.-------### `exitCode`--**Type**: `number`--Exit code of the actor run process. It's `null` if actor is still running.-------### `defaultKeyValueStoreId`--**Type**: `string`--ID of the default key-value store associated with the actor run. See [`KeyValueStore`](/docs/api/key-value-store) for details.-------### `defaultDatasetId`--**Type**: `string`--ID of the default dataset associated with the actor run. See [`Dataset`](/docs/api/dataset) for details.-------### `defaultRequestQueueId`--**Type**: `string`--ID of the default request queue associated with the actor run. See [`RequestQueue`](/docs/api/request-queue) for details.-------### `containerUrl`--**Type**: `string`--URL on which the web server running inside actor run's Docker container can be accessed. For more details, see-[Container web server](https://docs.apify.com/actor/run#container-web-server) in Apify actor documentation.-------### `output`--**Type**: `object` | `null` | `undefined`--Contains output of the actor run. The value is `null` or `undefined` in case the actor is still running, or if you pass `false` to the `fetchOutput`-option of [`Apify.call()`](/docs/api/apify#call).--For example:--```-{- "contentType": "application/json; charset=utf-8",- "body": {- "message": "Hello world!"- }-}-```-----diff --git a/docs/typedefs/ApifyCallError.md b/docs/typedefs/ApifyCallError.mddeleted file mode 100644index d822042e3..000000000--- a/docs/typedefs/ApifyCallError.md+++ /dev/null@@ -1,34 +0,0 @@-----id: apify-call-error-title: ApifyCallError------<a name="apifycallerror"></a>--The class represents exceptions thrown by the [`Apify.call()`](/docs/api/apify#call) function.--## Properties--### `message`--**Type**: `String`--Error message-------### `name`--**Type**: `String`--Contains `"ApifyCallError"`-------### `run`--**Type**: [`ActorRun`](/docs/typedefs/actor-run)--Object representing the failed actor run.-----diff --git a/docs/typedefs/ApifyEnv.md b/docs/typedefs/ApifyEnv.mddeleted file mode 100644index 169701461..000000000--- a/docs/typedefs/ApifyEnv.md+++ /dev/null@@ -1,90 +0,0 @@-----id: apify-env-title: ApifyEnv------<a name="apifyenv"></a>--Parsed representation of the `APIFY_XXX` environmental variables.--## Properties--### `actorId`--**Type**: `string` | `null`--ID of the actor (APIFY_ACTOR_ID)-------### `actorRunId`--**Type**: `string` | `null`--ID of the actor run (APIFY_ACTOR_RUN_ID)-------### `actorTaskId`--**Type**: `string` | `null`--ID of the actor task (APIFY_ACTOR_TASK_ID)-------### `userId`--**Type**: `string` | `null`--ID of the user who started the actor - note that it might be different than the owner ofthe actor (APIFY_USER_ID)-------### `token`--**Type**: `string` | `null`--Authentication token representing privileges given to the actor run, it can be passed to various Apify APIs (APIFY_TOKEN)-------### `startedAt`--**Type**: `Date` | `null`--Date when the actor was started (APIFY_STARTED_AT)-------### `timeoutAt`--**Type**: `Date` | `null`--Date when the actor will time out (APIFY_TIMEOUT_AT)-------### `defaultKeyValueStoreId`--**Type**: `string` | `null`--ID of the key-value store where input and output data of this actor is stored (APIFY_DEFAULT_KEY_VALUE_STORE_ID)-------### `defaultDatasetId`--**Type**: `string` | `null`--ID of the dataset where input and output data of this actor is stored (APIFY_DEFAULT_DATASET_ID)-------### `memoryMbytes`--**Type**: `number` | `null`--Amount of memory allocated for the actor, in megabytes (APIFY_MEMORY_MBYTES)-----diff --git a/docs/typedefs/AutoscaledPoolOptions.md b/docs/typedefs/AutoscaledPoolOptions.mddeleted file mode 100644index 2ba7ebfd6..000000000--- a/docs/typedefs/AutoscaledPoolOptions.md+++ /dev/null@@ -1,132 +0,0 @@-----id: autoscaled-pool-options-title: AutoscaledPoolOptions------<a name="autoscaledpooloptions"></a>--## Properties--### `runTaskFunction`--**Type**: `function`--A function that performs an asynchronous resource-intensive task. The function must either be labeled `async` or return a promise.-------### `isTaskReadyFunction`--**Type**: `function`--A function that indicates whether `runTaskFunction` should be called. This function is called every time there is free capacity for a new task and it-should indicate whether it should start a new task or not by resolving to either `true` or `false`. Besides its obvious use, it is also useful for-task throttling to save resources.-------### `isFinishedFunction`--**Type**: `function`--A function that is called only when there are no tasks to be processed. If it resolves to `true` then the pool's run finishes. Being called only when-there are no tasks being processed means that as long as `isTaskReadyFunction()` keeps resolving to `true`, `isFinishedFunction()` will never be-called. To abort a run, use the [`AutoscaledPool.abort()`](/docs/api/autoscaled-pool#abort) method.-------### `minConcurrency`--**Type**: `number` <code> = 1</code>--The minimum number of tasks running in parallel.--_WARNING:_ If you set this value too high with respect to the available system memory and CPU, your code might run extremely slow or crash. If you're-not sure, just keep the default value and the concurrency will scale up automatically.-------### `maxConcurrency`--**Type**: `number` <code> = 1000</code>--The maximum number of tasks running in parallel.-------### `desiredConcurrency`--**Type**: `number`--The desired number of tasks that should be running parallel on the start of the pool, if there is a large enough supply of them. By default, it is-`minConcurrency`.-------### `desiredConcurrencyRatio`--**Type**: `number` <code> = 0.95</code>--Minimum level of desired concurrency to reach before more scaling up is allowed.-------### `scaleUpStepRatio`--**Type**: `number` <code> = 0.05</code>--Defines the fractional amount of desired concurrency to be added with each scaling up. The minimum scaling step is one.-------### `scaleDownStepRatio`--**Type**: `number` <code> = 0.05</code>--Defines the amount of desired concurrency to be subtracted with each scaling down. The minimum scaling step is one.-------### `maybeRunIntervalSecs`--**Type**: `number` <code> = 0.5</code>--Indicates how often the pool should call the `runTaskFunction()` to start a new task, in seconds. This has no effect on starting new tasks immediately-after a task completes.-------### `loggingIntervalSecs`--**Type**: `number` <code> = 60</code>--Specifies a period in which the instance logs its state, in seconds. Set to `null` to disable periodic logging.-------### `autoscaleIntervalSecs`--**Type**: `number` <code> = 10</code>--Defines in seconds how often the pool should attempt to adjust the desired concurrency based on the latest system status. Setting it lower than 1-might have a severe impact on performance. We suggest using a value from 5 to 20.-------### `snapshotterOptions`--**Type**: [`SnapshotterOptions`](/docs/typedefs/snapshotter-options)--Options to be passed down to the [`Snapshotter`](/docs/api/snapshotter) constructor. This is useful for fine-tuning the snapshot intervals and-history.-------### `systemStatusOptions`--**Type**: [`SystemStatusOptions`](/docs/typedefs/system-status-options)--Options to be passed down to the [`SystemStatus`](/docs/api/system-status) constructor. This is useful for fine-tuning the system status reports. If a-custom snapshotter is set in the options, it will be used by the pool.-----diff --git a/docs/typedefs/BasicCrawlerOptions.md b/docs/typedefs/BasicCrawlerOptions.mddeleted file mode 100644index 45140b3f0..000000000--- a/docs/typedefs/BasicCrawlerOptions.md+++ /dev/null@@ -1,146 +0,0 @@-----id: basic-crawler-options-title: BasicCrawlerOptions------<a name="basiccrawleroptions"></a>--## Properties--### `handleRequestFunction`--**Type**: [`HandleRequest`](/docs/typedefs/handle-request)--User-provided function that performs the logic of the crawler. It is called for each URL to crawl.--The function receives the following object as an argument:--```-{- request: Request,- autoscaledPool: AutoscaledPool-}-```--where the [`Request`](/docs/api/request) instance represents the URL to crawl.--The function must return a promise, which is then awaited by the crawler.--If the function throws an exception, the crawler will try to re-crawl the request later, up to `option.maxRequestRetries` times. If all the retries-fail, the crawler calls the function provided to the `handleFailedRequestFunction` parameter. To make this work, you should **always** let your-function throw exceptions rather than catch them. The exceptions are logged to the request using the-[`Request.pushErrorMessage()`](/docs/api/request#pusherrormessage) function.-------### `requestList`--**Type**: [`RequestList`](/docs/api/request-list)--Static list of URLs to be processed. Either `requestList` or `requestQueue` option must be provided (or both).-------### `requestQueue`--**Type**: [`RequestQueue`](/docs/api/request-queue)--Dynamic queue of URLs to be processed. This is useful for recursive crawling of websites. Either `requestList` or `requestQueue` option must be-provided (or both).-------### `handleRequestTimeoutSecs`--**Type**: `number` <code> = 60</code>--Timeout in which the function passed as `handleRequestFunction` needs to finish, in seconds.-------### `handleFailedRequestFunction`--**Type**: [`HandleFailedRequest`](/docs/typedefs/handle-failed-request)--A function to handle requests that failed more than `option.maxRequestRetries` times.--The function receives the following object as an argument:--```-{- request: Request,- error: Error,-}-```--where the [`Request`](/docs/api/request) instance corresponds to the failed request, and the `Error` instance represents the last error thrown during-processing of the request.--See [source code](https://github.com/apifytech/apify-js/blob/master/src/crawlers/basic_crawler.js#L11) for the default implementation of this-function.-------### `maxRequestRetries`--**Type**: `number` <code> = 3</code>--Indicates how many times the request is retried if-[`BasicCrawlerOptions.handleRequestFunction`](/docs/typedefs/basic-crawler-options#handlerequestfunction) fails.-------### `maxRequestsPerCrawl`--**Type**: `number`--Maximum number of pages that the crawler will open. The crawl will stop when this limit is reached. Always set this value in order to prevent infinite-loops in misconfigured crawlers. Note that in cases of parallel crawling, the actual number of pages visited might be slightly higher than this value.-------### `autoscaledPoolOptions`--**Type**: [`AutoscaledPoolOptions`](/docs/typedefs/autoscaled-pool-options)--Custom options passed to the underlying [`AutoscaledPool`](/docs/api/autoscaled-pool) constructor. Note that the `runTaskFunction` and-`isTaskReadyFunction` options are provided by `BasicCrawler` and cannot be overridden. However, you can provide a custom implementation of-`isFinishedFunction`.-------### `minConcurrency`--**Type**: `number` <code> = 1</code>--Sets the minimum concurrency (parallelism) for the crawl. Shortcut to the corresponding [`AutoscaledPool`](/docs/api/autoscaled-pool) option.--_WARNING:_ If you set this value too high with respect to the available system memory and CPU, your crawler will run extremely slow or crash. If-you're not sure, just keep the default value and the concurrency will scale up automatically.-------### `maxConcurrency`--**Type**: `number` <code> = 1000</code>--Sets the maximum concurrency (parallelism) for the crawl. Shortcut to the corresponding [`AutoscaledPool`](/docs/api/autoscaled-pool) option.-------### `useSessionPool`--**Type**: `boolean` <code> = false</code>--If set to true. Basic crawler will initialize the [`SessionPool`](/docs/api/session-pool) with the corresponding `sessionPoolOptions`. The session-instance will be than available in the `handleRequestFunction`.-------### `sessionPoolOptions`--**Type**: [`SessionPoolOptions`](/docs/typedefs/session-pool-options)--The configuration options for {SessionPool} to use.-----diff --git a/docs/typedefs/CheerioCrawlerOptions.md b/docs/typedefs/CheerioCrawlerOptions.mddeleted file mode 100644index f0721b9c1..000000000--- a/docs/typedefs/CheerioCrawlerOptions.md+++ /dev/null@@ -1,301 +0,0 @@-----id: cheerio-crawler-options-title: CheerioCrawlerOptions------<a name="cheeriocrawleroptions"></a>--## Properties--### `handlePageFunction`--**Type**: [`CheerioHandlePage`](/docs/typedefs/cheerio-handle-page)--User-provided function that performs the logic of the crawler. It is called for each page loaded and parsed by the crawler.--The function receives the following object as an argument:--```-{- // The Cheerio object's function with the parsed HTML.- $: Cheerio,-- // The request body of the web page, whose type depends on the content type.- body: String|Buffer,-- // The parsed object from JSON for responses with the "application/json" content types.- // For other content types it's null.- json: Object,-- // Apify.Request object with details of the requested web page- request: Request,-- // Parsed Content-Type HTTP header: { type, encoding }- contentType: Object,-- // An instance of Node's http.IncomingMessage object,- response: Object,-- // Underlying AutoscaledPool instance used to manage the concurrency of crawler- autoscaledPool: AutoscaledPool,-- // Session object, useful to work around anti-scraping protections- session: Session-}-```--Type of `body` depends on the `Content-Type` header of the web page:--- String for `text/html`, `application/xhtml+xml`, `application/xml` MIME content types-- Buffer for others MIME content types--Parsed `Content-Type` header using [content-type package](https://www.npmjs.com/package/content-type) is stored in `contentType`.--Cheerio is available only for HTML and XML content types.--With the [`Request`](/docs/api/request) object representing the URL to crawl.--If the function returns, the returned promise is awaited by the crawler.--If the function throws an exception, the crawler will try to re-crawl the request later, up to `option.maxRequestRetries` times. If all the retries-fail, the crawler calls the function provided to the `handleFailedRequestFunction` parameter. To make this work, you should **always** let your-function throw exceptions rather than catch them. The exceptions are logged to the request using the-[`Request.pushErrorMessage()`](/docs/api/request#pusherrormessage) function.-------### `requestList`--**Type**: [`RequestList`](/docs/api/request-list)--Static list of URLs to be processed. Either `requestList` or `requestQueue` option must be provided (or both).-------### `requestQueue`--**Type**: [`RequestQueue`](/docs/api/request-queue)--Dynamic queue of URLs to be processed. This is useful for recursive crawling of websites. Either `requestList` or `requestQueue` option must be-provided (or both).-------### `requestOptions`--**Type**: [`RequestAsBrowserOptions`](/docs/typedefs/request-as-browser-options)--Represents the options passed to the `requestAsBrowser` function that makes the HTTP requests to fetch the web pages. Provided `requestOptions` are-added to internal defaults that cannot be overridden to ensure the operation of `CheerioCrawler` and all its options. Headers will not be merged, use-[`RequestList`](/docs/api/request-list) and/or [`RequestQueue`](/docs/api/request-queue) to initialize your [`Request`](/docs/api/request) with the-correct headers or use `prepareRequestFunction` to modify your [`Request`](/docs/api/request) dynamically. If you need more granular control over your-requests, use [`BasicCrawler`](/docs/api/basic-crawler).--The mandatory internal defaults that **CANNOT BE OVERRIDDEN** by `requestOptions`:--```-{- url, // Provided by RequestList and/or RequestQueue- method, // Provided by RequestList and/or RequestQueue- headers, // Provided by RequestList and/or RequestQueue- payload, // Provided by RequestList and/or RequestQueue- strictSSL, // Use ignoreSslErrors- proxy, // Use useApifyProxy or proxyUrls-}-```-------### `prepareRequestFunction`--**Type**: [`PrepareRequest`](/docs/typedefs/prepare-request)--A function that executes before the HTTP request is made to the target resource. This function is suitable for setting dynamic properties such as-cookies to the [`Request`](/docs/api/request).--The function receives the following object as an argument:--```-{- request: Request,- session: Session-}-```--where the [`Request`](/docs/api/request) instance corresponds to the initialized request and the [`Session`](/docs/api/session) instance corresponds-to used session.--The function should modify the properties of the passed [`Request`](/docs/api/request) instance in place because there are already earlier references-to it. Making a copy and returning it from this function is therefore not supported, because it would create inconsistencies where different parts of-SDK would have access to a different [`Request`](/docs/api/request) instance.-------### `handlePageTimeoutSecs`--**Type**: `number` <code> = 60</code>--Timeout in which the function passed as `handlePageFunction` needs to finish, given in seconds.-------### `requestTimeoutSecs`--**Type**: `number` <code> = 30</code>--Timeout in which the HTTP request to the resource needs to finish, given in seconds.-------### `ignoreSslErrors`--**Type**: `boolean` <code> = true</code>--If set to true, SSL certificate errors will be ignored.-------### `useApifyProxy`--**Type**: `boolean` <code> = false</code>--If set to `true`, `CheerioCrawler` will be configured to use [Apify Proxy](https://my.apify.com/proxy) for all connections. For more information, see-the [documentation](https://docs.apify.com/proxy)-------### `apifyProxyGroups`--**Type**: `Array<string>`--An array of proxy groups to be used by the [Apify Proxy](https://docs.apify.com/proxy). Only applied if the `useApifyProxy` option is `true`.-------### `apifyProxySession`--**Type**: `string`--Apify Proxy session identifier to be used with requests made by `CheerioCrawler`. All HTTP requests going through the proxy with the same session-identifier will use the same target proxy server (i.e. the same IP address). The identifier can only contain the following characters: `0-9`, `a-z`,-`A-Z`, `"."`, `"_"` and `"~"`. Only applied if the `useApifyProxy` option is `true`.-------### `proxyUrls`--**Type**: `Array<string>`--An array of custom proxy URLs to be used by the `CheerioCrawler` instance. The provided custom proxies' order will be randomized and the resulting-list rotated. Custom proxies are not compatible with Apify Proxy and an attempt to use both configuration options will cause an error to be thrown on-startup.-------### `handleFailedRequestFunction`--**Type**: [`HandleFailedRequest`](/docs/typedefs/handle-failed-request)--A function to handle requests that failed more than `option.maxRequestRetries` times.--The function receives the following object as an argument:--```-{- request: Request,- error: Error,-}-```--where the [`Request`](/docs/api/request) instance corresponds to the failed request, and the `Error` instance represents the last error thrown during-processing of the request.--See [source code](https://github.com/apifytech/apify-js/blob/master/src/crawlers/cheerio_crawler.js#L13) for the default implementation of this-function.-------### `additionalMimeTypes`--**Type**: `Array<string>`--An array of <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Complete_list_of_MIME_types"- target="_blank">MIME types</a> you want the crawler to load and process. By default, only `text/html` and `application/xhtml+xml` MIME types are-supported.-------### `maxRequestRetries`--**Type**: `number` <code> = 3</code>--Indicates how many times the request is retried if either `requestFunction` or `handlePageFunction` fails.-------### `maxRequestsPerCrawl`--**Type**: `number`--Maximum number of pages that the crawler will open. The crawl will stop when this limit is reached. Always set this value in order to prevent infinite-loops in misconfigured crawlers. Note that in cases of parallel crawling, the actual number of pages visited might be slightly higher than this value.-------### `autoscaledPoolOptions`--**Type**: [`AutoscaledPoolOptions`](/docs/typedefs/autoscaled-pool-options)--Custom options passed to the underlying [`AutoscaledPool`](/docs/api/autoscaled-pool) constructor. Note that the `runTaskFunction`,-`isTaskReadyFunction` and `isFinishedFunction` options are provided by `CheerioCrawler` and cannot be overridden. Reasonable-[`Snapshotter`](/docs/api/snapshotter) and [`SystemStatus`](/docs/api/system-status) defaults are provided to account for the fact that `cheerio`-parses HTML synchronously and therefore blocks the event loop.-------### `minConcurrency`--**Type**: `number` <code> = 1</code>--Sets the minimum concurrency (parallelism) for the crawl. Shortcut to the corresponding [`AutoscaledPool`](/docs/api/autoscaled-pool) option.--_WARNING:_ If you set this value too high with respect to the available system memory and CPU, your crawler will run extremely slow or crash. If-you're not sure, just keep the default value and the concurrency will scale up automatically.-------### `maxConcurrency`--**Type**: `number` <code> = 1000</code>--Sets the maximum concurrency (parallelism) for the crawl. Shortcut to the corresponding [`AutoscaledPool`](/docs/api/autoscaled-pool) option.-------### `useSessionPool`--**Type**: `boolean` <code> = false</code>--If set to true Crawler will automatically use Session Pool. It will automatically retire sessions on 403, 401 and 429 status codes. It also marks-Session as bad after a request timeout.-------### `sessionPoolOptions`--**Type**: [`SessionPoolOptions`](/docs/typedefs/session-pool-options)--Custom options passed to the underlying [`SessionPool`](/docs/api/session-pool) constructor.-------### `persistCookiesPerSession`--**Type**: `boolean`--Automatically saves cookies to Session. Works only if Session Pool is used.--It parses cookie from response "set-cookie" header saves or updates cookies for session and once the session is used for next request. It passes the-"Cookie" header to the request with the session cookies.-----diff --git a/docs/typedefs/CheerioHandlePage.md b/docs/typedefs/CheerioHandlePage.mddeleted file mode 100644index 2e1ec4050..000000000--- a/docs/typedefs/CheerioHandlePage.md+++ /dev/null@@ -1,14 +0,0 @@-----id: cheerio-handle-page-title: CheerioHandlePage------<a name="cheeriohandlepage"></a>--**Returns**: `Promise<void>`--**Params**--- **`inputs`**: [`CheerioHandlePageInputs`](/docs/typedefs/cheerio-handle-page-inputs) - Arguments passed to this callback.-----diff --git a/docs/typedefs/CheerioHandlePageInputs.md b/docs/typedefs/CheerioHandlePageInputs.mddeleted file mode 100644index f793969da..000000000--- a/docs/typedefs/CheerioHandlePageInputs.md+++ /dev/null@@ -1,73 +0,0 @@-----id: cheerio-handle-page-inputs-title: CheerioHandlePageInputs------<a name="cheeriohandlepageinputs"></a>--## Properties--### `$`--**Type**: `CheerioSelector`--The [Cheerio](https://cheerio.js.org/) object with parsed HTML.-------### `body`--**Type**: `string` | `Buffer`--The request body of the web page.-------### `json`--**Type**: `*`--The parsed object from JSON string if the response contains the content type application/json.-------### `request`--**Type**: [`Request`](/docs/api/request)--The original [`Request`](/docs/api/request) object.-------### `contentType`--**Type**: `Object`--Parsed `Content-Type header: { type, encoding }`.-------### `response`--**Type**: `IncomingMessage`--An instance of Node's http.IncomingMessage object,-------### `autoscaledPool`--**Type**: [`AutoscaledPool`](/docs/api/autoscaled-pool)--A reference to the underlying [`AutoscaledPool`](/docs/api/autoscaled-pool) class that manages the concurrency of the crawler. Note that this property-is only initialized after calling the [`CheerioCrawler.run()`](/docs/api/cheerio-crawler#run) function. You can use it to change the concurrency-settings on the fly, to pause the crawler by calling [`AutoscaledPool.pause()`](/docs/api/autoscaled-pool#pause) or to abort it by calling-[`AutoscaledPool.abort()`](/docs/api/autoscaled-pool#abort).-------### `session`--**Type**: [`Session`](/docs/api/session)-----diff --git a/docs/typedefs/CreateSession.md b/docs/typedefs/CreateSession.mddeleted file mode 100644index 8d0e38c86..000000000--- a/docs/typedefs/CreateSession.md+++ /dev/null@@ -1,16 +0,0 @@-----id: create-session-title: CreateSession------<a name="createsession"></a>--**Returns**: [`Session`](/docs/api/session)--Factory user-function which creates customized [`Session`](/docs/api/session) instances.--**Params**--- **`sessionPool`**: [`SessionPool`](/docs/api/session-pool) - Pool requesting the new session.-----diff --git a/docs/typedefs/DatasetConsumer.md b/docs/typedefs/DatasetConsumer.mddeleted file mode 100644index 2fc83ee43..000000000--- a/docs/typedefs/DatasetConsumer.md+++ /dev/null@@ -1,17 +0,0 @@-----id: dataset-consumer-title: DatasetConsumer------<a name="datasetconsumer"></a>--**Returns**: `object`--User-function used in the `Dataset.forEach()` API.--**Params**--- **`item`**: `object` - Current [`Dataset`](/docs/api/dataset) entry being processed.-- **`index`**: `number` - Position of current {Dataset} entry.-----diff --git a/docs/typedefs/DatasetContent.md b/docs/typedefs/DatasetContent.mddeleted file mode 100644index e7e97dd87..000000000--- a/docs/typedefs/DatasetContent.md+++ /dev/null@@ -1,48 +0,0 @@-----id: dataset-content-title: DatasetContent------<a name="datasetcontent"></a>--## Properties--### `items`--**Type**: `Array<object>`--Dataset entries based on chosen format parameter.-------### `total`--**Type**: `number`--Total count of entries in the dataset.-------### `offset`--**Type**: `number`--Position of the first returned entry in the dataset.-------### `count`--**Type**: `number`--Count of dataset entries returned in this set.-------### `limit`--**Type**: `number`--Maximum number of dataset entries requested.-----diff --git a/docs/typedefs/DatasetMapper.md b/docs/typedefs/DatasetMapper.mddeleted file mode 100644index 7518030cf..000000000--- a/docs/typedefs/DatasetMapper.md+++ /dev/null@@ -1,17 +0,0 @@-----id: dataset-mapper-title: DatasetMapper------<a name="datasetmapper"></a>--**Returns**: `object`--User-function used in the `Dataset.map()` API.--**Params**--- **`item`**: `object` - Currect [`Dataset`](/docs/api/dataset) entry being processed.-- **`index`**: `number` - Position of current {Dataset} entry.-----diff --git a/docs/typedefs/DatasetReducer.md b/docs/typedefs/DatasetReducer.mddeleted file mode 100644index 1eaa506c3..000000000--- a/docs/typedefs/DatasetReducer.md+++ /dev/null@@ -1,18 +0,0 @@-----id: dataset-reducer-title: DatasetReducer------<a name="datasetreducer"></a>--**Returns**: `object`--User-function used in the `Dataset.reduce()` API.--**Params**--- **`memo`**: `object` - Previous state of the reduction.-- **`item`**: `object` - Currect [`Dataset`](/docs/api/dataset) entry being processed.-- **`index`**: `number` - Position of current {Dataset} entry.-----diff --git a/docs/typedefs/HandleFailedRequest.md b/docs/typedefs/HandleFailedRequest.mddeleted file mode 100644index b6a5e2414..000000000--- a/docs/typedefs/HandleFailedRequest.md+++ /dev/null@@ -1,14 +0,0 @@-----id: handle-failed-request-title: HandleFailedRequest------<a name="handlefailedrequest"></a>--**Returns**: `void` \| `Promise<void>`--**Params**--- **`inputs`**: [`HandleFailedRequestInput`](/docs/typedefs/handle-failed-request-input) - Arguments passed to this callback.-----diff --git a/docs/typedefs/HandleFailedRequestInput.md b/docs/typedefs/HandleFailedRequestInput.mddeleted file mode 100644index 08eaa9d79..000000000--- a/docs/typedefs/HandleFailedRequestInput.md+++ /dev/null@@ -1,24 +0,0 @@-----id: handle-failed-request-input-title: HandleFailedRequestInput------<a name="handlefailedrequestinput"></a>--## Properties--### `request`--**Type**: [`Request`](/docs/api/request)--The original {Request} object.-------### `error`--**Type**: `Error`--The Error thrown by `handleRequestFunction`.-----diff --git a/docs/typedefs/HandleRequest.md b/docs/typedefs/HandleRequest.mddeleted file mode 100644index e681126dd..000000000--- a/docs/typedefs/HandleRequest.md+++ /dev/null@@ -1,14 +0,0 @@-----id: handle-request-title: HandleRequest------<a name="handlerequest"></a>--**Returns**: `Promise<void>`--**Params**--- **`inputs`**: [`HandleRequestInputs`](/docs/typedefs/handle-request-inputs) - Arguments passed to this callback.-----diff --git a/docs/typedefs/HandleRequestInputs.md b/docs/typedefs/HandleRequestInputs.mddeleted file mode 100644index 1f1081456..000000000--- a/docs/typedefs/HandleRequestInputs.md+++ /dev/null@@ -1,33 +0,0 @@-----id: handle-request-inputs-title: HandleRequestInputs------<a name="handlerequestinputs"></a>--## Properties--### `request`--**Type**: [`Request`](/docs/api/request)--The original {Request} object.-------### `autoscaledPool`--**Type**: [`AutoscaledPool`](/docs/api/autoscaled-pool)--A reference to the underlying [`AutoscaledPool`](/docs/api/autoscaled-pool) class that manages the concurrency of the crawler. Note that this property-is only initialized after calling the [`BasicCrawler.run()`](/docs/api/basic-crawler#run) function. You can use it to change the concurrency settings-on the fly, to pause the crawler by calling [`AutoscaledPool.pause()`](/docs/api/autoscaled-pool#pause) or to abort it by calling-[`AutoscaledPool.abort()`](/docs/api/autoscaled-pool#abort).-------### `session`--**Type**: [`Session`](/docs/api/session)-----diff --git a/docs/typedefs/InterceptHandler.md b/docs/typedefs/InterceptHandler.mddeleted file mode 100644index 6aa19861f..000000000--- a/docs/typedefs/InterceptHandler.md+++ /dev/null@@ -1,12 +0,0 @@-----id: intercept-handler-title: InterceptHandler------<a name="intercepthandler"></a>--**Params**--- **`request`**: [`PuppeteerRequest`](/docs/api/request)-----diff --git a/docs/typedefs/KeyConsumer.md b/docs/typedefs/KeyConsumer.mddeleted file mode 100644index c06aa6c9d..000000000--- a/docs/typedefs/KeyConsumer.md+++ /dev/null@@ -1,17 +0,0 @@-----id: key-consumer-title: KeyConsumer------<a name="keyconsumer"></a>--User-function used in the [`KeyValueStore.forEachKey()`](/docs/api/key-value-store#foreachkey) method.--**Params**--- **`key`**: `string` - Current {KeyValue} key being processed.-- **`index`**: `number` - Position of the current key in [`KeyValueStore`](/docs/api/key-value-store).-- **`info`**: `object` - Information about the current [`KeyValueStore`](/docs/api/key-value-store) entry.- - **`.size`**: `number` - Size of the value associated with the current key in bytes.-----diff --git a/docs/typedefs/LaunchPuppeteer.md b/docs/typedefs/LaunchPuppeteer.mddeleted file mode 100644index e5761a6b4..000000000--- a/docs/typedefs/LaunchPuppeteer.md+++ /dev/null@@ -1,16 +0,0 @@-----id: launch-puppeteer-title: LaunchPuppeteer------<a name="launchpuppeteer"></a>--**Returns**: `Promise<Browser>` - Promise that resolves to Puppeteer's `Browser` instance. This might be obtained by calling-[puppeteer.launch()](https://pptr.dev/#?product=Puppeteer&version=v2.0.0&show=api-puppeteerlaunchoptions) directly, or by delegating to-[`Apify.launchPuppeteer()`](/docs/api/apify#launchpuppeteer).--**Params**--- **`inputs`**: [`LaunchPuppeteerOptions`](/docs/typedefs/launch-puppeteer-options) - Arguments passed to this callback.-----diff --git a/docs/typedefs/LaunchPuppeteerFunction.md b/docs/typedefs/LaunchPuppeteerFunction.mddeleted file mode 100644index bd91cd0bb..000000000--- a/docs/typedefs/LaunchPuppeteerFunction.md+++ /dev/null@@ -1,14 +0,0 @@-----id: launch-puppeteer-function-title: LaunchPuppeteerFunction------<a name="launchpuppeteerfunction"></a>--**Returns**: `Promise<Browser>`--**Params**--- **`options`**: [`LaunchPuppeteerOptions`](/docs/typedefs/launch-puppeteer-options)-----diff --git a/docs/typedefs/LaunchPuppeteerOptions.md b/docs/typedefs/LaunchPuppeteerOptions.mddeleted file mode 100644index 2f9d84847..000000000--- a/docs/typedefs/LaunchPuppeteerOptions.md+++ /dev/null@@ -1,97 +0,0 @@-----id: launch-puppeteer-options-title: LaunchPuppeteerOptions------<a name="launchpuppeteeroptions"></a>--Apify extends the launch options of Puppeteer. You can use any of the Puppeteer compatible-[`LaunchOptions`](https://pptr.dev/#?product=Puppeteer&show=api-puppeteerlaunchoptions) options in the-[`Apify.launchPuppeteer()`](/docs/api/apify#launchpuppeteer) function and in addition, all the options available below.--## Properties--### `proxyUrl`--**Type**: `string`--URL to a HTTP proxy server. It must define the port number, and it may also contain proxy username and password.--Example: `http://bob:[email protected]:1234`.-------### `userAgent`--**Type**: `string`--The `User-Agent` HTTP header used by the browser. If not provided, the function sets `User-Agent` to a reasonable default to reduce the chance of-detection of the crawler.-------### `useChrome`--**Type**: `boolean` <code> = false</code>--If `true` and `executablePath` is not set, Puppeteer will launch full Google Chrome browser available on the machine rather than the bundled Chromium.-The path to Chrome executable is taken from the `APIFY_CHROME_EXECUTABLE_PATH` environment variable if provided, or defaults to the typical Google-Chrome executable location specific for the operating system. By default, this option is `false`.-------### `useApifyProxy`--**Type**: `boolean` <code> = false</code>--If set to `true`, Puppeteer will be configured to use [Apify Proxy](https://my.apify.com/proxy) for all connections. For more information, see the-[documentation](https://docs.apify.com/proxy)-------### `apifyProxyGroups`--**Type**: `Array<string>`--An array of proxy groups to be used by the [Apify Proxy](https://docs.apify.com/proxy). Only applied if the `useApifyProxy` option is `true`.-------### `apifyProxySession`--**Type**: `string`--Apify Proxy session identifier to be used by all the Chrome browsers. All HTTP requests going through the proxy with the same session identifier will-use the same target proxy server (i.e. the same IP address). The identifier can only contain the following characters: `0-9`, `a-z`, `A-Z`, `"."`,-`"_"` and `"~"`. Only applied if the `useApifyProxy` option is `true`.-------### `puppeteerModule`--**Type**: `string` | `Object`--Either a require path (`string`) to a package to be used instead of default `puppeteer`, or an already required module (`Object`). This enables usage-of various Puppeteer wrappers such as `puppeteer-extra`.--Take caution, because it can cause all kinds of unexpected errors and weird behavior. Apify SDK is not tested with any other library besides-`puppeteer` itself.-------### `stealth`--**Type**: `boolean`--This setting hides most of the known properties that identify headless Chrome and makes it nearly undetectable. It is recommended to use it together-with the `useChrome` set to `true`.-------### `stealthOptions`--**Type**: [`StealthOptions`](/docs/typedefs/stealth-options)--Using this configuration, you can disable some of the hiding tricks. For these settings to take effect `stealth` must be set to true-----diff --git a/docs/typedefs/LoggerOptions.md b/docs/typedefs/LoggerOptions.mddeleted file mode 100644index 1b3615a5e..000000000--- a/docs/typedefs/LoggerOptions.md+++ /dev/null@@ -1,66 +0,0 @@-----id: logger-options-title: LoggerOptions------<a name="loggeroptions"></a>--## Properties--### `level`--**Type**: `number` <code> = 4</code>--Sets the log level to the given value, preventing messages from less important log levels from being printed to the console. Use in conjunction with-the `log.LEVELS` constants.-------### `maxDepth`--**Type**: `number` <code> = 4</code>--Max depth of data object that will be logged. Anything deeper than the limit will be stripped off.-------### `maxStringLength`--**Type**: `number` <code> = 2000</code>--Max length of the string to be logged. Longer strings will be truncated.-------### `prefix`--**Type**: `string`--Prefix to be prepended the each logged line.-------### `suffix`--**Type**: `string`--Suffix that will be appended the each logged line.-------### `logger`--**Type**: `Object`--Logger implementation to be used. Default one is log.LoggerText to log messages as easily readable strings. Optionally you can use `log.LoggerJson`-that formats each log line as a JSON.-------### `data`--**Type**: `Object`--Additional data to be added to each log line.-----diff --git a/docs/typedefs/MemoryInfo.md b/docs/typedefs/MemoryInfo.mddeleted file mode 100644index 77a7070e8..000000000--- a/docs/typedefs/MemoryInfo.md+++ /dev/null@@ -1,50 +0,0 @@-----id: memory-info-title: MemoryInfo------<a name="memoryinfo"></a>--Describes memory usage of an Actor.--## Properties--### `totalBytes`--**Type**: `number`--Total memory available in the system or container-------### `freeBytes`--**Type**: `number`--Amount of free memory in the system or container-------### `usedBytes`--**Type**: `number`--Amount of memory used (= totalBytes - freeBytes)-------### `mainProcessBytes`--**Type**: `number`--Amount of memory used the current Node.js process-------### `childProcessesBytes`--**Type**: `number`--Amount of memory used by child processes of the current Node.js process-----diff --git a/docs/typedefs/PrepareRequest.md b/docs/typedefs/PrepareRequest.mddeleted file mode 100644index a0684eee8..000000000--- a/docs/typedefs/PrepareRequest.md+++ /dev/null@@ -1,14 +0,0 @@-----id: prepare-request-title: PrepareRequest------<a name="preparerequest"></a>--**Returns**: `void` \| `Promise<void>`--**Params**--- **`inputs`**: [`PrepareRequestInputs`](/docs/typedefs/prepare-request-inputs) - Arguments passed to this callback.-----diff --git a/docs/typedefs/PrepareRequestInputs.md b/docs/typedefs/PrepareRequestInputs.mddeleted file mode 100644index 598576b57..000000000--- a/docs/typedefs/PrepareRequestInputs.md+++ /dev/null@@ -1,24 +0,0 @@-----id: prepare-request-inputs-title: PrepareRequestInputs------<a name="preparerequestinputs"></a>--## Properties--### `request`--**Type**: [`Request`](/docs/api/request)--Original instance fo the {Request} object. Must be modified in-place.-------### `session`--**Type**: [`Session`](/docs/api/session)--The current session-----diff --git a/docs/typedefs/PuppeteerCrawlerOptions.md b/docs/typedefs/PuppeteerCrawlerOptions.mddeleted file mode 100644index c5b62e88f..000000000--- a/docs/typedefs/PuppeteerCrawlerOptions.md+++ /dev/null@@ -1,211 +0,0 @@-----id: puppeteer-crawler-options-title: PuppeteerCrawlerOptions------<a name="puppeteercrawleroptions"></a>--## Properties--### `handlePageFunction`--**Type**: [`PuppeteerHandlePage`](/docs/typedefs/puppeteer-handle-page)--Function that is called to process each request. It is passed an object with the following fields:--```-{- request: Request,- response: Response,- page: Page,- puppeteerPool: PuppeteerPool,- autoscaledPool: AutoscaledPool,- session: Session,-}-```--`request` is an instance of the [`Request`](/docs/api/request) object with details about the URL to open, HTTP method etc. `page` is an instance of-the `Puppeteer` [`Page`](https://pptr.dev/#?product=Puppeteer&show=api-class-page) `response` is an instance of the `Puppeteer`-[`Response`](https://pptr.dev/#?product=Puppeteer&show=api-class-response), which is the main resource response as returned by-`page.goto(request.url)`. `puppeteerPool` is an instance of the [`PuppeteerPool`](/docs/api/puppeteer-pool) used by this `PuppeteerCrawler`.--The function must return a promise, which is then awaited by the crawler.--If the function throws an exception, the crawler will try to re-crawl the request later, up to `option.maxRequestRetries` times. If all the retries-fail, the crawler calls the function provided to the `handleFailedRequestFunction` parameter. To make this work, you should **always** let your-function throw exceptions rather than catch them. The exceptions are logged to the request using the-[`Request.pushErrorMessage()`](/docs/api/request#pusherrormessage) function.-------### `requestList`--**Type**: [`RequestList`](/docs/api/request-list)--Static list of URLs to be processed. Either `requestList` or `requestQueue` option must be provided (or both).-------### `requestQueue`--**Type**: [`RequestQueue`](/docs/api/request-queue)--Dynamic queue of URLs to be processed. This is useful for recursive crawling of websites. Either `requestList` or `requestQueue` option must be-provided (or both).-------### `handlePageTimeoutSecs`--**Type**: `number` <code> = 60</code>--Timeout in which the function passed as `handlePageFunction` needs to finish, in seconds.-------### `gotoFunction`--**Type**: [`PuppeteerGoto`](/docs/typedefs/puppeteer-goto)--Overrides the function that opens the page in Puppeteer. The function should return the result of Puppeteer's-[page.goto()](https://pptr.dev/#?product=Puppeteer&show=api-pagegotourl-options) function, i.e. a `Promise` resolving to the-[Response](https://pptr.dev/#?product=Puppeteer&show=api-class-response) object.--This is useful if you need to extend the page load timeout or select different criteria to determine that the navigation succeeded.--Note that a single page object is only used to process a single request and it is closed afterwards.--By default, the function invokes [`puppeteer.gotoExtended()`](/docs/api/puppeteer#gotoextended) with a timeout of 60 seconds. For details, see source-code on [GitHub](https://github.com/apifytech/apify-js/blob/master/src/crawlers/puppeteer_crawler.js#L292).-------### `gotoTimeoutSecs`--**Type**: `number` <code> = 60</code>--Timeout in which page navigation needs to finish, in seconds. When `gotoFunction()` is used and thus the default function is overridden, this timeout-will not be used and needs to be configured in the new `gotoFunction()`.-------### `handleFailedRequestFunction`--**Type**: [`HandleFailedRequest`](/docs/typedefs/handle-failed-request)--A function to handle requests that failed more than `option.maxRequestRetries` times.--The function receives the following object as an argument:--```-{- request: Request,- error: Error,-}-```--Where the [`Request`](/docs/api/request) instance corresponds to the failed request, and the `Error` instance represents the last error thrown during-processing of the request.--See [source code](https://github.com/apifytech/apify-js/blob/master/src/crawlers/puppeteer_crawler.js#L301) for the default implementation of this-function.-------### `maxRequestRetries`--**Type**: `number` <code> = 3</code>--Indicates how many times the request is retried if either `handlePageFunction()` or `gotoFunction()` fails.-------### `maxRequestsPerCrawl`--**Type**: `number`--Maximum number of pages that the crawler will open. The crawl will stop when this limit is reached. Always set this value in order to prevent infinite-loops in misconfigured crawlers. Note that in cases of parallel crawling, the actual number of pages visited might be slightly higher than this value.-------### `puppeteerPoolOptions`--**Type**: [`PuppeteerPoolOptions`](/docs/typedefs/puppeteer-pool-options)--Custom options passed to the underlying [`PuppeteerPool`](/docs/api/puppeteer-pool) constructor. You can tweak those to fine-tune browser management.-------### `launchPuppeteerFunction`--**Type**: [`LaunchPuppeteerFunction`](/docs/typedefs/launch-puppeteer-function)--Overrides the default function to launch a new Puppeteer instance. Shortcut to the corresponding [`PuppeteerPool`](/docs/api/puppeteer-pool) option.-See source code on [GitHub](https://github.com/apifytech/apify-js/blob/master/src/puppeteer_pool.js#L28) for default behavior.-------### `launchPuppeteerOptions`--**Type**: [`LaunchPuppeteerOptions`](/docs/typedefs/launch-puppeteer-options)--Options used by [`Apify.launchPuppeteer()`](/docs/api/apify#launchpuppeteer) to start new Puppeteer instances. Shortcut to the corresponding-[`PuppeteerPool`](/docs/api/puppeteer-pool) option.-------### `autoscaledPoolOptions`--**Type**: [`AutoscaledPoolOptions`](/docs/typedefs/autoscaled-pool-options)--Custom options passed to the underlying [`AutoscaledPool`](/docs/api/autoscaled-pool) instance constructor. Note that the `runTaskFunction`,-`isTaskReadyFunction` and `isFinishedFunction` options are provided by `PuppeteerCrawler` and should not be overridden.-------### `minConcurrency`--**Type**: `number` <code> = 1</code>--Sets the minimum concurrency (parallelism) for the crawl. Shortcut to the corresponding-[`AutoscaledPoolOptions.minConcurrency`](/docs/typedefs/autoscaled-pool-options#minconcurrency) option.--_WARNING:_ If you set this value too high with respect to the available system memory and CPU, your crawler will run extremely slow or crash. If-you're not sure, just keep the default value and the concurrency will scale up automatically.-------### `maxConcurrency`--**Type**: `number` <code> = 1000</code>--Sets the maximum concurrency (parallelism) for the crawl. Shortcut to the corresponding-[`AutoscaledPoolOptions.maxConcurrency`](/docs/typedefs/autoscaled-pool-options#maxconcurrency) option.-------### `useSessionPool`--**Type**: `boolean` <code> = false</code>--If set to true Crawler will automatically use Session Pool. It will automatically retire sessions on 403, 401 and 429 status codes. It also marks-Session as bad after a request timeout.-------### `sessionPoolOptions`--**Type**: [`SessionPoolOptions`](/docs/typedefs/session-pool-options)--Custom options passed to the underlying [`SessionPool`](/docs/api/session-pool) constructor.-------### `persistCookiesPerSession`--**Type**: `boolean` <code> = false</code>--Automatically saves cookies to Session. Works only if Session Pool is used.-----diff --git a/docs/typedefs/PuppeteerGoto.md b/docs/typedefs/PuppeteerGoto.mddeleted file mode 100644index 88d572c77..000000000--- a/docs/typedefs/PuppeteerGoto.md+++ /dev/null@@ -1,16 +0,0 @@-----id: puppeteer-goto-title: PuppeteerGoto------<a name="puppeteergoto"></a>--**Returns**: `Promise<(PuppeteerResponse|null)>` - An instance of the Puppeteer-[`Response`](https://pptr.dev/#?product=Puppeteer&show=api-class-response), which is the main resource response as returned by-`page.goto(request.url)`.--**Params**--- **`inputs`**: [`PuppeteerGotoInputs`](/docs/typedefs/puppeteer-goto-inputs) - Arguments passed to this callback.-----diff --git a/docs/typedefs/PuppeteerGotoInputs.md b/docs/typedefs/PuppeteerGotoInputs.mddeleted file mode 100644index 561e4e81b..000000000--- a/docs/typedefs/PuppeteerGotoInputs.md+++ /dev/null@@ -1,48 +0,0 @@-----id: puppeteer-goto-inputs-title: PuppeteerGotoInputs------<a name="puppeteergotoinputs"></a>--## Properties--### `page`--**Type**: `PuppeteerPage`--is an instance of the Puppeteer [`Page`](https://pptr.dev/#?product=Puppeteer&show=api-class-page)-------### `request`--**Type**: [`Request`](/docs/api/request)--An instance of the [`Request`](/docs/api/request) object with details about the URL to open, HTTP method etc.-------### `autoscaledPool`--**Type**: [`AutoscaledPool`](/docs/api/autoscaled-pool)--An instance of the `AutoscaledPool`.-------### `puppeteerPool`--**Type**: [`PuppeteerPool`](/docs/api/puppeteer-pool)--An instance of the [`PuppeteerPool`](/docs/api/puppeteer-pool) used by this `PuppeteerCrawler`.-------### `session`--**Type**: [`Session`](/docs/api/session)--`Session` object for this request.-----diff --git a/docs/typedefs/PuppeteerHandlePage.md b/docs/typedefs/PuppeteerHandlePage.mddeleted file mode 100644index 713829d19..000000000--- a/docs/typedefs/PuppeteerHandlePage.md+++ /dev/null@@ -1,14 +0,0 @@-----id: puppeteer-handle-page-title: PuppeteerHandlePage------<a name="puppeteerhandlepage"></a>--**Returns**: `Promise<void>`--**Params**--- **`inputs`**: [`PuppeteerHandlePageInputs`](/docs/typedefs/puppeteer-handle-page-inputs) - Arguments passed to this callback.-----diff --git a/docs/typedefs/PuppeteerHandlePageInputs.md b/docs/typedefs/PuppeteerHandlePageInputs.mddeleted file mode 100644index fc9fa2ca8..000000000--- a/docs/typedefs/PuppeteerHandlePageInputs.md+++ /dev/null@@ -1,58 +0,0 @@-----id: puppeteer-handle-page-inputs-title: PuppeteerHandlePageInputs------<a name="puppeteerhandlepageinputs"></a>--## Properties--### `request`--**Type**: [`Request`](/docs/api/request)--An instance of the [`Request`](/docs/api/request) object with details about the URL to open, HTTP method etc.-------### `response`--**Type**: `PuppeteerResponse`--An instance of the Puppeteer [`Response`](https://pptr.dev/#?product=Puppeteer&show=api-class-response), which is the main resource response as-returned by `page.goto(request.url)`.-------### `page`--**Type**: `PuppeteerPage`--is an instance of the Puppeteer [`Page`](https://pptr.dev/#?product=Puppeteer&show=api-class-page)-------### `puppeteerPool`--**Type**: [`PuppeteerPool`](/docs/api/puppeteer-pool)--An instance of the [`PuppeteerPool`](/docs/api/puppeteer-pool) used by this `PuppeteerCrawler`.-------### `autoscaledPool`--**Type**: [`AutoscaledPool`](/docs/api/autoscaled-pool)--A reference to the underlying [`AutoscaledPool`](/docs/api/autoscaled-pool) class that manages the concurrency of the crawler. Note that this property-is only initialized after calling the [`PuppeteerCrawler.run()`](/docs/api/puppeteer-crawler#run) function. You can use it to change the concurrency-settings on the fly, to pause the crawler by calling [`AutoscaledPool.pause()`](/docs/api/autoscaled-pool#pause) or to abort it by calling-[`AutoscaledPool.abort()`](/docs/api/autoscaled-pool#abort).-------### `session`--**Type**: [`Session`](/docs/api/session)-----diff --git a/docs/typedefs/PuppeteerPoolOptions.md b/docs/typedefs/PuppeteerPoolOptions.mddeleted file mode 100644index 32d5f34a6..000000000--- a/docs/typedefs/PuppeteerPoolOptions.md+++ /dev/null@@ -1,113 +0,0 @@-----id: puppeteer-pool-options-title: PuppeteerPoolOptions------<a name="puppeteerpooloptions"></a>--## Properties--### `useLiveView`--**Type**: `boolean`--Enables the use of a preconfigured [`LiveViewServer`](/docs/api/live-view-server) that serves snapshots just before a page would be recycled by-`PuppeteerPool`. If there are no clients connected, it has close to zero impact on performance.-------### `maxOpenPagesPerInstance`--**Type**: `number` <code> = 50</code>--Maximum number of open pages (i.e. tabs) per browser. When this limit is reached, new pages are loaded in a new browser instance.-------### `retireInstanceAfterRequestCount`--**Type**: `number` <code> = 100</code>--Maximum number of requests that can be processed by a single browser instance. After the limit is reached, the browser is retired and new requests are-handled by a new browser instance.-------### `puppeteerOperationTimeoutSecs`--**Type**: `number` <code> = 15</code>--All browser management operations such as launching a new browser, opening a new page or closing a page will timeout after the set number of seconds-and the connected browser will be retired.-------### `instanceKillerIntervalSecs`--**Type**: `number` <code> = 60</code>--Indicates how often are the open Puppeteer instances checked whether they can be closed.-------### `killInstanceAfterSecs`--**Type**: `number` <code> = 300</code>--When Puppeteer instance reaches the `retireInstanceAfterRequestCount` limit then it is considered retired and no more tabs will be opened. After the-last tab is closed the whole browser is closed too. This parameter defines a time limit between the last tab was opened and before the browser is-closed even if there are pending open tabs.-------### `launchPuppeteerFunction`--**Type**: [`LaunchPuppeteerFunction`](/docs/typedefs/launch-puppeteer-function)--Overrides the default function to launch a new Puppeteer instance. The function must return a promise resolving to-[`Browser`](https://github.com/GoogleChrome/puppeteer/blob/master/docs/api.md#class-browser) instance. See the source code on-[GitHub](https://github.com/apifytech/apify-js/blob/master/src/puppeteer_pool.js#L28) for the default implementation.-------### `launchPuppeteerOptions`--**Type**: [`LaunchPuppeteerOptions`](/docs/typedefs/launch-puppeteer-options)--Options used by [`Apify.launchPuppeteer()`](/docs/api/apify#launchpuppeteer) to start new Puppeteer instances.-------### `recycleDiskCache`--**Type**: `boolean` <code> = false</code>--Enables recycling of disk cache directories by Chrome instances. When a browser instance is closed, its disk cache directory is not deleted but it's-used by a newly opened browser instance. This is useful to reduce amount of data that needs to be downloaded to speed up crawling and reduce proxy-usage. Note that the new browser starts with empty cookies, local storage etc. so this setting doesn't affect anonymity of your crawler.--Beware that the disk cache directories can consume a lot of disk space. To limit the space consumed, you can pass the `--disk-cache-size=X` argument-to `launchPuppeteerargs`, where `X` is the approximate maximum number of bytes for disk cache.--Do not use the `recycleDiskCache` setting together with `--disk-cache-dir` argument in `launchPuppeteerargs`, the behavior is undefined.-------### `useIncognitoPages`--**Type**: `boolean`--With this option selected, all pages will be opened in a new incognito browser context, which means that they will not share cookies or cache and-their resources will not be throttled by one another.-------### `proxyUrls`--**Type**: `Array<string>`--An array of custom proxy URLs to be used by the `PuppeteerPool` instance. The provided custom proxies' order will be randomized and the resulting list-rotated. Custom proxies are not compatible with Apify Proxy and an attempt to use both configuration options will cause an error to be thrown on-startup.-----diff --git a/docs/typedefs/QueueOperationInfo.md b/docs/typedefs/QueueOperationInfo.mddeleted file mode 100644index 91263bd2b..000000000--- a/docs/typedefs/QueueOperationInfo.md+++ /dev/null@@ -1,43 +0,0 @@-----id: queue-operation-info-title: QueueOperationInfo------<a name="queueoperationinfo"></a>--A helper class that is used to report results from various [`RequestQueue`](/docs/api/request-queue) functions as well as-[`utils.enqueueLinks()`](/docs/api/utils#enqueuelinks).--## Properties--### `wasAlreadyPresent`--**Type**: `boolean`--Indicates if request was already present in the queue.-------### `wasAlreadyHandled`--**Type**: `boolean`--Indicates if request was already marked as handled.-------### `requestId`--**Type**: `string`--The ID of the added request-------### `request`--**Type**: [`Request`](/docs/api/request)--The original [`Request`](/docs/api/request) object passed to the `RequestQueue` function.-----diff --git a/docs/typedefs/RequestAsBrowserOptions.md b/docs/typedefs/RequestAsBrowserOptions.mddeleted file mode 100644index 55fb72ffc..000000000--- a/docs/typedefs/RequestAsBrowserOptions.md+++ /dev/null@@ -1,94 +0,0 @@-----id: request-as-browser-options-title: RequestAsBrowserOptions------<a name="requestasbrowseroptions"></a>--## Properties--### `url`--**Type**: `string`--URL of the target endpoint. Supports both HTTP and HTTPS schemes.-------### `method`--**Type**: `string` <code> = "GET"</code>--HTTP method.-------### `headers`--**Type**: `Object`--Additional HTTP headers to add. It's only recommended to use this option, with headers that are typically added by websites, such as cookies.-Overriding default browser headers will remove the masking this function provides.-------### `proxyUrl`--**Type**: `string`--An HTTP proxy to be passed down to the HTTP request. Supports proxy authentication with Basic Auth.-------### `languageCode`--**Type**: `string` <code> = "en"</code>--Two-letter ISO 639 language code.-------### `countryCode`--**Type**: `string` <code> = "US"</code>--Two-letter ISO 3166 country code.-------### `useMobileVersion`--**Type**: `boolean`--If `true`, the function uses User-Agent of a mobile browser.-------### `abortFunction`--**Type**: [`AbortFunction`](/docs/typedefs/abort-function)--Function accepts `response` object as a single parameter and should return true or false. If function returns true request gets aborted. This function-is passed to the [@apify/http-request](https://www.npmjs.com/package/@apify/http-request) NPM package.-------### `ignoreSslErrors`--**Type**: `boolean` <code> = true</code>--If set to true, SSL/TLS certificate errors will be ignored.-------### `useInsecureHttpParser`--**Type**: `boolean` <code> = true</code>--Node.js' HTTP parser is stricter than parsers used by web browsers, which prevents scraping of websites whose servers do not comply with HTTP specs,-either by accident or due to some anti-scraping protections, causing e.g. the `invalid header value char` error. The `useInsecureHttpParser` option-forces the HTTP parser to ignore certain errors which lets you scrape such websites. However, it will also open your application to some security-vulnerabilities, although the risk should be negligible as these vulnerabilities mainly relate to server applications, not clients. Learn more in this-[blog post](https://snyk.io/blog/node-js-release-fixes-a-critical-http-security-vulnerability/).-----diff --git a/docs/typedefs/RequestListInput.md b/docs/typedefs/RequestListInput.mddeleted file mode 100644index d5dbda7fc..000000000--- a/docs/typedefs/RequestListInput.md+++ /dev/null@@ -1,26 +0,0 @@-----id: request-list-input-title: RequestListInput------<a name="requestlistinput"></a>--## Properties--### `method`--**Type**: `string`-------### `requestsFromUrl`--**Type**: `string`-------### `regex`--**Type**: `RegExp`-----diff --git a/docs/typedefs/RequestListOptions.md b/docs/typedefs/RequestListOptions.mddeleted file mode 100644index 2613ee172..000000000--- a/docs/typedefs/RequestListOptions.md+++ /dev/null@@ -1,151 +0,0 @@-----id: request-list-options-title: RequestListOptions------<a name="requestlistoptions"></a>--## Properties--### `sources`--**Type**: [`Array<(RequestOptions|Request|string)>`](/docs/typedefs/request-options)--An array of sources of URLs for the [`RequestList`](/docs/api/request-list). It can be either an array of strings, plain objects that define at least-the `url` property, or an array of [`Request`](/docs/api/request) instances.--**IMPORTANT:** The `sources` array will be consumed (left empty) after `RequestList` initializes. This is a measure to prevent memory leaks in-situations when millions of sources are added.--Additionally, the `requestsFromUrl` property may be used instead of `url`, which will instruct `RequestList` to download the source URLs from a given-remote location. The URLs will be parsed from the received response.--```-[- // A single URL- 'http://example.com/a/b',-- // Modify Request options- { method: PUT, 'https://example.com/put, payload: { foo: 'bar' }}-- // Batch import of URLs from a file hosted on the web,- // where the URLs should be requested using the HTTP POST request- { method: 'POST', requestsFromUrl: 'http://example.com/urls.txt' },-- // Batch import from remote file, using a specific regular expression to extract the URLs.- { requestsFromUrl: 'http://example.com/urls.txt', regex: /https:\/\/example.com\/.+/ },-- // Get list of URLs from a Google Sheets document. Just add "/gviz/tq?tqx=out:csv" to the Google Sheet URL.- // For details, see https://help.apify.com/en/articles/2906022-scraping-a-list-of-urls-from-a-google-sheets-document- { requestsFromUrl: 'https://docs.google.com/spreadsheets/d/1GA5sSQhQjB_REes8I5IKg31S-TuRcznWOPjcpNqtxmU/gviz/tq?tqx=out:csv' }-]-```-------### `sourcesFunction`--**Type**: `function`--A function that will be called to get the sources for the `RequestList`, but only if `RequestList` was not able to fetch their persisted version (see-[`RequestListOptions.persistRequestsKey`](/docs/typedefs/request-list-options#persistrequestskey)). It must return an `Array` of-[`Request`](/docs/api/request) or [`RequestOptions`](/docs/typedefs/request-options).--This is very useful in a scenario when getting the sources is a resource intensive or time consuming task, such as fetching URLs from multiple-sitemaps or parsing URLs from large datasets. Using the `sourcesFunction` in combination with `persistStateKey` and `persistRequestsKey` will allow-you to fetch and parse those URLs only once, saving valuable time when your actor migrates or restarts.--If both [`RequestListOptions.sources`](/docs/typedefs/request-list-options#sources) and-[`RequestListOptions.sourcesFunction`](/docs/typedefs/request-list-options#sourcesfunction) are provided, the sources returned by the function will be-added after the `sources`.--**Example:**--```javascript-// Let's say we want to scrape URLs extracted from sitemaps.--const sourcesFunction = async () => {- // With super large sitemaps, this operation could take very long- // and big websites typically have multiple sitemaps.- const sitemaps = await downloadHugeSitemaps();- return parseUrlsFromSitemaps(sitemaps);-};--// Sitemaps can change in real-time, so it's important to persist-// the URLs we collected. Otherwise we might lose our scraping-// state in case of an actor migration / failure / time-out.-const requestList = new RequestList({- sourcesFunction,- persistStateKey: 'state-key',- persistRequestsKey: 'requests-key',-});--// The sourcesFunction is called now and the Requests are persisted.-// If something goes wrong and we need to start again, RequestList-// will load the persisted Requests from storage and will NOT-// call the sourcesFunction again, saving time and resources.-await requestList.initialize();-```-------### `persistStateKey`--**Type**: `string`--Identifies the key in the default key-value store under which `RequestList` periodically stores its state (i.e. which URLs were crawled and which-not). If the actor is restarted, `RequestList` will read the state and continue where it left off.--If `persistStateKey` is not set, `RequestList` will always start from the beginning, and all the source URLs will be crawled again.-------### `persistRequestsKey`--**Type**: `string`--Identifies the key in the default key-value store under which the `RequestList` persists its Requests during the-[`RequestList.initialize()`](/docs/api/request-list#initialize) call. This is necessary if `persistStateKey` is set and the source URLs might-potentially change, to ensure consistency of the source URLs and state object. However, it comes with some storage and performance overheads.--If `persistRequestsKey` is not set, [`RequestList.initialize()`](/docs/api/request-list#initialize) will always fetch the sources from their origin,-check that they are consistent with the restored state (if any) and throw an error if they are not.-------### `state`--**Type**: [`RequestListState`](/docs/typedefs/request-list-state)--The state object that the `RequestList` will be initialized from. It is in the form as returned by `RequestList.getState()`, such as follows:--```-{- nextIndex: 5,- nextUniqueKey: 'unique-key-5'- inProgress: {- 'unique-key-1': true,- 'unique-key-4': true,- },-}-```--Note that the preferred (and simpler) way to persist the state of crawling of the `RequestList` is to use the `stateKeyPrefix` parameter instead.-------### `keepDuplicateUrls`--**Type**: `boolean` <code> = false</code>--By default, `RequestList` will deduplicate the provided URLs. Default deduplication is based on the `uniqueKey` property of passed source-[`Request`](/docs/api/request) objects.--If the property is not present, it is generated by normalizing the URL. If present, it is kept intact. In any case, only one request per `uniqueKey`-is added to the `RequestList` resulting in removal of duplicate URLs / unique keys.--Setting `keepDuplicateUrls` to `true` will append an additional identifier to the `uniqueKey` of each request that does not already include a-`uniqueKey`. Therefore, duplicate URLs will be kept in the list. It does not protect the user from having duplicates in user set `uniqueKey`s however.-It is the user's responsibility to ensure uniqueness of their unique keys if they wish to keep more than just a single copy in the `RequestList`.-----diff --git a/docs/typedefs/RequestListState.md b/docs/typedefs/RequestListState.mddeleted file mode 100644index 7b6e785e8..000000000--- a/docs/typedefs/RequestListState.md+++ /dev/null@@ -1,47 +0,0 @@-----id: request-list-state-title: RequestListState------<a name="requestliststate"></a>--Represents state of a [`RequestList`](/docs/api/request-list). It can be used to resume a [`RequestList`](/docs/api/request-list) which has been-previously processed. You can obtain the state by calling [`RequestList.getState()`](/docs/api/request-list#getstate) and receive an object with the-following structure:--```-{- nextIndex: 5,- nextUniqueKey: 'unique-key-5'- inProgress: {- 'unique-key-1': true,- 'unique-key-4': true- },-}-```--## Properties--### `nextIndex`--**Type**: `number`--Position of the next request to be processed.-------### `nextUniqueKey`--**Type**: `string`--Key of the next request to be processed.-------### `inProgress`--**Type**: `Object<string, boolean>`--An object mapping request keys to a boolean value respresenting whether they are being processed at the moment.-----diff --git a/docs/typedefs/RequestOptions.md b/docs/typedefs/RequestOptions.mddeleted file mode 100644index 8ab74b639..000000000--- a/docs/typedefs/RequestOptions.md+++ /dev/null@@ -1,94 +0,0 @@-----id: request-options-title: RequestOptions------<a name="requestoptions"></a>--Specifies required and optional fields for constructing a [`Request`](/docs/api/request).--## Properties--### `url`--**Type**: `string`--URL of the web page to crawl. It must be a non-empty string.-------### `uniqueKey`--**Type**: `string`--A unique key identifying the request. Two requests with the same `uniqueKey` are considered as pointing to the same URL.--If `uniqueKey` is not provided, then it is automatically generated by normalizing the URL. For example, the URL of `HTTP://www.EXAMPLE.com/something/`-will produce the `uniqueKey` of `http://www.example.com/something`.--The `keepUrlFragment` option determines whether URL hash fragment is included in the `uniqueKey` or not.--The `useExtendedUniqueKey` options determines whether method and payload are included in the `uniqueKey`, producing a `uniqueKey` in the following-format: `METHOD(payloadHash):normalizedUrl`. This is useful when requests point to the same URL, but with different methods and payloads. For example:-form submits.--Pass an arbitrary non-empty text value to the `uniqueKey` property to override the default behavior and specify which URLs shall be considered equal.-------### `method`--**Type**: `string` <code> = "'GET'"</code>-------### `payload`--**Type**: `string` | `Buffer`--HTTP request payload, e.g. for POST requests.-------### `headers`--**Type**: `Object` <code> = {}</code>--HTTP headers in the following format:--```-{- Accept: 'text/html',- 'Content-Type': 'application/json'-}-```-------### `userData`--**Type**: `object` <code> = {}</code>--Custom user data assigned to the request. Use this to save any request related data to the request's scope, keeping them accessible on retries,-failures etc.-------### `keepUrlFragment`--**Type**: `boolean` <code> = false</code>--If `false` then the hash part of a URL is removed when computing the `uniqueKey` property. For example, this causes the `http://www.example.com#foo`-and `http://www.example.com#bar` URLs to have the same `uniqueKey` of `http://www.example.com` and thus the URLs are considered equal. Note that this-option only has an effect if `uniqueKey` is not set.-------### `useExtendedUniqueKey`--**Type**: `boolean` <code> = false</code>--If `true` then the `uniqueKey` is computed not only from the URL, but also from the method and payload properties. This is useful when making requests-to the same URL that are differentiated by method or payload, such as form submit navigations in browsers.-----diff --git a/docs/typedefs/RequestTransform.md b/docs/typedefs/RequestTransform.mddeleted file mode 100644index 7e151af04..000000000--- a/docs/typedefs/RequestTransform.md+++ /dev/null@@ -1,17 +0,0 @@-----id: request-transform-title: RequestTransform------<a name="requesttransform"></a>--**Returns**: [`RequestOptions`](/docs/typedefs/request-options) - The modified request options to enqueue.--Takes an Apify {RequestOptions} object and changes it's attributes in a desired way. This user-function is used-[`utils.enqueueLinks()`](/docs/api/utils#enqueuelinks) to modify requests before enqueuing them.--**Params**--- **`original`**: [`RequestOptions`](/docs/typedefs/request-options) - Request options to be modified.-----diff --git a/docs/typedefs/SessionOptions.md b/docs/typedefs/SessionOptions.mddeleted file mode 100644index 4a0b48c7e..000000000--- a/docs/typedefs/SessionOptions.md+++ /dev/null@@ -1,99 +0,0 @@-----id: session-options-title: SessionOptions------<a name="sessionoptions"></a>--## Properties--### `id`--**Type**: `string`--Id of session used for generating fingerprints. It is used as proxy session name.-------### `maxAgeSecs`--**Type**: `number` <code> = 3000</code>--Number of seconds after which the session is considered as expired.-------### `userData`--**Type**: `object`--Object where custom user data can be stored. For example custom headers.-------### `maxErrorScore`--**Type**: `number` <code> = 3</code>--Maximum number of marking session as blocked usage. If the `errorScore` reaches the `maxErrorScore` session is marked as block and it is thrown away.-It starts at 0. Calling the `markBad` function increases the `errorScore` by 1. Calling the `markGood` will decrease the `errorScore` by-`errorScoreDecrement`-------### `errorScoreDecrement`--**Type**: `number` <code> = 0.5</code>--It is used for healing the session. For example: if your session is marked bad two times, but it is successful on the third attempt it's errorScore is-decremented by this number.-------### `createdAt`--**Type**: `Date`--Date of creation.-------### `expiresAt`--**Type**: `Date`--Date of expiration.-------### `usageCount`--**Type**: `number` <code> = 0</code>--Indicates how many times the session has been used.-------### `errorCount`--**Type**: `number` <code> = 0</code>--Indicates how many times the session is marked bad.-------### `maxUsageCount`--**Type**: `number` <code> = 50</code>--Session should be used only a limited amount of times. This number indicates how many times the session is going to be used, before it is thrown away.-------### `sessionPool`--**Type**: [`SessionPool`](/docs/api/session-pool)--SessionPool instance. Session will emit the `sessionRetired` event on this instance.-----diff --git a/docs/typedefs/SessionPoolOptions.md b/docs/typedefs/SessionPoolOptions.mddeleted file mode 100644index 0beb142ff..000000000--- a/docs/typedefs/SessionPoolOptions.md+++ /dev/null@@ -1,48 +0,0 @@-----id: session-pool-options-title: SessionPoolOptions------<a name="sessionpooloptions"></a>--## Properties--### `maxPoolSize`--**Type**: `number` <code> = 1000</code>--Maximum size of the pool. Indicates how many sessions are rotated.-------### `sessionOptions`--**Type**: [`SessionOptions`](/docs/typedefs/session-options)--The configuration options for {Session} instances.-------### `persistStateKeyValueStoreId`--**Type**: `string`--Name or Id of `KeyValueStore` where is the `SessionPool` state stored.-------### `persistStateKey`--**Type**: `string` <code> = "\"SESSION_POOL_STATE\""</code>--Session pool persists it's state under this key in Key value store.-------### `createSessionFunction`--**Type**: [`CreateSession`](/docs/typedefs/create-session)--Custom function that should return `Session` instance. Function receives `SessionPool` instance as a parameter-----diff --git a/docs/typedefs/SessionState.md b/docs/typedefs/SessionState.mddeleted file mode 100644index 81f2743e8..000000000--- a/docs/typedefs/SessionState.md+++ /dev/null@@ -1,64 +0,0 @@-----id: session-state-title: SessionState------<a name="sessionstate"></a>--Persistable [`Session`](/docs/api/session) state.--## Properties--### `id`--**Type**: `string`-------### `cookieJar`--**Type**: `CookieJar`-------### `userData`--**Type**: `object`-------### `errorScore`--**Type**: `number`-------### `maxErrorScore`--**Type**: `number`-------### `errorScoreDecrement`--**Type**: `number`-------### `usageCount`--**Type**: `number`-------### `expiresAt`--**Type**: `string`-------### `createdAt`--**Type**: `string`-----diff --git a/docs/typedefs/SnapshotterOptions.md b/docs/typedefs/SnapshotterOptions.mddeleted file mode 100644index 70963c766..000000000--- a/docs/typedefs/SnapshotterOptions.md+++ /dev/null@@ -1,83 +0,0 @@-----id: snapshotter-options-title: SnapshotterOptions------<a name="snapshotteroptions"></a>--## Properties--### `eventLoopSnapshotIntervalSecs`--**Type**: `number` <code> = 0.5</code>--Defines the interval of measuring the event loop response time.-------### `clientSnapshotIntervalSecs`--**Type**: `number` <code> = 1</code>--Defines the interval of checking the current state of the remote API client.-------### `maxBlockedMillis`--**Type**: `number` <code> = 50</code>--Maximum allowed delay of the event loop in milliseconds. Exceeding this limit overloads the event loop.-------### `cpuSnapshotIntervalSecs`--**Type**: `number` <code> = 1</code>--Defines the interval of measuring CPU usage. This is only used when running locally. On the Apify platform, the statistics are provided externally at-a fixed interval.-------### `maxUsedCpuRatio`--**Type**: `number` <code> = 0.95</code>--Defines the maximum usage of CPU. Exceeding this limit overloads the CPU.-------### `memorySnapshotIntervalSecs`--**Type**: `number` <code> = 1</code>--Defines the interval of measuring memory consumption. This is only used when running locally. On the Apify platform, the statistics are provided-externally at a fixed interval. The measurement itself is resource intensive (25 - 50ms async). Therefore, setting this interval below 1 second is not-recommended.-------### `maxUsedMemoryRatio`--**Type**: `number` <code> = 0.7</code>--Defines the maximum ratio of total memory that can be used. Exceeding this limit overloads the memory.-------### `maxClientErrors`--**Type**: `number` <code> = 1</code>--Defines the maximum number of new rate limit errors within the given interval.-------### `snapshotHistorySecs`--**Type**: `number` <code> = 60</code>--Sets the interval in seconds for which a history of resource snapshots will be kept. Increasing this to very high numbers will affect performance.-----diff --git a/docs/typedefs/SocialHandles.md b/docs/typedefs/SocialHandles.mddeleted file mode 100644index 225b56f52..000000000--- a/docs/typedefs/SocialHandles.md+++ /dev/null@@ -1,73 +0,0 @@-----id: social-handles-title: SocialHandles------<a name="socialhandles"></a>--Representation of social handles parsed from a HTML page.--The object has the following structure:--```-{- emails: String[],- phones: String[],- phonesUncertain: String[],- linkedIns: String[],- twitters: String[],- instagrams: String[],- facebooks: String[],- youtubes: String[],-}-```--## Properties--### `emails`--**Type**: `Array<string>`-------### `phones`--**Type**: `Array<string>`-------### `phonesUncertain`--**Type**: `Array<string>`-------### `linkedIns`--**Type**: `Array<string>`-------### `twitters`--**Type**: `Array<string>`-------### `instagrams`--**Type**: `Array<string>`-------### `facebooks`--**Type**: `Array<string>`-------### `youtubes`--**Type**: `Array<string>`-----diff --git a/docs/typedefs/SourceInput.md b/docs/typedefs/SourceInput.mddeleted file mode 100644index 224a5fcdf..000000000--- a/docs/typedefs/SourceInput.md+++ /dev/null@@ -1,8 +0,0 @@-----id: source-input-title: SourceInput------<a name="sourceinput"></a>-----diff --git a/docs/typedefs/StealthOptions.md b/docs/typedefs/StealthOptions.mddeleted file mode 100644index 39ecf82c7..000000000--- a/docs/typedefs/StealthOptions.md+++ /dev/null@@ -1,91 +0,0 @@-----id: stealth-options-title: StealthOptions------<a name="stealthoptions"></a>--Configuration of stealth tricks for a proper hiding effect all of them should be set to true. These tricks are applied only when the `stealth` option-is set to `true`.--## Properties--### `addPlugins`--**Type**: `boolean` <code> = true</code>--If plugins should be added to the navigator.-------### `emulateWindowFrame`--**Type**: `boolean` <code> = true</code>--Emulates window Iframe.-------### `emulateWebGL`--**Type**: `boolean` <code> = true</code>--Emulates graphic card.-------### `emulateConsoleDebug`--**Type**: `boolean` <code> = true</code>--Emulates console.debug to return null.-------### `addLanguage`--**Type**: `boolean` <code> = true</code>--Adds languages to the navigator.-------### `hideWebDriver`--**Type**: `boolean` <code> = true</code>--Hides the webdriver by changing the navigator proto.-------### `hackPermissions`--**Type**: `boolean` <code> = true</code>--Fakes interaction with permissions.-------### `mockChrome`--**Type**: `boolean` <code> = true</code>--Adds the chrome runtime properties.-------### `mockChromeInIframe`--**Type**: `boolean` <code> = true</code>--Adds the chrome runtime properties inside the every newly created iframe.-------### `mockDeviceMemory`--**Type**: `boolean` <code> = true</code>--Sets device memory to other value than 0.-----diff --git a/docs/typedefs/SystemInfo.md b/docs/typedefs/SystemInfo.mddeleted file mode 100644index eebad09ea..000000000--- a/docs/typedefs/SystemInfo.md+++ /dev/null@@ -1,38 +0,0 @@-----id: system-info-title: SystemInfo------<a name="systeminfo"></a>--Represents the current status of the system.--## Properties--### `isSystemIdle`--**Type**: `boolean`--If true, system is being overloaded.-------### `memInfo`--**Type**: `object`--Memory-------### `eventLoopInfo`--**Type**: `object`-------### `cpuInfo`--**Type**: `object`-----diff --git a/docs/typedefs/SystemStatusOptions.md b/docs/typedefs/SystemStatusOptions.mddeleted file mode 100644index ffd10f479..000000000--- a/docs/typedefs/SystemStatusOptions.md+++ /dev/null@@ -1,56 +0,0 @@-----id: system-status-options-title: SystemStatusOptions------<a name="systemstatusoptions"></a>--## Properties--### `currentHistorySecs`--**Type**: `number` <code> = 5</code>--Defines max age of snapshots used in the [`SystemStatus.getCurrentStatus()`](/docs/api/system-status#getcurrentstatus) measurement.-------### `maxMemoryOverloadedRatio`--**Type**: `number` <code> = 0.2</code>--Sets the maximum ratio of overloaded snapshots in a memory sample. If the sample exceeds this ratio, the system will be overloaded.-------### `maxEventLoopOverloadedRatio`--**Type**: `number` <code> = 0.2</code>--Sets the maximum ratio of overloaded snapshots in an event loop sample. If the sample exceeds this ratio, the system will be overloaded.-------### `maxCpuOverloadedRatio`--**Type**: `number` <code> = 0.4</code>--Sets the maximum ratio of overloaded snapshots in a CPU sample. If the sample exceeds this ratio, the system will be overloaded.-------### `maxClientOverloadedRatio`--**Type**: `number` <code> = 0.2</code>--Sets the maximum ratio of overloaded snapshots in a Client sample. If the sample exceeds this ratio, the system will be overloaded.-------### `snapshotter`--**Type**: [`Snapshotter`](/docs/api/snapshotter)--The `Snapshotter` instance to be queried for `SystemStatus`.-----diff --git a/docs/typedefs/UserFunc.md b/docs/typedefs/UserFunc.mddeleted file mode 100644index b959c093e..000000000--- a/docs/typedefs/UserFunc.md+++ /dev/null@@ -1,10 +0,0 @@-----id: user-func-title: UserFunc------<a name="userfunc"></a>--**Returns**: `Promise<void>`-----diff --git a/package.json b/package.jsonindex 4815342a9..53758cc9e 100644--- a/package.json+++ b/package.json@@ -1,9 +1,9 @@{"name": "apify",- "version": "0.20.0",+ "version": "0.20.1","description": "The scalable web crawling and scraping library for JavaScript/Node.js. Enables development of data extraction and web automation jobs (not only) with headless Chrome and Puppeteer.","engines": {- "node": ">=10.17.0"+ "node": "^10.17.0 || ^12.3.0"},"main": "build/index.js","types": "types/index.d.ts",diff --git a/types/actor.d.ts b/types/actor.d.tsdeleted file mode 100644index 3fd116837..000000000--- a/types/actor.d.ts+++ /dev/null@@ -1,90 +0,0 @@-export function getEnv(): ApifyEnv;-export function main(userFunc: UserFunc): void;-export function call(actId: string, input?: any, options?: {- contentType?: string;- token?: string;- memoryMbytes?: number;- timeoutSecs?: number;- build?: string;- waitSecs?: string;- fetchOutput?: boolean;- disableBodyParser?: boolean;- webhooks?: any[];-} | undefined): Promise<ActorRun>;-export function callTask(taskId: string, input?: any, options?: {- contentType?: string;- token?: string;- memoryMbytes?: number;- timeoutSecs?: number;- build?: string;- waitSecs?: string;- webhooks?: any[];-} | undefined): Promise<ActorRun>;-export function metamorph(targetActorId: string, input?: any, options?: {- contentType?: string;- build?: string;-} | undefined): Promise<void>;-export function getApifyProxyUrl(options?: {- password?: string;- groups?: string[];- session?: string;- country?: string;-} | undefined): string;-export function addWebhook({ eventTypes, requestUrl, payloadTemplate, idempotencyKey }: {- eventTypes: string[];- requestUrl: string;- payloadTemplate?: string;- idempotencyKey?: string;-}): Promise<any>;-/**- * Parsed representation of the `APIFY_XXX` environmental variables.- */-export type ApifyEnv = {- /**- * ID of the actor (APIFY_ACTOR_ID)- */- actorId: string | null;- /**- * ID of the actor run (APIFY_ACTOR_RUN_ID)- */- actorRunId: string | null;- /**- * ID of the actor task (APIFY_ACTOR_TASK_ID)- */- actorTaskId: string | null;- /**- * ID of the user who started the actor - note that it might be- * different than the owner ofthe actor (APIFY_USER_ID)- */- userId: string | null;- /**- * Authentication token representing privileges given to the actor run,- * it can be passed to various Apify APIs (APIFY_TOKEN)- */- token: string | null;- /**- * Date when the actor was started (APIFY_STARTED_AT)- */- startedAt: Date | null;- /**- * Date when the actor will time out (APIFY_TIMEOUT_AT)- */- timeoutAt: Date | null;- /**- * ID of the key-value store where input and output data of this- * actor is stored (APIFY_DEFAULT_KEY_VALUE_STORE_ID)- */- defaultKeyValueStoreId: string | null;- /**- * ID of the dataset where input and output data of this- * actor is stored (APIFY_DEFAULT_DATASET_ID)- */- defaultDatasetId: string | null;- /**- * Amount of memory allocated for the actor,- * in megabytes (APIFY_MEMORY_MBYTES)- */- memoryMbytes: number | null;-};-export type UserFunc = () => Promise<void>;-import { ActorRun } from "./typedefs";diff --git a/types/autoscaling/autoscaled_pool.d.ts b/types/autoscaling/autoscaled_pool.d.tsdeleted file mode 100644index f321bb6f2..000000000--- a/types/autoscaling/autoscaled_pool.d.ts+++ /dev/null@@ -1,365 +0,0 @@-export default AutoscaledPool;-export type AutoscaledPoolOptions = {- /**- * A function that performs an asynchronous resource-intensive task.- * The function must either be labeled `async` or return a promise.- */- runTaskFunction: Function;- /**- * A function that indicates whether `runTaskFunction` should be called.- * This function is called every time there is free capacity for a new task and it should- * indicate whether it should start a new task or not by resolving to either `true` or `false`.- * Besides its obvious use, it is also useful for task throttling to save resources.- */- isTaskReadyFunction: Function;- /**- * A function that is called only when there are no tasks to be processed.- * If it resolves to `true` then the pool's run finishes. Being called only- * when there are no tasks being processed means that as long as `isTaskReadyFunction()`- * keeps resolving to `true`, `isFinishedFunction()` will never be called.- * To abort a run, use the {@link AutoscaledPool#abort} method.- */- isFinishedFunction: Function;- /**- * The minimum number of tasks running in parallel.- *- * *WARNING:* If you set this value too high with respect to the available system memory and CPU, your code might run extremely slow or crash.- * If you're not sure, just keep the default value and the concurrency will scale up automatically.- */- minConcurrency?: number;- /**- * The maximum number of tasks running in parallel.- */- maxConcurrency?: number;- /**- * The desired number of tasks that should be running parallel on the start of the pool,- * if there is a large enough supply of them.- * By default, it is `minConcurrency`.- */- desiredConcurrency?: number;- /**- * Minimum level of desired concurrency to reach before more scaling up is allowed.- */- desiredConcurrencyRatio?: number;- /**- * Defines the fractional amount of desired concurrency to be added with each scaling up.- * The minimum scaling step is one.- */- scaleUpStepRatio?: number;- /**- * Defines the amount of desired concurrency to be subtracted with each scaling down.- * The minimum scaling step is one.- */- scaleDownStepRatio?: number;- /**- * Indicates how often the pool should call the `runTaskFunction()` to start a new task, in seconds.- * This has no effect on starting new tasks immediately after a task completes.- */- maybeRunIntervalSecs?: number;- /**- * Specifies a period in which the instance logs its state, in seconds.- * Set to `null` to disable periodic logging.- */- loggingIntervalSecs?: number;- /**- * Defines in seconds how often the pool should attempt to adjust the desired concurrency- * based on the latest system status. Setting it lower than 1 might have a severe impact on performance.- * We suggest using a value from 5 to 20.- */- autoscaleIntervalSecs?: number;- /**- * Options to be passed down to the {@link Snapshotter} constructor. This is useful for fine-tuning- * the snapshot intervals and history.- */- snapshotterOptions?: SnapshotterOptions;- /**- * Options to be passed down to the {@link SystemStatus} constructor. This is useful for fine-tuning- * the system status reports. If a custom snapshotter is set in the options, it will be used- * by the pool.- */- systemStatusOptions?: SystemStatusOptions;-};-/**- * @typedef AutoscaledPoolOptions- * @property {Function} runTaskFunction- * A function that performs an asynchronous resource-intensive task.- * The function must either be labeled `async` or return a promise.- *- * @property {Function} isTaskReadyFunction- * A function that indicates whether `runTaskFunction` should be called.- * This function is called every time there is free capacity for a new task and it should- * indicate whether it should start a new task or not by resolving to either `true` or `false`.- * Besides its obvious use, it is also useful for task throttling to save resources.- *- * @property {Function} isFinishedFunction- * A function that is called only when there are no tasks to be processed.- * If it resolves to `true` then the pool's run finishes. Being called only- * when there are no tasks being processed means that as long as `isTaskReadyFunction()`- * keeps resolving to `true`, `isFinishedFunction()` will never be called.- * To abort a run, use the {@link AutoscaledPool#abort} method.- *- * @property {number} [minConcurrency=1]- * The minimum number of tasks running in parallel.- *- * *WARNING:* If you set this value too high with respect to the available system memory and CPU, your code might run extremely slow or crash.- * If you're not sure, just keep the default value and the concurrency will scale up automatically.- * @property {number} [maxConcurrency=1000]- * The maximum number of tasks running in parallel.- * @property {number} [desiredConcurrency]- * The desired number of tasks that should be running parallel on the start of the pool,- * if there is a large enough supply of them.- * By default, it is `minConcurrency`.- * @property {number} [desiredConcurrencyRatio=0.95]- * Minimum level of desired concurrency to reach before more scaling up is allowed.- * @property {number} [scaleUpStepRatio=0.05]- * Defines the fractional amount of desired concurrency to be added with each scaling up.- * The minimum scaling step is one.- * @property {number} [scaleDownStepRatio=0.05]- * Defines the amount of desired concurrency to be subtracted with each scaling down.- * The minimum scaling step is one.- * @property {number} [maybeRunIntervalSecs=0.5]- * Indicates how often the pool should call the `runTaskFunction()` to start a new task, in seconds.- * This has no effect on starting new tasks immediately after a task completes.- * @property {number} [loggingIntervalSecs=60]- * Specifies a period in which the instance logs its state, in seconds.- * Set to `null` to disable periodic logging.- * @property {number} [autoscaleIntervalSecs=10]- * Defines in seconds how often the pool should attempt to adjust the desired concurrency- * based on the latest system status. Setting it lower than 1 might have a severe impact on performance.- * We suggest using a value from 5 to 20.- * @property {SnapshotterOptions} [snapshotterOptions]- * Options to be passed down to the {@link Snapshotter} constructor. This is useful for fine-tuning- * the snapshot intervals and history.- * @property {SystemStatusOptions} [systemStatusOptions]- * Options to be passed down to the {@link SystemStatus} constructor. This is useful for fine-tuning- * the system status reports. If a custom snapshotter is set in the options, it will be used- * by the pool.- */-/**- * Manages a pool of asynchronous resource-intensive tasks that are executed in parallel.- * The pool only starts new tasks if there is enough free CPU and memory available- * and the Javascript event loop is not blocked.- *- * The information about the CPU and memory usage is obtained by the {@link Snapshotter} class,- * which makes regular snapshots of system resources that may be either local- * or from the Apify cloud infrastructure in case the process is running on the Apify platform.- * Meaningful data gathered from these snapshots is provided to `AutoscaledPool` by the {@link SystemStatus} class.- *- * Before running the pool, you need to implement the following three functions:- * {@link AutoscaledPoolOptions#runTaskFunction},- * {@link AutoscaledPoolOptions#isTaskReadyFunction} and- * {@link AutoscaledPoolOptions#isFinishedFunction}.- *- * The auto-scaled pool is started by calling the {@link AutoscaledPool#run} function.- * The pool periodically queries the {@link AutoscaledPoolOptions#isTaskReadyFunction} function- * for more tasks, managing optimal concurrency, until the function resolves to `false`. The pool then queries- * the {@link AutoscaledPoolOptions#isFinishedFunction}. If it resolves to `true`, the run finishes after all running tasks complete.- * If it resolves to `false`, it assumes there will be more tasks available later and keeps periodically querying for tasks.- * If any of the tasks throws then the {@link AutoscaledPool#run} function rejects the promise with an error.- *- * The pool evaluates whether it should start a new task every time one of the tasks finishes- * and also in the interval set by the `options.maybeRunIntervalSecs` parameter.- *- * **Example usage:**- *- * ```javascript- * const pool = new Apify.AutoscaledPool({- * maxConcurrency: 50,- * runTaskFunction: async () => {- * // Run some resource-intensive asynchronous operation here.- * },- * isTaskReadyFunction: async () => {- * // Tell the pool whether more tasks are ready to be processed.- * // Return true or false- * },- * isFinishedFunction: async () => {- * // Tell the pool whether it should finish- * // or wait for more tasks to become available.- * // Return true or false- * }- * });- *- * await pool.run();- * ```- */-declare class AutoscaledPool {- /**- * @param {AutoscaledPoolOptions} options All `AutoscaledPool` configuration options.- */- constructor(options?: AutoscaledPoolOptions);- desiredConcurrencyRatio: any;- scaleUpStepRatio: any;- scaleDownStepRatio: any;- maybeRunIntervalMillis: number;- loggingIntervalMillis: number;- autoscaleIntervalMillis: number;- runTaskFunction: any;- isFinishedFunction: any;- isTaskReadyFunction: any;- _minConcurrency: any;- _maxConcurrency: any;- _desiredConcurrency: any;- _currentConcurrency: number;- isStopped: boolean;- lastLoggingTime: number;- resolve: ((value?: any) => void) | null;- reject: ((reason?: any) => void) | null;- /**- * Gets called every autoScaleIntervalSecs and evaluates the current system status.- * If the system IS NOT overloaded and the settings allow it, it scales up.- * If the system IS overloaded and the settings allow it, it scales down.- *- * @ignore- */- _autoscale(intervalCallback: any): any;- /**- * Starts a new task- * if the number of running tasks (current concurrency) is lower than desired concurrency- * and the system is not currently overloaded- * and this.isTaskReadyFunction() returns true.- *- * It doesn't allow multiple concurrent runs of this method.- *- * @ignore- */- _maybeRunTask(intervalCallback: any): Promise<void>;- snapshotter: any;- systemStatus: SystemStatus;- /**- * @ignore- */- setMaxConcurrency(maxConcurrency: any): void;- /**- * @ignore- */- setMinConcurrency(minConcurrency: any): void;- /**- * Sets the minimum number of tasks running in parallel.- *- * *WARNING:* If you set this value too high with respect to the available system memory and CPU, your code might run extremely slow or crash.- * If you're not sure, just keep the default value and the concurrency will scale up automatically.- *- * @param {number} value- */- set minConcurrency(arg: number);- /**- * Gets the minimum number of tasks running in parallel.- *- * @return {number}- */- get minConcurrency(): number;- /**- * Sets the maximum number of tasks running in parallel.- *- * @param {number} value- */- set maxConcurrency(arg: number);- /**- * Gets the maximum number of tasks running in parallel.- *- * @return {number}- */- get maxConcurrency(): number;- /**- * Sets the desired concurrency for the pool, i.e. the number of tasks that should be running- * in parallel if there's large enough supply of tasks.- *- * @param {number} value- */- set desiredConcurrency(arg: number);- /**- * Gets the desired concurrency for the pool,- * which is an estimated number of parallel tasks that the system can currently support.- *- * @return {number}- */- get desiredConcurrency(): number;- /**- * Gets the the number of parallel tasks currently running in the pool.- *- * @return {number}- */- get currentConcurrency(): number;- /**- * Runs the auto-scaled pool. Returns a promise that gets resolved or rejected once- * all the tasks are finished or one of them fails.- *- * @return {Promise<void>}- */- run(): Promise<void>;- poolPromise: Promise<any> | undefined;- autoscaleInterval: any;- maybeRunInterval: any;- /**- * Aborts the run of the auto-scaled pool and destroys it. The promise returned from- * the {@link AutoscaledPool#run} function will immediately resolve, no more new tasks- * will be spawned and all running tasks will be left in their current state.- *- * Due to the nature of the tasks, auto-scaled pool cannot reliably guarantee abortion- * of all the running tasks, therefore, no abortion is attempted and some of the tasks- * may finish, while others may not. Essentially, auto-scaled pool doesn't care about- * their state after the invocation of `.abort()`, but that does not mean that some- * parts of their asynchronous chains of commands will not execute.- *- * @return {Promise<void>}- */- abort(): Promise<void>;- /**- * Prevents the auto-scaled pool from starting new tasks, but allows the running ones to finish- * (unlike abort, which terminates them). Used together with {@link AutoscaledPool#resume}- *- * The function's promise will resolve once all running tasks have completed and the pool- * is effectively idle. If the `timeoutSecs` argument is provided, the promise will reject- * with a timeout error after the `timeoutSecs` seconds.- *- * The promise returned from the {@link AutoscaledPool#run} function will not resolve- * when `.pause()` is invoked (unlike abort, which resolves it).- *- * @param {number} [timeoutSecs]- * @return {Promise<void>}- */- pause(timeoutSecs?: number | undefined): Promise<void>;- /**- * Resumes the operation of the autoscaled-pool by allowing more tasks to be run.- * Used together with {@link AutoscaledPool#pause}- *- * Tasks will automatically start running again in `options.maybeRunIntervalSecs`.- */- resume(): void;- queryingIsTaskReady: boolean | undefined;- /**- * Scales the pool up by increasing- * the desired concurrency by the scaleUpStepRatio.- *- * @param {Object} systemStatus for logging- * @ignore- */- _scaleUp(systemStatus: Object): void;- /**- * Scales the pool down by decreasing- * the desired concurrency by the scaleDownStepRatio.- *- * @param {Object} systemStatus for logging- * @ignore- */- _scaleDown(systemStatus: Object): void;- /**- * If there are no running tasks and this.isFinishedFunction() returns true then closes- * the pool and resolves the pool's promise returned by the run() method.- *- * It doesn't allow multiple concurrent runs of this method.- *- * @ignore- */- _maybeFinish(): Promise<void>;- queryingIsFinished: boolean | undefined;- /**- * Cleans up resources.- *- * @ignore- */- _destroy(): Promise<void>;-}-import { SnapshotterOptions } from "./snapshotter";-import { SystemStatusOptions } from "./system_status";-import SystemStatus from "./system_status";diff --git a/types/autoscaling/snapshotter.d.ts b/types/autoscaling/snapshotter.d.tsdeleted file mode 100644index 378adcc9c..000000000--- a/types/autoscaling/snapshotter.d.ts+++ /dev/null@@ -1,249 +0,0 @@-export default Snapshotter;-export type SnapshotterOptions = {- /**- * Defines the interval of measuring the event loop response time.- */- eventLoopSnapshotIntervalSecs?: number;- /**- * Defines the interval of checking the current state- * of the remote API client.- */- clientSnapshotIntervalSecs?: number;- /**- * Maximum allowed delay of the event loop in milliseconds.- * Exceeding this limit overloads the event loop.- */- maxBlockedMillis?: number;- /**- * Defines the interval of measuring CPU usage.- * This is only used when running locally. On the Apify platform,- * the statistics are provided externally at a fixed interval.- */- cpuSnapshotIntervalSecs?: number;- /**- * Defines the maximum usage of CPU.- * Exceeding this limit overloads the CPU.- */- maxUsedCpuRatio?: number;- /**- * Defines the interval of measuring memory consumption.- * This is only used when running locally. On the Apify platform,- * the statistics are provided externally at a fixed interval.- * The measurement itself is resource intensive (25 - 50ms async).- * Therefore, setting this interval below 1 second is not recommended.- */- memorySnapshotIntervalSecs?: number;- /**- * Defines the maximum ratio of total memory that can be used.- * Exceeding this limit overloads the memory.- */- maxUsedMemoryRatio?: number;- /**- * Defines the maximum number of new rate limit errors within- * the given interval.- */- maxClientErrors?: number;- /**- * Sets the interval in seconds for which a history of resource snapshots- * will be kept. Increasing this to very high numbers will affect performance.- */- snapshotHistorySecs?: number;-};-/**- * @typedef SnapshotterOptions- * @property {number} [eventLoopSnapshotIntervalSecs=0.5]- * Defines the interval of measuring the event loop response time.- * @property {number} [clientSnapshotIntervalSecs=1]- * Defines the interval of checking the current state- * of the remote API client.- * @property {number} [maxBlockedMillis=50]- * Maximum allowed delay of the event loop in milliseconds.- * Exceeding this limit overloads the event loop.- * @property {number} [cpuSnapshotIntervalSecs=1]- * Defines the interval of measuring CPU usage.- * This is only used when running locally. On the Apify platform,- * the statistics are provided externally at a fixed interval.- * @property {number} [maxUsedCpuRatio=0.95]- * Defines the maximum usage of CPU.- * Exceeding this limit overloads the CPU.- * @property {number} [memorySnapshotIntervalSecs=1]- * Defines the interval of measuring memory consumption.- * This is only used when running locally. On the Apify platform,- * the statistics are provided externally at a fixed interval.- * The measurement itself is resource intensive (25 - 50ms async).- * Therefore, setting this interval below 1 second is not recommended.- * @property {number} [maxUsedMemoryRatio=0.7]- * Defines the maximum ratio of total memory that can be used.- * Exceeding this limit overloads the memory.- * @property {number} [maxClientErrors=1]- * Defines the maximum number of new rate limit errors within- * the given interval.- * @property {number} [snapshotHistorySecs=60]- * Sets the interval in seconds for which a history of resource snapshots- * will be kept. Increasing this to very high numbers will affect performance.- */-/**- * Creates snapshots of system resources at given intervals and marks the resource- * as either overloaded or not during the last interval. Keeps a history of the snapshots.- * It tracks the following resources: Memory, EventLoop, API and CPU.- * The class is used by the {@link AutoscaledPool} class.- *- * When running on the Apify platform, the CPU and memory statistics are provided by the platform,- * as collected from the running Docker container. When running locally, `Snapshotter`- * makes its own statistics by querying the OS.- *- * CPU becomes overloaded locally when its current use exceeds the `maxUsedCpuRatio` option or- * when Apify platform marks it as overloaded.- *- * Memory becomes overloaded if its current use exceeds the `maxUsedMemoryRatio` option.- * It's computed using the total memory available to the container when running on- * the Apify platform and a quarter of total system memory when running locally.- * Max total memory when running locally may be overridden by using the `APIFY_MEMORY_MBYTES`- * environment variable.- *- * Event loop becomes overloaded if it slows down by more than the `maxBlockedMillis` option.- *- * Client becomes overloaded when rate limit errors (429 - Too Many Requests),- * typically received from the request queue, exceed the set limit within the set interval.- */-declare class Snapshotter {- /**- * @param {SnapshotterOptions} [options] All `Snapshotter` configuration options.- */- constructor(options?: SnapshotterOptions | undefined);- eventLoopSnapshotIntervalMillis: number;- memorySnapshotIntervalMillis: number;- clientSnapshotIntervalMillis: number;- cpuSnapshotIntervalMillis: number;- snapshotHistoryMillis: number;- maxBlockedMillis: any;- maxUsedMemoryRatio: any;- maxUsedCpuRatio: any;- maxClientErrors: any;- maxMemoryBytes: number | null;- cpuSnapshots: any[];- eventLoopSnapshots: any[];- memorySnapshots: any[];- clientSnapshots: any[];- eventLoopInterval: any;- memoryInterval: any;- clientInterval: any;- cpuInterval: any;- lastLoggedCriticalMemoryOverloadAt: Date | null;- /**- * Creates a snapshot of current CPU usage- * using the Apify platform `systemInfo` event.- * @param {Object} systemInfo- * @ignore- */- _snapshotCpuOnPlatform(systemInfo: Object): void;- /**- * Creates a snapshot of current memory usage- * using the Apify platform `systemInfo` event.- * @param {*} systemInfo- * @ignore- */- _snapshotMemoryOnPlatform(systemInfo: any): void;- /**- * Starts capturing snapshots at configured intervals.- * @return {Promise<void>}- */- start(): Promise<void>;- /**- * Stops all resource capturing.- * @return {Promise<void>}- */- stop(): Promise<void>;- /**- * Returns a sample of latest memory snapshots, with the size of the sample defined- * by the sampleDurationMillis parameter. If omitted, it returns a full snapshot history.- * @param {number} [sampleDurationMillis]- * @return {Array<*>}- */- getMemorySample(sampleDurationMillis?: number | undefined): any[];- /**- * Returns a sample of latest event loop snapshots, with the size of the sample defined- * by the sampleDurationMillis parameter. If omitted, it returns a full snapshot history.- * @param {number} [sampleDurationMillis]- * @return {Array<*>}- */- getEventLoopSample(sampleDurationMillis?: number | undefined): any[];- /**- * Returns a sample of latest CPU snapshots, with the size of the sample defined- * by the sampleDurationMillis parameter. If omitted, it returns a full snapshot history.- * @param {number} [sampleDurationMillis]- * @return {Array<*>}- */- getCpuSample(sampleDurationMillis?: number | undefined): any[];- /**- * Returns a sample of latest Client snapshots, with the size of the sample defined- * by the sampleDurationMillis parameter. If omitted, it returns a full snapshot history.- * @param {number} sampleDurationMillis- * @return {Array<*>}- */- getClientSample(sampleDurationMillis: number): any[];- /**- * Finds the latest snapshots by sampleDurationMillis in the provided array.- * @param {Array<*>} snapshots- * @param {number} [sampleDurationMillis]- * @return {Array<*>}- * @ignore- */- _getSample(snapshots: any[], sampleDurationMillis?: number | undefined): any[];- /**- * Creates a snapshot of current memory usage- * using the Apify platform `systemInfo` event.- * @param {Function} intervalCallback- * @return {Promise<void>}- * @ignore- */- _snapshotMemoryOnLocal(intervalCallback: Function): Promise<void>;- /**- * Checks for critical memory overload and logs it to the console.- * @param {*} systemInfo- * @ignore- */- _memoryOverloadWarning({ memCurrentBytes }: any): void;- /**- * Creates a snapshot of current event loop delay.- * @param {Function} intervalCallback- * @ignore- */- _snapshotEventLoop(intervalCallback: Function): void;- /**- * Creates a snapshot of current CPU usage- * using OS provided metrics.- * @param {Function} intervalCallback- * @ignore- */- _snapshotCpuOnLocal(intervalCallback: Function): void;- _getCurrentCpuTicks(): {- idle: number;- total: number;- };- /**- * Creates a snapshot of current API state by checking for- * rate limit errors. Only errors produced by a 2nd retry- * of the API call are considered for snapshotting since- * earlier errors may just be caused by a random spike in- * number of requests and do not necessarily signify API- * overloading.- *- * @param intervalCallback- * @private- */- _snapshotClient(intervalCallback: any): void;- /**- * Removes snapshots that are older than the snapshotHistorySecs option- * from the array (destructively - in place).- * @param {Array<*>} snapshots- * @param {Date} now- * @ignore- */- _pruneSnapshots(snapshots: any[], now: Date): void;- /**- * Calculate max memory for platform or local usage.- * @ignore- */- _ensureCorrectMaxMemory(): Promise<void>;-}diff --git a/types/autoscaling/system_status.d.ts b/types/autoscaling/system_status.d.tsdeleted file mode 100644index 01bdd488e..000000000--- a/types/autoscaling/system_status.d.ts+++ /dev/null@@ -1,205 +0,0 @@-export default SystemStatus;-/**- * Represents the current status of the system.- */-export type SystemInfo = {- /**- * If true, system is being overloaded.- */- isSystemIdle: boolean;- /**- * Memory- */- memInfo: any;- eventLoopInfo: any;- cpuInfo: any;-};-export type SystemStatusOptions = {- /**- * Defines max age of snapshots used in the- * {@link SystemStatus#getCurrentStatus} measurement.- */- currentHistorySecs?: number;- /**- * Sets the maximum ratio of overloaded snapshots in a memory sample.- * If the sample exceeds this ratio, the system will be overloaded.- */- maxMemoryOverloadedRatio?: number;- /**- * Sets the maximum ratio of overloaded snapshots in an event loop sample.- * If the sample exceeds this ratio, the system will be overloaded.- */- maxEventLoopOverloadedRatio?: number;- /**- * Sets the maximum ratio of overloaded snapshots in a CPU sample.- * If the sample exceeds this ratio, the system will be overloaded.- */- maxCpuOverloadedRatio?: number;- /**- * Sets the maximum ratio of overloaded snapshots in a Client sample.- * If the sample exceeds this ratio, the system will be overloaded.- */- maxClientOverloadedRatio?: number;- /**- * The `Snapshotter` instance to be queried for `SystemStatus`.- */- snapshotter?: Snapshotter;-};-/**- * Represents the current status of the system.- *- * @typedef SystemInfo- * @property {boolean} isSystemIdle- * If true, system is being overloaded.- * @property {object} memInfo- * Memory- * @property {object} eventLoopInfo- * @property {object} cpuInfo- */-/**- * @typedef SystemStatusOptions- * @property {number} [currentHistorySecs=5]- * Defines max age of snapshots used in the- * {@link SystemStatus#getCurrentStatus} measurement.- * @property {number} [maxMemoryOverloadedRatio=0.2]- * Sets the maximum ratio of overloaded snapshots in a memory sample.- * If the sample exceeds this ratio, the system will be overloaded.- * @property {number} [maxEventLoopOverloadedRatio=0.2]- * Sets the maximum ratio of overloaded snapshots in an event loop sample.- * If the sample exceeds this ratio, the system will be overloaded.- * @property {number} [maxCpuOverloadedRatio=0.4]- * Sets the maximum ratio of overloaded snapshots in a CPU sample.- * If the sample exceeds this ratio, the system will be overloaded.- * @property {number} [maxClientOverloadedRatio=0.2]- * Sets the maximum ratio of overloaded snapshots in a Client sample.- * If the sample exceeds this ratio, the system will be overloaded.- * @property {Snapshotter} [snapshotter]- * The `Snapshotter` instance to be queried for `SystemStatus`.- */-/**- * Provides a simple interface to reading system status from a {@link Snapshotter} instance.- * It only exposes two functions {@link SystemStatus#getCurrentStatus}- * and {@link SystemStatus#getHistoricalStatus}.- * The system status is calculated using a weighted average of overloaded- * messages in the snapshots, with the weights being the time intervals- * between the snapshots. Each resource is calculated separately- * and the system is overloaded whenever at least one resource is overloaded.- * The class is used by the {@link AutoscaledPool} class.- *- * {@link SystemStatus#getCurrentStatus}- * returns a boolean that represents the current status of the system.- * The length of the current timeframe in seconds is configurable- * by the `currentHistorySecs` option and represents the max age- * of snapshots to be considered for the calculation.- *- * {@link SystemStatus#getHistoricalStatus}- * returns a boolean that represents the long-term status- * of the system. It considers the full snapshot history available- * in the {@link Snapshotter} instance.- */-declare class SystemStatus {- /**- * @param {SystemStatusOptions} [options] All `SystemStatus` configuration options.- */- constructor(options?: SystemStatusOptions | undefined);- currentHistorySecs: number;- maxMemoryOverloadedRatio: any;- maxEventLoopOverloadedRatio: any;- maxCpuOverloadedRatio: any;- maxClientOverloadedRatio: any;- snapshotter: any;- /**- * Returns an {@link SystemInfo} object with the following structure:- *- * ```javascript- * {- * isSystemIdle: Boolean,- * memInfo: Object,- * eventLoopInfo: Object,- * cpuInfo: Object- * }- * ```- *- * Where the `isSystemIdle` property is set to `false` if the system- * has been overloaded in the last `options.currentHistorySecs` seconds,- * and `true` otherwise.- * @return {SystemInfo}- */- getCurrentStatus(): SystemInfo;- /**- * Returns an {@link SystemInfo} object with the following structure:- *- * ```javascript- * {- * isSystemIdle: Boolean,- * memInfo: Object,- * eventLoopInfo: Object,- * cpuInfo: Object- * }- * ```- *- * Where the `isSystemIdle` property is set to `false` if the system- * has been overloaded in the full history of the {@link Snapshotter}- * (which is configurable in the {@link Snapshotter}) and `true` otherwise.- * @return {SystemInfo}- */- getHistoricalStatus(): SystemInfo;- /**- * Returns a system status object.- *- * @param {number} [sampleDurationMillis]- * @return {SystemInfo}- * @ignore- */- _isSystemIdle(sampleDurationMillis?: number | undefined): SystemInfo;- /**- * Returns an object with an isOverloaded property set to true- * if the memory has been overloaded in the last sampleDurationMillis.- *- * @param {number} sampleDurationMillis- * @return {object}- * @ignore- */- _isMemoryOverloaded(sampleDurationMillis: number): any;- /**- * Returns an object with an isOverloaded property set to true- * if the event loop has been overloaded in the last sampleDurationMillis.- *- * @param {number} sampleDurationMillis- * @return {object}- * @ignore- */- _isEventLoopOverloaded(sampleDurationMillis: number): any;- /**- * Returns an object with an isOverloaded property set to true- * if the CPU has been overloaded in the last sampleDurationMillis.- *- * @param {number} sampleDurationMillis- * @return {object}- * @ignore- */- _isCpuOverloaded(sampleDurationMillis: number): any;- /**- * Returns an object with an isOverloaded property set to true- * if the client has been overloaded in the last sampleDurationMillis.- * @param {number} sampleDurationMillis- * @return {{isOverloaded: boolean, maxOverloadedRatio: number, actualRatio: number}}- * @private- */- _isClientOverloaded(sampleDurationMillis: number): {- isOverloaded: boolean;- maxOverloadedRatio: number;- actualRatio: number;- };- /**- * Returns an object with sample information and an isOverloaded property- * set to true if at least the ratio of snapshots in the sample are overloaded.- *- * @param {Array<*>} sample- * @param {number} ratio- * @return {object}- * @ignore- */- _isSampleOverloaded(sample: any[], ratio: number): any;-}-import Snapshotter from "./snapshotter";diff --git a/types/constants.d.ts b/types/constants.d.tsdeleted file mode 100644index f1ba61070..000000000--- a/types/constants.d.ts+++ /dev/null@@ -1,41 +0,0 @@-/**- * The default user agent used by `Apify.launchPuppeteer`.- * Last updated on 2018-12-30.- */-export const DEFAULT_USER_AGENT: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.87 Safari/537.36";-export namespace EXIT_CODES {- export const SUCCESS: number;- export const ERROR_USER_FUNCTION_THREW: number;- export const ERROR_UNKNOWN: number;-}-/**- * These events are just internal for Apify package, so we don't need them in apify-shared package.- *- * @type {{CPU_INFO: string, SYSTEM_INFO: string, MIGRATING: string, PERSIST_STATE: string}}- */-export const ACTOR_EVENT_NAMES_EX: {- CPU_INFO: string;- SYSTEM_INFO: string;- MIGRATING: string;- PERSIST_STATE: string;-};-/**- * Most common user agents from https://techblog.willshouse.com/2012/01/03/most-common-user-agents/- *- * Last updated on 2019-02-18.- */-export const USER_AGENT_LIST: string[];-/**- * Base URL of Apify's API endpoints.- * @type {string}- */-export const APIFY_API_BASE_URL: string;-/**- * Multiplier used in CheerioCrawler and PuppeteerCrawler to set a reasonable- * handleRequestTimeoutSecs in BasicCrawler that would not impare functionality.- *- * @type {number}- */-export const BASIC_CRAWLER_TIMEOUT_MULTIPLIER: number;-export const COUNTRY_CODE_REGEX: RegExp;-export const STATUS_CODES_BLOCKED: number[];diff --git a/types/crawlers/basic_crawler.d.ts b/types/crawlers/basic_crawler.d.tsdeleted file mode 100644index 234184aed..000000000--- a/types/crawlers/basic_crawler.d.ts+++ /dev/null@@ -1,342 +0,0 @@-export default BasicCrawler;-export type BasicCrawlerOptions = {- /**- * User-provided function that performs the logic of the crawler. It is called for each URL to crawl.- *- * The function receives the following object as an argument:- * ```- * {- * request: Request,- * autoscaledPool: AutoscaledPool- * }- * ```- * where the {@link Request} instance represents the URL to crawl.- *- * The function must return a promise, which is then awaited by the crawler.- *- * If the function throws an exception, the crawler will try to re-crawl the- * request later, up to `option.maxRequestRetries` times.- * If all the retries fail, the crawler calls the function- * provided to the `handleFailedRequestFunction` parameter.- * To make this work, you should **always**- * let your function throw exceptions rather than catch them.- * The exceptions are logged to the request using the- * {@link Request#pushErrorMessage} function.- */- handleRequestFunction: HandleRequest;- /**- * Static list of URLs to be processed.- * Either `requestList` or `requestQueue` option must be provided (or both).- */- requestList?: RequestList;- /**- * Dynamic queue of URLs to be processed. This is useful for recursive crawling of websites.- * Either `requestList` or `requestQueue` option must be provided (or both).- */- requestQueue?: RequestQueue;- /**- * Timeout in which the function passed as `handleRequestFunction` needs to finish, in seconds.- */- handleRequestTimeoutSecs?: number;- /**- * A function to handle requests that failed more than `option.maxRequestRetries` times.- *- * The function receives the following object as an argument:- * ```- * {- * request: Request,- * error: Error,- * }- * ```- * where the {@link Request} instance corresponds to the failed request, and the `Error` instance- * represents the last error thrown during processing of the request.- *- * See- * [source code](https://github.com/apifytech/apify-js/blob/master/src/crawlers/basic_crawler.js#L11)- * for the default implementation of this function.- */- handleFailedRequestFunction?: HandleFailedRequest;- /**- * Indicates how many times the request is retried if {@link BasicCrawlerOptions.handleRequestFunction} fails.- */- maxRequestRetries?: number;- /**- * Maximum number of pages that the crawler will open. The crawl will stop when this limit is reached.- * Always set this value in order to prevent infinite loops in misconfigured crawlers.- * Note that in cases of parallel crawling, the actual number of pages visited might be slightly higher than this value.- */- maxRequestsPerCrawl?: number;- /**- * Custom options passed to the underlying {@link AutoscaledPool} constructor.- * Note that the `runTaskFunction` and `isTaskReadyFunction` options- * are provided by `BasicCrawler` and cannot be overridden.- * However, you can provide a custom implementation of `isFinishedFunction`.- */- autoscaledPoolOptions?: AutoscaledPoolOptions;- /**- * Sets the minimum concurrency (parallelism) for the crawl. Shortcut to the corresponding {@link AutoscaledPool} option.- *- * *WARNING:* If you set this value too high with respect to the available system memory and CPU, your crawler will run extremely slow or crash.- * If you're not sure, just keep the default value and the concurrency will scale up automatically.- */- minConcurrency?: number;- /**- * Sets the maximum concurrency (parallelism) for the crawl. Shortcut to the corresponding {@link AutoscaledPool} option.- */- maxConcurrency?: number;- /**- * If set to true. Basic crawler will initialize the {@link SessionPool} with the corresponding `sessionPoolOptions`.- * The session instance will be than available in the `handleRequestFunction`.- */- useSessionPool?: boolean;- /**- * The configuration options for {SessionPool} to use.- */- sessionPoolOptions?: SessionPoolOptions;-};-export type HandleRequest = (inputs: HandleRequestInputs) => Promise<void>;-export type HandleRequestInputs = {- /**- * The original {Request} object.- */- request: Request;- /**- * A reference to the underlying {@link AutoscaledPool} class that manages the concurrency of the crawler.- * Note that this property is only initialized after calling the {@link BasicCrawler#run} function.- * You can use it to change the concurrency settings on the fly,- * to pause the crawler by calling {@link AutoscaledPool#pause}- * or to abort it by calling {@link AutoscaledPool#abort}.- */- autoscaledPool: AutoscaledPool;- session?: Session;-};-export type HandleFailedRequest = (inputs: HandleFailedRequestInput) => void | Promise<void>;-export type HandleFailedRequestInput = {- /**- * The original {Request} object.- */- request: Request;- /**- * The Error thrown by `handleRequestFunction`.- */- error: Error;-};-/**- * @typedef BasicCrawlerOptions- * @property {HandleRequest} handleRequestFunction- * User-provided function that performs the logic of the crawler. It is called for each URL to crawl.- *- * The function receives the following object as an argument:- * ```- * {- * request: Request,- * autoscaledPool: AutoscaledPool- * }- * ```- * where the {@link Request} instance represents the URL to crawl.- *- * The function must return a promise, which is then awaited by the crawler.- *- * If the function throws an exception, the crawler will try to re-crawl the- * request later, up to `option.maxRequestRetries` times.- * If all the retries fail, the crawler calls the function- * provided to the `handleFailedRequestFunction` parameter.- * To make this work, you should **always**- * let your function throw exceptions rather than catch them.- * The exceptions are logged to the request using the- * {@link Request#pushErrorMessage} function.- * @property {RequestList} [requestList]- * Static list of URLs to be processed.- * Either `requestList` or `requestQueue` option must be provided (or both).- * @property {RequestQueue} [requestQueue]- * Dynamic queue of URLs to be processed. This is useful for recursive crawling of websites.- * Either `requestList` or `requestQueue` option must be provided (or both).- * @property {number} [handleRequestTimeoutSecs=60]- * Timeout in which the function passed as `handleRequestFunction` needs to finish, in seconds.- * @property {HandleFailedRequest} [handleFailedRequestFunction]- * A function to handle requests that failed more than `option.maxRequestRetries` times.- *- * The function receives the following object as an argument:- * ```- * {- * request: Request,- * error: Error,- * }- * ```- * where the {@link Request} instance corresponds to the failed request, and the `Error` instance- * represents the last error thrown during processing of the request.- *- * See- * [source code](https://github.com/apifytech/apify-js/blob/master/src/crawlers/basic_crawler.js#L11)- * for the default implementation of this function.- * @property {number} [maxRequestRetries=3]- * Indicates how many times the request is retried if {@link BasicCrawlerOptions.handleRequestFunction} fails.- * @property {number} [maxRequestsPerCrawl]- * Maximum number of pages that the crawler will open. The crawl will stop when this limit is reached.- * Always set this value in order to prevent infinite loops in misconfigured crawlers.- * Note that in cases of parallel crawling, the actual number of pages visited might be slightly higher than this value.- * @property {AutoscaledPoolOptions} [autoscaledPoolOptions]- * Custom options passed to the underlying {@link AutoscaledPool} constructor.- * Note that the `runTaskFunction` and `isTaskReadyFunction` options- * are provided by `BasicCrawler` and cannot be overridden.- * However, you can provide a custom implementation of `isFinishedFunction`.- * @property {number} [minConcurrency=1]- * Sets the minimum concurrency (parallelism) for the crawl. Shortcut to the corresponding {@link AutoscaledPool} option.- *- * *WARNING:* If you set this value too high with respect to the available system memory and CPU, your crawler will run extremely slow or crash.- * If you're not sure, just keep the default value and the concurrency will scale up automatically.- * @property {number} [maxConcurrency=1000]- * Sets the maximum concurrency (parallelism) for the crawl. Shortcut to the corresponding {@link AutoscaledPool} option.- * @property {boolean} [useSessionPool=false]- * If set to true. Basic crawler will initialize the {@link SessionPool} with the corresponding `sessionPoolOptions`.- * The session instance will be than available in the `handleRequestFunction`.- * @property {SessionPoolOptions} [sessionPoolOptions] The configuration options for {SessionPool} to use.- */-/**- * Provides a simple framework for parallel crawling of web pages.- * The URLs to crawl are fed either from a static list of URLs- * or from a dynamic queue of URLs enabling recursive crawling of websites.- *- * `BasicCrawler` is a low-level tool that requires the user to implement the page- * download and data extraction functionality themselves.- * If you want a crawler that already facilitates this functionality,- * please consider using {@link PuppeteerCrawler} or {@link CheerioCrawler}.- *- * `BasicCrawler` invokes the user-provided {@link BasicCrawlerOptions.handleRequestFunction}- * for each {@link Request} object, which represents a single URL to crawl.- * The {@link Request} objects are fed from the {@link RequestList} or the {@link RequestQueue}- * instances provided by the {@link BasicCrawlerOptions.requestList} or {@link BasicCrawlerOptions.requestQueue}- * constructor options, respectively.- *- * If both {@link BasicCrawlerOptions.requestList} and {@link BasicCrawlerOptions.requestQueue} options are used,- * the instance first processes URLs from the {@link RequestList} and automatically enqueues all of them- * to {@link RequestQueue} before it starts their processing. This ensures that a single URL is not crawled multiple times.- *- * The crawler finishes if there are no more {@link Request} objects to crawl.- *- * New requests are only dispatched when there is enough free CPU and memory available,- * using the functionality provided by the {@link AutoscaledPool} class.- * All {@link AutoscaledPool} configuration options can be passed to the `autoscaledPoolOptions`- * parameter of the `BasicCrawler` constructor. For user convenience, the `minConcurrency` and `maxConcurrency`- * {@link AutoscaledPool} options are available directly in the `BasicCrawler` constructor.- *- * **Example usage:**- *- * ```javascript- * // Prepare a list of URLs to crawl- * const requestList = new Apify.RequestList({- * sources: [- * { url: 'http://www.example.com/page-1' },- * { url: 'http://www.example.com/page-2' },- * ],- * });- * await requestList.initialize();- *- * // Crawl the URLs- * const crawler = new Apify.BasicCrawler({- * requestList,- * handleRequestFunction: async ({ request }) => {- * // 'request' contains an instance of the Request class- * // Here we simply fetch the HTML of the page and store it to a dataset- * const { body } = await Apify.utils.requestAsBrowser(request);- * await Apify.pushData({- * url: request.url,- * html: body,- * })- * },- * });- *- * await crawler.run();- * ```- *- * @property {AutoscaledPool} autoscaledPool- * A reference to the underlying {@link AutoscaledPool} class that manages the concurrency of the crawler.- * Note that this property is only initialized after calling the {@link BasicCrawler#run} function.- * You can use it to change the concurrency settings on the fly,- * to pause the crawler by calling {@link AutoscaledPool#pause}- * or to abort it by calling {@link AutoscaledPool#abort}.- */-declare class BasicCrawler {- /**- * @param {BasicCrawlerOptions} options- * All `BasicCrawler` parameters are passed via an options object.- */- constructor(options: BasicCrawlerOptions);- requestList: any;- requestQueue: any;- handleRequestFunction: any;- handleRequestTimeoutMillis: number;- handleFailedRequestFunction: any;- maxRequestRetries: any;- handledRequestsCount: number;- stats: Statistics;- sessionPoolOptions: any;- useSessionPool: any;- autoscaledPoolOptions: any;- isRunningPromise: Promise<void> | null;- /**- * Runs the crawler. Returns a promise that gets resolved once all the requests are processed.- *- * @return {Promise<void>}- */- run(): Promise<void>;- autoscaledPool: AutoscaledPool | undefined;- sessionPool: import("../session_pool/session_pool").SessionPool | undefined;- _pauseOnMigration(): Promise<void>;- /**- * Fetches request from either RequestList or RequestQueue. If request comes from a RequestList- * and RequestQueue is present then enqueues it to the queue first.- *- * @ignore- */- _fetchNextRequest(): Promise<any>;- /**- * Wrapper around handleRequestFunction that fetches requests from RequestList/RequestQueue- * then retries them in a case of an error, etc.- *- * @ignore- */- _runTaskFunction(): Promise<void>;- /**- * Returns true if either RequestList or RequestQueue have a request ready for processing.- *- * @ignore- */- _isTaskReadyFunction(): Promise<boolean>;- /**- * Returns true if both RequestList and RequestQueue have all requests finished.- *- * @ignore- */- _defaultIsFinishedFunction(): Promise<any>;- /**- * Handles errors thrown by user provided handleRequestFunction()- * @param {Error} error- * @param {Request} request- * @param {(RequestList|RequestQueue)} source- * @return {Promise<boolean|void|QueueOperationInfo>} willBeRetried- * @ignore- */- _requestFunctionErrorHandler(error: Error, request: Request, source: RequestList | RequestQueue): Promise<boolean | void | QueueOperationInfo>;- /**- * Updates handledRequestsCount from possibly stored counts,- * usually after worker migration. Since one of the stores- * needs to have priority when both are present,- * it is the request queue, because generally, the request- * list will first be dumped into the queue and then left- * empty.- *- * @return {Promise<void>}- * @ignore- */- _loadHandledRequestCount(): Promise<void>;-}-import { RequestList } from "../request_list";-import { RequestQueue } from "../request_queue";-import { AutoscaledPoolOptions } from "../autoscaling/autoscaled_pool";-import { SessionPoolOptions } from "../session_pool/session_pool";-import Request from "../request";-import AutoscaledPool from "../autoscaling/autoscaled_pool";-import { Session } from "../session_pool/session";-import Statistics from "./statistics";-import { QueueOperationInfo } from "../request_queue";diff --git a/types/crawlers/cheerio_crawler.d.ts b/types/crawlers/cheerio_crawler.d.tsdeleted file mode 100644index 95f523ba2..000000000--- a/types/crawlers/cheerio_crawler.d.ts+++ /dev/null@@ -1,676 +0,0 @@-/// <reference types="node" />-export default CheerioCrawler;-export type CheerioCrawlerOptions = {- /**- * User-provided function that performs the logic of the crawler. It is called for each page- * loaded and parsed by the crawler.- *- * The function receives the following object as an argument:- * ```- * {- * // The Cheerio object's function with the parsed HTML.- * $: Cheerio,- *- * // The request body of the web page, whose type depends on the content type.- * body: String|Buffer,- *- * // The parsed object from JSON for responses with the "application/json" content types.- * // For other content types it's null.- * json: Object,- *- * // Apify.Request object with details of the requested web page- * request: Request,- *- * // Parsed Content-Type HTTP header: { type, encoding }- * contentType: Object,- *- * // An instance of Node's http.IncomingMessage object,- * response: Object,- *- * // Underlying AutoscaledPool instance used to manage the concurrency of crawler- * autoscaledPool: AutoscaledPool,- *- * // Session object, useful to work around anti-scraping protections- * session: Session- * }- * ```- *- * Type of `body` depends on the `Content-Type` header of the web page:- * - String for `text/html`, `application/xhtml+xml`, `application/xml` MIME content types- * - Buffer for others MIME content types- *- * Parsed `Content-Type` header using- * [content-type package](https://www.npmjs.com/package/content-type)- * is stored in `contentType`.- *- * Cheerio is available only for HTML and XML content types.- *- * With the {@link Request} object representing the URL to crawl.- *- * If the function returns, the returned promise is awaited by the crawler.- *- * If the function throws an exception, the crawler will try to re-crawl the- * request later, up to `option.maxRequestRetries` times.- * If all the retries fail, the crawler calls the function- * provided to the `handleFailedRequestFunction` parameter.- * To make this work, you should **always**- * let your function throw exceptions rather than catch them.- * The exceptions are logged to the request using the- * {@link Request#pushErrorMessage} function.- */- handlePageFunction: CheerioHandlePage;- /**- * Static list of URLs to be processed.- * Either `requestList` or `requestQueue` option must be provided (or both).- */- requestList?: RequestList;- /**- * Dynamic queue of URLs to be processed. This is useful for recursive crawling of websites.- * Either `requestList` or `requestQueue` option must be provided (or both).- */- requestQueue?: RequestQueue;- /**- * Represents the options passed to the {@link requestAsBrowser} function that makes the HTTP requests to fetch the web pages.- * Provided `requestOptions` are added to internal defaults that cannot be overridden to ensure- * the operation of `CheerioCrawler` and all its options. Headers will not be merged,- * use {@link RequestList} and/or {@link RequestQueue} to initialize your {@link Request} with the- * correct headers or use `prepareRequestFunction` to modify your {@link Request} dynamically.- * If you need more granular control over your requests, use {@link BasicCrawler}.- *- * The mandatory internal defaults that **CANNOT BE OVERRIDDEN** by `requestOptions`:- * ```- * {- * url, // Provided by RequestList and/or RequestQueue- * method, // Provided by RequestList and/or RequestQueue- * headers, // Provided by RequestList and/or RequestQueue- * payload, // Provided by RequestList and/or RequestQueue- * strictSSL, // Use ignoreSslErrors- * proxy, // Use useApifyProxy or proxyUrls- * }- * ```- */- requestOptions?: utilsRequest.RequestAsBrowserOptions;- /**- * A function that executes before the HTTP request is made to the target resource.- * This function is suitable for setting dynamic properties such as cookies to the {@link Request}.- *- * The function receives the following object as an argument:- * ```- * {- * request: Request,- * session: Session- * }- * ```- * where the {@link Request} instance corresponds to the initialized request- * and the {@link Session} instance corresponds to used session.- *- * The function should modify the properties of the passed {@link Request} instance- * in place because there are already earlier references to it. Making a copy and returning it from- * this function is therefore not supported, because it would create inconsistencies where- * different parts of SDK would have access to a different {@link Request} instance.- */- prepareRequestFunction?: PrepareRequest;- /**- * Timeout in which the function passed as `handlePageFunction` needs to finish, given in seconds.- */- handlePageTimeoutSecs?: number;- /**- * Timeout in which the HTTP request to the resource needs to finish, given in seconds.- */- requestTimeoutSecs?: number;- /**- * If set to true, SSL certificate errors will be ignored.- */- ignoreSslErrors?: boolean;- /**- * If set to `true`, `CheerioCrawler` will be configured to use- * [Apify Proxy](https://my.apify.com/proxy) for all connections.- * For more information, see the [documentation](https://docs.apify.com/proxy)- */- useApifyProxy?: boolean;- /**- * An array of proxy groups to be used- * by the [Apify Proxy](https://docs.apify.com/proxy).- * Only applied if the `useApifyProxy` option is `true`.- */- apifyProxyGroups?: string[];- /**- * Apify Proxy session identifier to be used with requests made by `CheerioCrawler`.- * All HTTP requests going through the proxy with the same session identifier- * will use the same target proxy server (i.e. the same IP address).- * The identifier can only contain the following characters: `0-9`, `a-z`, `A-Z`, `"."`, `"_"` and `"~"`.- * Only applied if the `useApifyProxy` option is `true`.- */- apifyProxySession?: string;- /**- * An array of custom proxy URLs to be used by the `CheerioCrawler` instance.- * The provided custom proxies' order will be randomized and the resulting list rotated.- * Custom proxies are not compatible with Apify Proxy and an attempt to use both- * configuration options will cause an error to be thrown on startup.- */- proxyUrls?: string[];- /**- * A function to handle requests that failed more than `option.maxRequestRetries` times.- *- * The function receives the following object as an argument:- * ```- * {- * request: Request,- * error: Error,- * }- * ```- * where the {@link Request} instance corresponds to the failed request, and the `Error` instance- * represents the last error thrown during processing of the request.- *- * See [source code](https://github.com/apifytech/apify-js/blob/master/src/crawlers/cheerio_crawler.js#L13)- * for the default implementation of this function.- */- handleFailedRequestFunction?: HandleFailedRequest;- /**- * An array of <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Complete_list_of_MIME_types"- * target="_blank">MIME types</a> you want the crawler to load and process.- * By default, only `text/html` and `application/xhtml+xml` MIME types are supported.- */- additionalMimeTypes?: string[];- /**- * Indicates how many times the request is retried if either `requestFunction` or `handlePageFunction` fails.- */- maxRequestRetries?: number;- /**- * Maximum number of pages that the crawler will open. The crawl will stop when this limit is reached.- * Always set this value in order to prevent infinite loops in misconfigured crawlers.- * Note that in cases of parallel crawling, the actual number of pages visited might be slightly higher than this value.- */- maxRequestsPerCrawl?: number;- /**- * Custom options passed to the underlying {@link AutoscaledPool} constructor.- * Note that the `runTaskFunction`, `isTaskReadyFunction` and `isFinishedFunction` options- * are provided by `CheerioCrawler` and cannot be overridden. Reasonable {@link Snapshotter}- * and {@link SystemStatus} defaults are provided to account for the fact that `cheerio`- * parses HTML synchronously and therefore blocks the event loop.- */- autoscaledPoolOptions?: AutoscaledPoolOptions;- /**- * Sets the minimum concurrency (parallelism) for the crawl. Shortcut to the corresponding {@link AutoscaledPool} option.- *- * *WARNING:* If you set this value too high with respect to the available system memory and CPU, your crawler will run extremely slow or crash.- * If you're not sure, just keep the default value and the concurrency will scale up automatically.- */- minConcurrency?: number;- /**- * Sets the maximum concurrency (parallelism) for the crawl. Shortcut to the corresponding {@link AutoscaledPool} option.- */- maxConcurrency?: number;- /**- * If set to true Crawler will automatically use Session Pool. It will automatically retire sessions on 403, 401 and 429 status codes.- * It also marks Session as bad after a request timeout.- */- useSessionPool?: boolean;- /**- * Custom options passed to the underlying {@link SessionPool} constructor.- */- sessionPoolOptions?: SessionPoolOptions;- /**- * Automatically saves cookies to Session. Works only if Session Pool is used.- *- * It parses cookie from response "set-cookie" header saves or updates cookies for session and once the session is used for next request.- * It passes the "Cookie" header to the request with the session cookies.- */- persistCookiesPerSession?: boolean;-};-export type PrepareRequestInputs = {- /**- * Original instance fo the {Request} object. Must be modified in-place.- */- request: Request;- /**- * The current session- */- session?: Session;-};-export type PrepareRequest = (inputs: PrepareRequestInputs) => void | Promise<void>;-export type CheerioHandlePageInputs = {- /**- * The [Cheerio](https://cheerio.js.org/) object with parsed HTML.- */- $?: CheerioSelector;- /**- * The request body of the web page.- */- body: string | Buffer;- /**- * The parsed object from JSON string if the response contains the content type application/json.- */- json?: any;- /**- * The original {@link Request} object.- */- request: Request;- /**- * Parsed `Content-Type header: { type, encoding }`.- */- contentType: {- type: string;- encoding: string;- };- /**- * An instance of Node's http.IncomingMessage object,- */- response: IncomingMessage;- /**- * A reference to the underlying {@link AutoscaledPool} class that manages the concurrency of the crawler.- * Note that this property is only initialized after calling the {@link CheerioCrawler#run} function.- * You can use it to change the concurrency settings on the fly,- * to pause the crawler by calling {@link AutoscaledPool#pause}- * or to abort it by calling {@link AutoscaledPool#abort}.- */- autoscaledPool: AutoscaledPool;- session?: Session;-};-export type CheerioHandlePage = (inputs: CheerioHandlePageInputs) => Promise<void>;-/**- * @typedef CheerioCrawlerOptions- * @property {CheerioHandlePage} handlePageFunction- * User-provided function that performs the logic of the crawler. It is called for each page- * loaded and parsed by the crawler.- *- * The function receives the following object as an argument:- * ```- * {- * // The Cheerio object's function with the parsed HTML.- * $: Cheerio,- *- * // The request body of the web page, whose type depends on the content type.- * body: String|Buffer,- *- * // The parsed object from JSON for responses with the "application/json" content types.- * // For other content types it's null.- * json: Object,- *- * // Apify.Request object with details of the requested web page- * request: Request,- *- * // Parsed Content-Type HTTP header: { type, encoding }- * contentType: Object,- *- * // An instance of Node's http.IncomingMessage object,- * response: Object,- *- * // Underlying AutoscaledPool instance used to manage the concurrency of crawler- * autoscaledPool: AutoscaledPool,- *- * // Session object, useful to work around anti-scraping protections- * session: Session- * }- * ```- *- * Type of `body` depends on the `Content-Type` header of the web page:- * - String for `text/html`, `application/xhtml+xml`, `application/xml` MIME content types- * - Buffer for others MIME content types- *- * Parsed `Content-Type` header using- * [content-type package](https://www.npmjs.com/package/content-type)- * is stored in `contentType`.- *- * Cheerio is available only for HTML and XML content types.- *- * With the {@link Request} object representing the URL to crawl.- *- * If the function returns, the returned promise is awaited by the crawler.- *- * If the function throws an exception, the crawler will try to re-crawl the- * request later, up to `option.maxRequestRetries` times.- * If all the retries fail, the crawler calls the function- * provided to the `handleFailedRequestFunction` parameter.- * To make this work, you should **always**- * let your function throw exceptions rather than catch them.- * The exceptions are logged to the request using the- * {@link Request#pushErrorMessage} function.- * @property {RequestList} [requestList]- * Static list of URLs to be processed.- * Either `requestList` or `requestQueue` option must be provided (or both).- * @property {RequestQueue} [requestQueue]- * Dynamic queue of URLs to be processed. This is useful for recursive crawling of websites.- * Either `requestList` or `requestQueue` option must be provided (or both).- * @property {RequestAsBrowserOptions} [requestOptions]- * Represents the options passed to the {@link requestAsBrowser} function that makes the HTTP requests to fetch the web pages.- * Provided `requestOptions` are added to internal defaults that cannot be overridden to ensure- * the operation of `CheerioCrawler` and all its options. Headers will not be merged,- * use {@link RequestList} and/or {@link RequestQueue} to initialize your {@link Request} with the- * correct headers or use `prepareRequestFunction` to modify your {@link Request} dynamically.- * If you need more granular control over your requests, use {@link BasicCrawler}.- *- * The mandatory internal defaults that **CANNOT BE OVERRIDDEN** by `requestOptions`:- * ```- * {- * url, // Provided by RequestList and/or RequestQueue- * method, // Provided by RequestList and/or RequestQueue- * headers, // Provided by RequestList and/or RequestQueue- * payload, // Provided by RequestList and/or RequestQueue- * strictSSL, // Use ignoreSslErrors- * proxy, // Use useApifyProxy or proxyUrls- * }- * ```- * @property {PrepareRequest} [prepareRequestFunction]- * A function that executes before the HTTP request is made to the target resource.- * This function is suitable for setting dynamic properties such as cookies to the {@link Request}.- *- * The function receives the following object as an argument:- * ```- * {- * request: Request,- * session: Session- * }- * ```- * where the {@link Request} instance corresponds to the initialized request- * and the {@link Session} instance corresponds to used session.- *- * The function should modify the properties of the passed {@link Request} instance- * in place because there are already earlier references to it. Making a copy and returning it from- * this function is therefore not supported, because it would create inconsistencies where- * different parts of SDK would have access to a different {@link Request} instance.- *- * @property {number} [handlePageTimeoutSecs=60]- * Timeout in which the function passed as `handlePageFunction` needs to finish, given in seconds.- * @property {number} [requestTimeoutSecs=30]- * Timeout in which the HTTP request to the resource needs to finish, given in seconds.- * @property {boolean} [ignoreSslErrors=true]- * If set to true, SSL certificate errors will be ignored.- * @property {boolean} [useApifyProxy=false]- * If set to `true`, `CheerioCrawler` will be configured to use- * [Apify Proxy](https://my.apify.com/proxy) for all connections.- * For more information, see the [documentation](https://docs.apify.com/proxy)- * @property {string[]} [apifyProxyGroups]- * An array of proxy groups to be used- * by the [Apify Proxy](https://docs.apify.com/proxy).- * Only applied if the `useApifyProxy` option is `true`.- * @property {string} [apifyProxySession]- * Apify Proxy session identifier to be used with requests made by `CheerioCrawler`.- * All HTTP requests going through the proxy with the same session identifier- * will use the same target proxy server (i.e. the same IP address).- * The identifier can only contain the following characters: `0-9`, `a-z`, `A-Z`, `"."`, `"_"` and `"~"`.- * Only applied if the `useApifyProxy` option is `true`.- * @property {string[]} [proxyUrls]- * An array of custom proxy URLs to be used by the `CheerioCrawler` instance.- * The provided custom proxies' order will be randomized and the resulting list rotated.- * Custom proxies are not compatible with Apify Proxy and an attempt to use both- * configuration options will cause an error to be thrown on startup.- * @property {HandleFailedRequest} [handleFailedRequestFunction]- * A function to handle requests that failed more than `option.maxRequestRetries` times.- *- * The function receives the following object as an argument:- * ```- * {- * request: Request,- * error: Error,- * }- * ```- * where the {@link Request} instance corresponds to the failed request, and the `Error` instance- * represents the last error thrown during processing of the request.- *- * See [source code](https://github.com/apifytech/apify-js/blob/master/src/crawlers/cheerio_crawler.js#L13)- * for the default implementation of this function.- * @property {string[]} [additionalMimeTypes]- * An array of <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Complete_list_of_MIME_types"- * target="_blank">MIME types</a> you want the crawler to load and process.- * By default, only `text/html` and `application/xhtml+xml` MIME types are supported.- * @property {number} [maxRequestRetries=3]- * Indicates how many times the request is retried if either `requestFunction` or `handlePageFunction` fails.- * @property {number} [maxRequestsPerCrawl]- * Maximum number of pages that the crawler will open. The crawl will stop when this limit is reached.- * Always set this value in order to prevent infinite loops in misconfigured crawlers.- * Note that in cases of parallel crawling, the actual number of pages visited might be slightly higher than this value.- * @property {AutoscaledPoolOptions} [autoscaledPoolOptions]- * Custom options passed to the underlying {@link AutoscaledPool} constructor.- * Note that the `runTaskFunction`, `isTaskReadyFunction` and `isFinishedFunction` options- * are provided by `CheerioCrawler` and cannot be overridden. Reasonable {@link Snapshotter}- * and {@link SystemStatus} defaults are provided to account for the fact that `cheerio`- * parses HTML synchronously and therefore blocks the event loop.- * @property {number} [minConcurrency=1]- * Sets the minimum concurrency (parallelism) for the crawl. Shortcut to the corresponding {@link AutoscaledPool} option.- *- * *WARNING:* If you set this value too high with respect to the available system memory and CPU, your crawler will run extremely slow or crash.- * If you're not sure, just keep the default value and the concurrency will scale up automatically.- * @property {number} [maxConcurrency=1000]- * Sets the maximum concurrency (parallelism) for the crawl. Shortcut to the corresponding {@link AutoscaledPool} option.- * @property {boolean} [useSessionPool=false]- * If set to true Crawler will automatically use Session Pool. It will automatically retire sessions on 403, 401 and 429 status codes.- * It also marks Session as bad after a request timeout.- * @property {SessionPoolOptions} [sessionPoolOptions]- * Custom options passed to the underlying {@link SessionPool} constructor.- * @property {boolean} [persistCookiesPerSession]- * Automatically saves cookies to Session. Works only if Session Pool is used.- *- * It parses cookie from response "set-cookie" header saves or updates cookies for session and once the session is used for next request.- * It passes the "Cookie" header to the request with the session cookies.- */-/**- * Provides a framework for the parallel crawling of web pages using plain HTTP requests and- * [cheerio](https://www.npmjs.com/package/cheerio) HTML parser.- * The URLs to crawl are fed either from a static list of URLs- * or from a dynamic queue of URLs enabling recursive crawling of websites.- *- * Since `CheerioCrawler` uses raw HTTP requests to download web pages,- * it is very fast and efficient on data bandwidth. However, if the target website requires JavaScript- * to display the content, you might need to use {@link PuppeteerCrawler} instead,- * because it loads the pages using full-featured headless Chrome browser.- *- * `CheerioCrawler` downloads each URL using a plain HTTP request,- * parses the HTML content using [Cheerio](https://www.npmjs.com/package/cheerio)- * and then invokes the user-provided {@link CheerioCrawlerOptions.handlePageFunction} to extract page data- * using a [jQuery](https://jquery.com/)-like interface to the parsed HTML DOM.- *- * The source URLs are represented using {@link Request} objects that are fed from- * {@link RequestList} or {@link RequestQueue} instances provided by the {@link CheerioCrawlerOptions.requestList}- * or {@link CheerioCrawlerOptions.requestQueue} constructor options, respectively.- *- * If both {@link CheerioCrawlerOptions.requestList} and {@link CheerioCrawlerOptions.requestQueue} are used,- * the instance first processes URLs from the {@link RequestList} and automatically enqueues all of them- * to {@link RequestQueue} before it starts their processing. This ensures that a single URL is not crawled multiple times.- *- * The crawler finishes when there are no more {@link Request} objects to crawl.- *- * `CheerioCrawler` downloads the web pages using the {@link utils#requestAsBrowser} utility function.- * You can use the `requestOptions` parameter to pass additional options to this function.- *- * By default, `CheerioCrawler` only processes web pages with the `text/html`- * and `application/xhtml+xml` MIME content types (as reported by the `Content-Type` HTTP header),- * and skips pages with other content types. If you want the crawler to process other content types,- * use the {@link CheerioCrawlerOptions.additionalMimeTypes} constructor option.- * Beware that the parsing behavior differs for HTML, XML, JSON and other types of content.- * For details, see {@link CheerioCrawlerOptions.handlePageFunction}.- *- * New requests are only dispatched when there is enough free CPU and memory available,- * using the functionality provided by the {@link AutoscaledPool} class.- * All {@link AutoscaledPool} configuration options can be passed to the `autoscaledPoolOptions`- * parameter of the `CheerioCrawler` constructor. For user convenience, the `minConcurrency` and `maxConcurrency`- * {@link AutoscaledPool} options are available directly in the `CheerioCrawler` constructor.- *- * **Example usage:**- *- * ```javascript- * // Prepare a list of URLs to crawl- * const requestList = new Apify.RequestList({- * sources: [- * { url: 'http://www.example.com/page-1' },- * { url: 'http://www.example.com/page-2' },- * ],- * });- * await requestList.initialize();- *- * // Crawl the URLs- * const crawler = new Apify.CheerioCrawler({- * requestList,- * handlePageFunction: async ({ request, response, body, contentType, $ }) => {- * const data = [];- *- * // Do some data extraction from the page with Cheerio.- * $('.some-collection').each((index, el) => {- * data.push({ title: $(el).find('.some-title').text() });- * });- *- * // Save the data to dataset.- * await Apify.pushData({- * url: request.url,- * html: body,- * data,- * })- * },- * });- *- * await crawler.run();- * ```- * @property {AutoscaledPool} autoscaledPool- * A reference to the underlying {@link AutoscaledPool} class that manages the concurrency of the crawler.- * Note that this property is only initialized after calling the {@link CheerioCrawler#run} function.- * You can use it to change the concurrency settings on the fly,- * to pause the crawler by calling {@link AutoscaledPool#pause}- * or to abort it by calling {@link AutoscaledPool#abort}.- */-declare class CheerioCrawler {- /**- * @param {CheerioCrawlerOptions} options- * All `CheerioCrawler` parameters are passed via an options object.- */- constructor(options?: CheerioCrawlerOptions);- supportedMimeTypes: Set<string>;- requestOptions: utilsRequest.RequestAsBrowserOptions;- handlePageFunction: CheerioHandlePage;- handlePageTimeoutMillis: number;- requestTimeoutMillis: number;- ignoreSslErrors: boolean;- useApifyProxy: boolean;- apifyProxyGroups: string[];- apifyProxySession: string;- proxyUrls: any[];- lastUsedProxyUrlIndex: number;- prepareRequestFunction: PrepareRequest;- persistCookiesPerSession: boolean;- useSessionPool: boolean;- /** @ignore */- basicCrawler: any;- isRunningPromise: any;- /**- * Runs the crawler. Returns promise that gets resolved once all the requests got processed.- *- * @return {Promise<void>}- */- run(): Promise<void>;- autoscaledPool: any;- /**- * Wrapper around handlePageFunction that opens and closes pages etc.- *- * @param {Object} options- * @param {Request} options.request- * @param {AutoscaledPool} options.autoscaledPool- * @param {Session} options.session- * @ignore- */- _handleRequestFunction({ request, autoscaledPool, session }: {- request: Request;- autoscaledPool: AutoscaledPool;- session: Session;- }): Promise<any>;- /**- * Function to make the HTTP request. It performs optimizations- * on the request such as only downloading the request body if the- * received content type matches text/html, application/xml, application/xhtml+xml.- *- * @param {Object} options- * @param {Request} options.request- * @param {Session} options.session- * @ignore- */- _requestFunction({ request, session }: {- request: Request;- session: Session;- }): Promise<{- dom: any;- isXml: boolean;- response: any;- contentType: {- type: string;- encoding: any;- };- body?: undefined;- } | {- body: any;- response: any;- contentType: {- type: string;- encoding: any;- };- dom?: undefined;- isXml?: undefined;- }>;- /**- * Combines the provided `requestOptions` with mandatory (non-overridable) values.- * @param {Request} request- * @param {Session} [session]- * @ignore- */- _getRequestOptions(request: Request, session?: Session | undefined): utilsRequest.RequestAsBrowserOptions & {- url: string;- method: string;- headers: any;- ignoreSslErrors: boolean;- proxyUrl: string | null;- stream: boolean;- useCaseSensitiveHeaders: boolean;- abortFunction: (res: any) => boolean;- timeoutSecs: number;- };- /**- * Enables the use of a proxy by returning a proxy URL- * based on configured options or null if no proxy is used.- * @param {Session} [session]- * @returns {(string|null)}- * @ignore- */- _getProxyUrl(session?: Session | undefined): string | null;- _encodeResponse(request: any, response: any, encoding: any): {- response: any;- encoding: any;- };- _parseHtmlToDom(response: any): Promise<any>;- /**- * Checks and extends supported mime types- * @param {Array<(string|Object)>} additionalMimeTypes- * @ignore- */- _extendSupportedMimeTypes(additionalMimeTypes: (string | Object)[]): void;- /**- * Handles blocked request- * @param {Session} session- * @param {number} statusCode- * @private- */- _throwOnBlockedRequest(session: Session, statusCode: number): void;- /**- * Handles timeout request- * @param {Session} session- * @private- */- _handleRequestTimeout(session: Session): void;- /**- * @param {Object} options- * @param {Error} options.error- * @param {Request} options.request- * @return {Promise<void>}- * @ignore- */- _defaultHandleFailedRequestFunction({ error, request }: {- error: Error;- request: Request;- }): Promise<void>;-}-import { RequestList } from "../request_list";-import { RequestQueue } from "../request_queue";-import * as utilsRequest from "../utils_request";-import { HandleFailedRequest } from "./basic_crawler";-import { AutoscaledPoolOptions } from "../autoscaling/autoscaled_pool";-import { SessionPoolOptions } from "../session_pool/session_pool";-import Request from "../request";-import { Session } from "../session_pool/session";-import { IncomingMessage } from "http";-import AutoscaledPool from "../autoscaling/autoscaled_pool";diff --git a/types/crawlers/puppeteer_crawler.d.ts b/types/crawlers/puppeteer_crawler.d.tsdeleted file mode 100644index b423c2e34..000000000--- a/types/crawlers/puppeteer_crawler.d.ts+++ /dev/null@@ -1,530 +0,0 @@-export default PuppeteerCrawler;-export type PuppeteerCrawlerOptions = {- /**- * Function that is called to process each request.- * It is passed an object with the following fields:- *- * ```- * {- * request: Request,- * response: Response,- * page: Page,- * puppeteerPool: PuppeteerPool,- * autoscaledPool: AutoscaledPool,- * session: Session,- * }- * ```- *- * `request` is an instance of the {@link Request} object with details about the URL to open, HTTP method etc.- * `page` is an instance of the `Puppeteer`- * [`Page`](https://pptr.dev/#?product=Puppeteer&show=api-class-page)- * `response` is an instance of the `Puppeteer`- * [`Response`](https://pptr.dev/#?product=Puppeteer&show=api-class-response),- * which is the main resource response as returned by `page.goto(request.url)`.- * `puppeteerPool` is an instance of the {@link PuppeteerPool} used by this `PuppeteerCrawler`.- *- * The function must return a promise, which is then awaited by the crawler.- *- * If the function throws an exception, the crawler will try to re-crawl the- * request later, up to `option.maxRequestRetries` times.- * If all the retries fail, the crawler calls the function- * provided to the `handleFailedRequestFunction` parameter.- * To make this work, you should **always**- * let your function throw exceptions rather than catch them.- * The exceptions are logged to the request using the- * {@link Request#pushErrorMessage} function.- */- handlePageFunction: PuppeteerHandlePage;- /**- * Static list of URLs to be processed.- * Either `requestList` or `requestQueue` option must be provided (or both).- */- requestList?: RequestList;- /**- * Dynamic queue of URLs to be processed. This is useful for recursive crawling of websites.- * Either `requestList` or `requestQueue` option must be provided (or both).- */- requestQueue?: RequestQueue;- /**- * Timeout in which the function passed as `handlePageFunction` needs to finish, in seconds.- */- handlePageTimeoutSecs?: number;- /**- * Overrides the function that opens the page in Puppeteer. The function should return the result of Puppeteer's- * [page.goto()](https://pptr.dev/#?product=Puppeteer&show=api-pagegotourl-options) function,- * i.e. a `Promise` resolving to the [Response](https://pptr.dev/#?product=Puppeteer&show=api-class-response) object.- *- * This is useful if you need to extend the page load timeout or select different criteria- * to determine that the navigation succeeded.- *- * Note that a single page object is only used to process a single request and it is closed afterwards.- *- * By default, the function invokes {@link puppeteer#gotoExtended} with a timeout of 60 seconds.- * For details, see source code on- * [GitHub](https://github.com/apifytech/apify-js/blob/master/src/crawlers/puppeteer_crawler.js#L292).- */- gotoFunction?: PuppeteerGoto;- /**- * Timeout in which page navigation needs to finish, in seconds. When `gotoFunction()` is used and thus the default- * function is overridden, this timeout will not be used and needs to be configured in the new `gotoFunction()`.- */- gotoTimeoutSecs?: number;- /**- * A function to handle requests that failed more than `option.maxRequestRetries` times.- *- * The function receives the following object as an argument:- * ```- * {- * request: Request,- * error: Error,- * }- * ```- * Where the {@link Request} instance corresponds to the failed request, and the `Error` instance- * represents the last error thrown during processing of the request.- *- * See- * [source code](https://github.com/apifytech/apify-js/blob/master/src/crawlers/puppeteer_crawler.js#L301)- * for the default implementation of this function.- */- handleFailedRequestFunction?: HandleFailedRequest;- /**- * Indicates how many times the request is retried if either `handlePageFunction()` or `gotoFunction()` fails.- */- maxRequestRetries?: number;- /**- * Maximum number of pages that the crawler will open. The crawl will stop when this limit is reached.- * Always set this value in order to prevent infinite loops in misconfigured crawlers.- * Note that in cases of parallel crawling, the actual number of pages visited might be slightly higher than this value.- */- maxRequestsPerCrawl?: number;- /**- * Custom options passed to the underlying {@link PuppeteerPool} constructor.- * You can tweak those to fine-tune browser management.- */- puppeteerPoolOptions?: PuppeteerPoolOptions;- /**- * Overrides the default function to launch a new Puppeteer instance.- * Shortcut to the corresponding {@link PuppeteerPool} option.- * See source code on- * [GitHub](https://github.com/apifytech/apify-js/blob/master/src/puppeteer_pool.js#L28)- * for default behavior.- */- launchPuppeteerFunction?: LaunchPuppeteerFunction;- /**- * Options used by {@link Apify#launchPuppeteer} to start new Puppeteer instances.- * Shortcut to the corresponding {@link PuppeteerPool} option.- */- launchPuppeteerOptions?: LaunchPuppeteerOptions;- /**- * Custom options passed to the underlying {@link AutoscaledPool} instance constructor.- * Note that the `runTaskFunction`, `isTaskReadyFunction` and `isFinishedFunction` options- * are provided by `PuppeteerCrawler` and should not be overridden.- */- autoscaledPoolOptions?: AutoscaledPoolOptions;- /**- * Sets the minimum concurrency (parallelism) for the crawl. Shortcut to the- * corresponding {@link AutoscaledPoolOptions.minConcurrency} option.- *- * *WARNING:* If you set this value too high with respect to the available system memory and CPU,- * your crawler will run extremely slow or crash. If you're not sure, just keep the default value- * and the concurrency will scale up automatically.- */- minConcurrency?: number;- /**- * Sets the maximum concurrency (parallelism) for the crawl. Shortcut to the- * corresponding {@link AutoscaledPoolOptions.maxConcurrency} option.- */- maxConcurrency?: number;- /**- * If set to true Crawler will automatically use Session Pool. It will automatically retire- * sessions on 403, 401 and 429 status codes. It also marks Session as bad after a request timeout.- */- useSessionPool?: boolean;- /**- * Custom options passed to the underlying {@link SessionPool} constructor.- */- sessionPoolOptions?: SessionPoolOptions;- /**- * Automatically saves cookies to Session. Works only if Session Pool is used.- */- persistCookiesPerSession?: boolean;-};-export type PuppeteerHandlePageInputs = {- /**- * An instance of the {@link Request} object with details about the URL to open, HTTP method etc.- */- request: Request;- /**- * An instance of the Puppeteer- * [`Response`](https://pptr.dev/#?product=Puppeteer&show=api-class-response),- * which is the main resource response as returned by `page.goto(request.url)`.- */- response: PuppeteerResponse;- /**- * is an instance of the Puppeteer- * [`Page`](https://pptr.dev/#?product=Puppeteer&show=api-class-page)- */- page: PuppeteerPage;- /**- * An instance of the {@link PuppeteerPool} used by this `PuppeteerCrawler`.- */- puppeteerPool: PuppeteerPool;- /**- * A reference to the underlying {@link AutoscaledPool} class that manages the concurrency of the crawler.- * Note that this property is only initialized after calling the {@link PuppeteerCrawler#run} function.- * You can use it to change the concurrency settings on the fly,- * to pause the crawler by calling {@link AutoscaledPool#pause}- * or to abort it by calling {@link AutoscaledPool#abort}.- */- autoscaledPool: AutoscaledPool;- session?: Session;-};-export type PuppeteerHandlePage = (inputs: PuppeteerHandlePageInputs) => Promise<void>;-export type PuppeteerGotoInputs = {- /**- * is an instance of the Puppeteer- * [`Page`](https://pptr.dev/#?product=Puppeteer&show=api-class-page)- */- page: PuppeteerPage;- /**- * An instance of the {@link Request} object with details about the URL to open, HTTP method etc.- */- request: Request;- /**- * An instance of the `AutoscaledPool`.- */- autoscaledPool: AutoscaledPool;- /**- * An instance of the {@link PuppeteerPool} used by this `PuppeteerCrawler`.- */- puppeteerPool: PuppeteerPool;- /**- * `Session` object for this request.- */- session?: Session;-};-export type PuppeteerGoto = (inputs: PuppeteerGotoInputs) => Promise<PuppeteerResponse | null>;-export type LaunchPuppeteer = (inputs: LaunchPuppeteerOptions) => Promise<Browser>;-/**- * @typedef PuppeteerCrawlerOptions- * @property {PuppeteerHandlePage} handlePageFunction- * Function that is called to process each request.- * It is passed an object with the following fields:- *- * ```- * {- * request: Request,- * response: Response,- * page: Page,- * puppeteerPool: PuppeteerPool,- * autoscaledPool: AutoscaledPool,- * session: Session,- * }- * ```- *- * `request` is an instance of the {@link Request} object with details about the URL to open, HTTP method etc.- * `page` is an instance of the `Puppeteer`- * [`Page`](https://pptr.dev/#?product=Puppeteer&show=api-class-page)- * `response` is an instance of the `Puppeteer`- * [`Response`](https://pptr.dev/#?product=Puppeteer&show=api-class-response),- * which is the main resource response as returned by `page.goto(request.url)`.- * `puppeteerPool` is an instance of the {@link PuppeteerPool} used by this `PuppeteerCrawler`.- *- * The function must return a promise, which is then awaited by the crawler.- *- * If the function throws an exception, the crawler will try to re-crawl the- * request later, up to `option.maxRequestRetries` times.- * If all the retries fail, the crawler calls the function- * provided to the `handleFailedRequestFunction` parameter.- * To make this work, you should **always**- * let your function throw exceptions rather than catch them.- * The exceptions are logged to the request using the- * {@link Request#pushErrorMessage} function.- * @property {RequestList} [requestList]- * Static list of URLs to be processed.- * Either `requestList` or `requestQueue` option must be provided (or both).- * @property {RequestQueue} [requestQueue]- * Dynamic queue of URLs to be processed. This is useful for recursive crawling of websites.- * Either `requestList` or `requestQueue` option must be provided (or both).- * @property {number} [handlePageTimeoutSecs=60]- * Timeout in which the function passed as `handlePageFunction` needs to finish, in seconds.- * @property {PuppeteerGoto} [gotoFunction]- * Overrides the function that opens the page in Puppeteer. The function should return the result of Puppeteer's- * [page.goto()](https://pptr.dev/#?product=Puppeteer&show=api-pagegotourl-options) function,- * i.e. a `Promise` resolving to the [Response](https://pptr.dev/#?product=Puppeteer&show=api-class-response) object.- *- * This is useful if you need to extend the page load timeout or select different criteria- * to determine that the navigation succeeded.- *- * Note that a single page object is only used to process a single request and it is closed afterwards.- *- * By default, the function invokes {@link puppeteer#gotoExtended} with a timeout of 60 seconds.- * For details, see source code on- * [GitHub](https://github.com/apifytech/apify-js/blob/master/src/crawlers/puppeteer_crawler.js#L292).- * @property {number} [gotoTimeoutSecs=60]- * Timeout in which page navigation needs to finish, in seconds. When `gotoFunction()` is used and thus the default- * function is overridden, this timeout will not be used and needs to be configured in the new `gotoFunction()`.- * @property {HandleFailedRequest} [handleFailedRequestFunction]- * A function to handle requests that failed more than `option.maxRequestRetries` times.- *- * The function receives the following object as an argument:- * ```- * {- * request: Request,- * error: Error,- * }- * ```- * Where the {@link Request} instance corresponds to the failed request, and the `Error` instance- * represents the last error thrown during processing of the request.- *- * See- * [source code](https://github.com/apifytech/apify-js/blob/master/src/crawlers/puppeteer_crawler.js#L301)- * for the default implementation of this function.- * @property {number} [maxRequestRetries=3]- * Indicates how many times the request is retried if either `handlePageFunction()` or `gotoFunction()` fails.- * @property {number} [maxRequestsPerCrawl]- * Maximum number of pages that the crawler will open. The crawl will stop when this limit is reached.- * Always set this value in order to prevent infinite loops in misconfigured crawlers.- * Note that in cases of parallel crawling, the actual number of pages visited might be slightly higher than this value.- * @property {PuppeteerPoolOptions} [puppeteerPoolOptions]- * Custom options passed to the underlying {@link PuppeteerPool} constructor.- * You can tweak those to fine-tune browser management.- * @property {LaunchPuppeteerFunction} [launchPuppeteerFunction]- * Overrides the default function to launch a new Puppeteer instance.- * Shortcut to the corresponding {@link PuppeteerPool} option.- * See source code on- * [GitHub](https://github.com/apifytech/apify-js/blob/master/src/puppeteer_pool.js#L28)- * for default behavior.- * @property {LaunchPuppeteerOptions} [launchPuppeteerOptions]- * Options used by {@link Apify#launchPuppeteer} to start new Puppeteer instances.- * Shortcut to the corresponding {@link PuppeteerPool} option.- * @property {AutoscaledPoolOptions} [autoscaledPoolOptions]- * Custom options passed to the underlying {@link AutoscaledPool} instance constructor.- * Note that the `runTaskFunction`, `isTaskReadyFunction` and `isFinishedFunction` options- * are provided by `PuppeteerCrawler` and should not be overridden.- * @property {number} [minConcurrency=1]- * Sets the minimum concurrency (parallelism) for the crawl. Shortcut to the- * corresponding {@link AutoscaledPoolOptions.minConcurrency} option.- *- * *WARNING:* If you set this value too high with respect to the available system memory and CPU,- * your crawler will run extremely slow or crash. If you're not sure, just keep the default value- * and the concurrency will scale up automatically.- * @property {number} [maxConcurrency=1000]- * Sets the maximum concurrency (parallelism) for the crawl. Shortcut to the- * corresponding {@link AutoscaledPoolOptions.maxConcurrency} option.- * @property {boolean} [useSessionPool=false]- * If set to true Crawler will automatically use Session Pool. It will automatically retire- * sessions on 403, 401 and 429 status codes. It also marks Session as bad after a request timeout.- * @property {SessionPoolOptions} [sessionPoolOptions]- * Custom options passed to the underlying {@link SessionPool} constructor.- * @property {boolean} [persistCookiesPerSession=false]- * Automatically saves cookies to Session. Works only if Session Pool is used.- */-/**- * Provides a simple framework for parallel crawling of web pages- * using headless Chrome with [Puppeteer](https://github.com/GoogleChrome/puppeteer).- * The URLs to crawl are fed either from a static list of URLs- * or from a dynamic queue of URLs enabling recursive crawling of websites.- *- * Since `PuppeteerCrawler` uses headless Chrome to download web pages and extract data,- * it is useful for crawling of websites that require to execute JavaScript.- * If the target website doesn't need JavaScript, consider using {@link CheerioCrawler},- * which downloads the pages using raw HTTP requests and is about 10x faster.- *- * The source URLs are represented using {@link Request} objects that are fed from- * {@link RequestList} or {@link RequestQueue} instances provided by the {@link PuppeteerCrawlerOptions.requestList}- * or {@link PuppeteerCrawlerOptions.requestQueue} constructor options, respectively.- *- * If both {@link PuppeteerCrawlerOptions.requestList} and {@link PuppeteerCrawlerOptions.requestQueue} are used,- * the instance first processes URLs from the {@link RequestList} and automatically enqueues all of them- * to {@link RequestQueue} before it starts their processing. This ensures that a single URL is not crawled multiple times.- *- * The crawler finishes when there are no more {@link Request} objects to crawl.- *- * `PuppeteerCrawler` opens a new Chrome page (i.e. tab) for each {@link Request} object to crawl- * and then calls the function provided by user as the {@link PuppeteerCrawlerOptions.handlePageFunction} option.- *- * New pages are only opened when there is enough free CPU and memory available,- * using the functionality provided by the {@link AutoscaledPool} class.- * All {@link AutoscaledPool} configuration options can be passed to the {@link PuppeteerCrawlerOptions.autoscaledPoolOptions}- * parameter of the `PuppeteerCrawler` constructor. For user convenience, the `minConcurrency` and `maxConcurrency`- * {@link AutoscaledPoolOptions} are available directly in the `PuppeteerCrawler` constructor.- *- * Note that the pool of Puppeteer instances is internally managed by the {@link PuppeteerPool} class.- * Many constructor options such as {@link PuppeteerPoolOptions.maxOpenPagesPerInstance} or- * {@link PuppeteerPoolOptions.launchPuppeteerFunction} are passed directly to the {@link PuppeteerPool} constructor.- *- * **Example usage:**- *- * ```javascript- * const crawler = new Apify.PuppeteerCrawler({- * requestList,- * handlePageFunction: async ({ page, request }) => {- * // This function is called to extract data from a single web page- * // 'page' is an instance of Puppeteer.Page with page.goto(request.url) already called- * // 'request' is an instance of Request class with information about the page to load- * await Apify.pushData({- * title: await page.title(),- * url: request.url,- * succeeded: true,- * })- * },- * handleFailedRequestFunction: async ({ request }) => {- * // This function is called when the crawling of a request failed too many times- * await Apify.pushData({- * url: request.url,- * succeeded: false,- * errors: request.errorMessages,- * })- * },- * });- *- * await crawler.run();- * ```- * @property {AutoscaledPool} autoscaledPool- * A reference to the underlying {@link AutoscaledPool} class that manages the concurrency of the crawler.- * Note that this property is only initialized after calling the {@link PuppeteerCrawler#run} function.- * You can use it to change the concurrency settings on the fly,- * to pause the crawler by calling {@link AutoscaledPool#pause}- * or to abort it by calling {@link AutoscaledPool#abort}.- *- */-declare class PuppeteerCrawler {- /**- * @param {PuppeteerCrawlerOptions} options- * All `PuppeteerCrawler` parameters are passed via an options object.- */- constructor(options: PuppeteerCrawlerOptions);- handlePageFunction: PuppeteerHandlePage;- gotoFunction: PuppeteerGoto;- handlePageTimeoutMillis: number;- gotoTimeoutMillis: number;- puppeteerPoolOptions: {- launchPuppeteerFunction: LaunchPuppeteerFunction;- launchPuppeteerOptions: LaunchPuppeteerOptions;- /**- * Enables the use of a preconfigured {@link LiveViewServer} that serves snapshots- * just before a page would be recycled by `PuppeteerPool`. If there are no clients- * connected, it has close to zero impact on performance.- */- useLiveView?: boolean;- /**- * Maximum number of open pages (i.e. tabs) per browser. When this limit is reached, new pages are loaded in a new browser instance.- */- maxOpenPagesPerInstance?: number;- /**- * Maximum number of requests that can be processed by a single browser instance.- * After the limit is reached, the browser is retired and new requests are- * handled by a new browser instance.- */- retireInstanceAfterRequestCount?: number;- /**- * All browser management operations such as launching a new browser, opening a new page- * or closing a page will timeout after the set number of seconds and the connected- * browser will be retired.- */- puppeteerOperationTimeoutSecs?: number;- /**- * Indicates how often are the open Puppeteer instances checked whether they can be closed.- */- instanceKillerIntervalSecs?: number;- /**- * When Puppeteer instance reaches the `retireInstanceAfterRequestCount` limit then- * it is considered retired and no more tabs will be opened. After the last tab is closed the- * whole browser is closed too. This parameter defines a time limit between the last tab was opened and- * before the browser is closed even if there are pending open tabs.- */- killInstanceAfterSecs?: number;- /**- * Enables recycling of disk cache directories by Chrome instances.- * When a browser instance is closed, its disk cache directory is not deleted but it's used by a newly opened browser instance.- * This is useful to reduce amount of data that needs to be downloaded to speed up crawling and reduce proxy usage.- * Note that the new browser starts with empty cookies, local storage etc. so this setting doesn't affect anonymity of your crawler.- *- * Beware that the disk cache directories can consume a lot of disk space.- * To limit the space consumed, you can pass the `--disk-cache-size=X` argument to `launchPuppeteerargs`,- * where `X` is the approximate maximum number of bytes for disk cache.- *- * Do not use the `recycleDiskCache` setting together with `--disk-cache-dir`- * argument in `launchPuppeteerargs`, the behavior is undefined.- */- recycleDiskCache?: boolean;- /**- * With this option selected, all pages will be opened in a new incognito browser context, which means- * that they will not share cookies or cache and their resources will not be throttled by one another.- */- useIncognitoPages?: boolean;- /**- * An array of custom proxy URLs to be used by the `PuppeteerPool` instance.- * The provided custom proxies' order will be randomized and the resulting list rotated.- * Custom proxies are not compatible with Apify Proxy and an attempt to use both- * configuration options will cause an error to be thrown on startup.- */- proxyUrls?: string[];- };- puppeteerPool: PuppeteerPool | null;- useSessionPool: boolean;- sessionPoolOptions: SessionPoolOptions;- persistCookiesPerSession: boolean;- /** @ignore */- basicCrawler: BasicCrawler;- /**- * Runs the crawler. Returns promise that gets resolved once all the requests got processed.- *- * @return {Promise<void>}- */- run(): Promise<void>;- sessionPool: import("../session_pool/session_pool").SessionPool | undefined;- isRunningPromise: Promise<void> | undefined;- autoscaledPool: AutoscaledPool | undefined;- /**- * Wrapper around handlePageFunction that opens and closes pages etc.- *- * @param {Object} options- * @param {Request} options.request- * @param {AutoscaledPool} options.autoscaledPool- * @ignore- */- _handleRequestFunction({ request, autoscaledPool }: {- request: Request;- autoscaledPool: AutoscaledPool;- }): Promise<void>;- /**- * @param {Object} options- * @param {PuppeteerPage} options.page- * @param {Request} options.request- * @return {Promise<PuppeteerResponse>}- * @ignore- */- _defaultGotoFunction({ page, request }: {- page: PuppeteerPage;- request: Request;- }): Promise<PuppeteerResponse>;- /**- * @param {Object} options- * @param {Error} options.error- * @param {Request} options.request- * @return {Promise<void>}- * @ignore- */- _defaultHandleFailedRequestFunction({ error, request }: {- error: Error;- request: Request;- }): Promise<void>;-}-import { RequestList } from "../request_list";-import { RequestQueue } from "../request_queue";-import { HandleFailedRequest } from "./basic_crawler";-import { PuppeteerPoolOptions } from "../puppeteer_pool";-import { LaunchPuppeteerFunction } from "../puppeteer_pool";-import { LaunchPuppeteerOptions } from "../puppeteer";-import { AutoscaledPoolOptions } from "../autoscaling/autoscaled_pool";-import { SessionPoolOptions } from "../session_pool/session_pool";-import Request from "../request";-import { Response as PuppeteerResponse } from "puppeteer";-import { Page as PuppeteerPage } from "puppeteer";-import PuppeteerPool from "../puppeteer_pool";-import AutoscaledPool from "../autoscaling/autoscaled_pool";-import { Session } from "../session_pool/session";-import { Browser } from "puppeteer";-import BasicCrawler from "./basic_crawler";diff --git a/types/crawlers/statistics.d.ts b/types/crawlers/statistics.d.tsdeleted file mode 100644index 78ec18369..000000000--- a/types/crawlers/statistics.d.ts+++ /dev/null@@ -1,39 +0,0 @@-/**- * The statistics class provides an interface to collecting and logging run- * statistics of arbitrary jobs. Currently it provides the following information:- *- * - Average run time of successful jobs- * - Number of successful jobs per minute- * - Total number of successful jobs- * - Total number of failed jobs- * - A histogram of retry counts = Number of jobs that finished after N retries.- *- * @ignore- */-export default class Statistics {- constructor(options?: {});- logIntervalMillis: number;- logMessage: any;- jobRetryHistogram: any[];- finishedJobs: number;- failedJobs: number;- jobsInProgress: Map<any, any>;- minJobDurationMillis: number;- maxJobDurationMillis: number;- totalJobDurationMillis: number;- startedAt: Date | null;- logInterval: NodeJS.Timeout | null;- startJob(id: any): void;- finishJob(id: any): void;- failJob(id: any): void;- getCurrent(): {- avgDurationMillis: number;- perMinute: number;- finished: number;- failed: number;- retryHistogram: any[];- };- startLogging(): void;- stopLogging(): void;- _saveRetryCountForJob(job: any): void;-}diff --git a/types/dataset.d.ts b/types/dataset.d.tsdeleted file mode 100644index bf69b3675..000000000--- a/types/dataset.d.ts+++ /dev/null@@ -1,363 +0,0 @@-export const DATASET_ITERATORS_DEFAULT_LIMIT: 10000;-export const LOCAL_STORAGE_SUBDIR: string;-export const LOCAL_FILENAME_DIGITS: 9;-export const LOCAL_GET_ITEMS_DEFAULT_LIMIT: 250000;-export function checkAndSerialize(item: Object, limitBytes: number, index?: number | undefined): string;-export function chunkBySize(items: any[], limitBytes: number): any[];-/**- * The `Dataset` class represents a store for structured data where each object stored has the same attributes,- * such as online store products or real estate offers. You can imagine it as a table,- * where each object is a row and its attributes are columns.- * Dataset is an append-only storage - you can only add new records to it but you cannot modify or remove existing records.- * Typically it is used to store crawling results.- *- * Do not instantiate this class directly, use the- * {@link Apify#openDataset} function instead.- *- * `Dataset` stores its data either on local disk or in the Apify cloud,- * depending on whether the `APIFY_LOCAL_STORAGE_DIR` or `APIFY_TOKEN` environment variables are set.- *- * If the `APIFY_LOCAL_STORAGE_DIR` environment variable is set, the data is stored in- * the local directory in the following files:- * ```- * {APIFY_LOCAL_STORAGE_DIR}/datasets/{DATASET_ID}/{INDEX}.json- * ```- * Note that `{DATASET_ID}` is the name or ID of the dataset. The default dataset has ID: `default`,- * unless you override it by setting the `APIFY_DEFAULT_DATASET_ID` environment variable.- * Each dataset item is stored as a separate JSON file, where `{INDEX}` is a zero-based index of the item in the dataset.- *- * If the `APIFY_TOKEN` environment variable is set but `APIFY_LOCAL_STORAGE_DIR` not, the data is stored in the- * [Apify Dataset](https://docs.apify.com/storage/dataset)- * cloud storage. Note that you can force usage of the cloud storage also by passing the `forceCloud`- * option to {@link Apify#openDataset} function,- * even if the `APIFY_LOCAL_STORAGE_DIR` variable is set.- *- * **Example usage:**- *- * ```javascript- * // Write a single row to the default dataset- * await Apify.pushData({ col1: 123, col2: 'val2' });- *- * // Open a named dataset- * const dataset = await Apify.openDataset('some-name');- *- * // Write a single row- * await dataset.pushData({ foo: 'bar' });- *- * // Write multiple rows- * await dataset.pushData([- * { foo: 'bar2', col2: 'val2' },- * { col3: 123 },- * ]);- * ```- * @hideconstructor- */-export class Dataset {- /**- * @param {string} datasetId- * @param {string} datasetName- */- constructor(datasetId: string, datasetName: string);- datasetId: string;- datasetName: string;- /**- * Stores an object or an array of objects to the dataset.- * The function returns a promise that resolves when the operation finishes.- * It has no result, but throws on invalid args or other errors.- *- * **IMPORTANT**: Make sure to use the `await` keyword when calling `pushData()`,- * otherwise the actor process might finish before the data is stored!- *- * The size of the data is limited by the receiving API and therefore `pushData()` will only- * allow objects whose JSON representation is smaller than 9MB. When an array is passed,- * none of the included objects- * may be larger than 9MB, but the array itself may be of any size.- *- * The function internally- * chunks the array into separate items and pushes them sequentially.- * The chunking process is stable (keeps order of data), but it does not provide a transaction- * safety mechanism. Therefore, in the event of an uploading error (after several automatic retries),- * the function's Promise will reject and the dataset will be left in a state where some of- * the items have already been saved to the dataset while other items from the source array were not.- * To overcome this limitation, the developer may, for example, read the last item saved in the dataset- * and re-attempt the save of the data from this item onwards to prevent duplicates.- * @param {object|Array<object>} data Object or array of objects containing data to be stored in the default dataset.- * The objects must be serializable to JSON and the JSON representation of each object must be smaller than 9MB.- * @return {Promise<void>}- */- pushData(data: any): Promise<void>;- /**- * Returns {DatasetContent} object holding the items in the dataset based on the provided parameters.- *- * **NOTE**: If using dataset with local disk storage, the `format` option must be `json` and- * the following options are not supported:- * `unwind`, `disableBodyParser`, `attachment`, `bom` and `simplified`.- * If you try to use them, you will receive an error.- *- * @param {Object} [options] All `getData()` parameters are passed- * via an options object with the following keys:- * @param {string} [options.format='json']- * Format of the `items` property, possible values are: `json`, `csv`, `xlsx`, `html`, `xml` and `rss`.- * @param {number} [options.offset=0]- * Number of array elements that should be skipped at the start.- * @param {number} [options.limit=250000]- * Maximum number of array elements to return.- * @param {boolean} [options.desc=false]- * If `true` then the objects are sorted by `createdAt` in descending order.- * Otherwise they are sorted in ascending order.- * @param {string[]} [options.fields]- * An array of field names that will be included in the result. If omitted, all fields are included in the results.- * @param {string} [options.unwind]- * Specifies a name of the field in the result objects that will be used to unwind the resulting objects.- * By default, the results are returned as they are.- * @param {boolean} [options.disableBodyParser=false]- * If `true` then response from API will not be parsed.- * @param {boolean} [options.attachment=false]- * If `true` then the response will define the `Content-Disposition: attachment` HTTP header, forcing a web- * browser to download the file rather than to display it. By default, this header is not present.- * @param {string} [options.delimiter=',']- * A delimiter character for CSV files, only used if `format` is `csv`.- * @param {boolean} [options.bom]- * All responses are encoded in UTF-8 encoding. By default, the CSV files are prefixed with the UTF-8 Byte- * Order Mark (BOM), while JSON, JSONL, XML, HTML and RSS files are not. If you want to override this default- * behavior, set `bom` option to `true` to include the BOM, or set `bom` to `false` to skip it.- * @param {string} [options.xmlRoot='results']- * Overrides the default root element name of the XML output. By default, the root element is `results`.- * @param {string} [options.xmlRow='page']- * Overrides the default element name that wraps each page or page function result object in XML output.- * By default, the element name is `page` or `result`, depending on the value of the `simplified` option.- * @param {boolean} [options.skipHeaderRow=false]- * If set to `true` then header row in CSV format is skipped.- * @param {boolean} [options.clean=false]- * If `true` then the function returns only non-empty items and skips hidden fields (i.e. fields starting with `#` character).- * Note that the `clean` parameter is a shortcut for `skipHidden: true` and `skipEmpty: true` options.- * @param {boolean} [options.skipHidden=false]- * If `true` then the function doesn't return hidden fields (fields starting with "#" character).- * @param {boolean} [options.skipEmpty=false]- * If `true` then the function doesn't return empty items.- * Note that in this case the returned number of items might be lower than limit parameter and pagination must be done using the `limit` value.- * @param {boolean} [options.simplified]- * If `true` then function applies the `fields: ['url','pageFunctionResult','errorInfo']` and `unwind: 'pageFunctionResult'` options.- * This feature is used to emulate simplified results provided by Apify API version 1 used for- * the legacy Apify Crawler and it's not recommended to use it in new integrations.- * @param {boolean} [options.skipFailedPages]- * If `true` then, the all the items with errorInfo property will be skipped from the output.- * This feature is here to emulate functionality of Apify API version 1 used for- * the legacy Apify Crawler product and it's not recommended to use it in new integrations.- * @return {Promise<DatasetContent>}- */- getData(options?: {- format?: string;- offset?: number;- limit?: number;- desc?: boolean;- fields?: string[];- unwind?: string;- disableBodyParser?: boolean;- attachment?: boolean;- delimiter?: string;- bom?: boolean;- xmlRoot?: string;- xmlRow?: string;- skipHeaderRow?: boolean;- clean?: boolean;- skipHidden?: boolean;- skipEmpty?: boolean;- simplified?: boolean;- skipFailedPages?: boolean;- } | undefined): Promise<DatasetContent>;- /**- * Returns an object containing general information about the dataset.- *- * The function returns the same object as the Apify API Client's- * [getDataset](https://docs.apify.com/api/apify-client-js/latest#ApifyClient-datasets-getDataset)- * function, which in turn calls the- * [Get dataset](https://apify.com/docs/api/v2#/reference/datasets/dataset/get-dataset)- * API endpoint.- *- * **Example:**- * ```- * {- * id: "WkzbQMuFYuamGv3YF",- * name: "my-dataset",- * userId: "wRsJZtadYvn4mBZmm",- * createdAt: new Date("2015-12-12T07:34:14.202Z"),- * modifiedAt: new Date("2015-12-13T08:36:13.202Z"),- * accessedAt: new Date("2015-12-14T08:36:13.202Z"),- * itemCount: 14,- * cleanItemCount: 10- * }- * ```- *- * @returns {Promise<object>}- */- getInfo(): Promise<any>;- /**- * Iterates over dataset items, yielding each in turn to an `iteratee` function.- * Each invocation of `iteratee` is called with two arguments: `(item, index)`.- *- * If the `iteratee` function returns a Promise then it is awaited before the next call.- * If it throws an error, the iteration is aborted and the `forEach` function throws the error.- *- * **Example usage**- * ```javascript- * const dataset = await Apify.openDataset('my-results');- * await dataset.forEach(async (item, index) => {- * console.log(`Item at ${index}: ${JSON.stringify(item)}`);- * });- * ```- *- * @param {DatasetConsumer} iteratee A function that is called for every item in the dataset.- * @param {Object} [options] All `forEach()` parameters are passed- * via an options object with the following keys:- * @param {boolean} [options.desc=false] If `true` then the objects are sorted by `createdAt` in descending order.- * @param {string[]} [options.fields] If provided then returned objects will only contain specified keys.- * @param {string} [options.unwind] If provided then objects will be unwound based on provided field.- * @param {number} [index=0] Specifies the initial index number passed to the `iteratee` function.- * @return {Promise<void>}- */- forEach(iteratee: DatasetConsumer, options?: {- desc?: boolean;- fields?: string[];- unwind?: string;- } | undefined, index?: number | undefined): Promise<void>;- /**- * Produces a new array of values by mapping each value in list through a transformation function `iteratee()`.- * Each invocation of `iteratee()` is called with two arguments: `(element, index)`.- *- * If `iteratee` returns a `Promise` then it's awaited before a next call.- *- * @param {DatasetMapper} iteratee- * @param {Object} [options] All `map()` parameters are passed- * via an options object with the following keys:- * @param {boolean} [options.desc=false] If `true` then the objects are sorted by createdAt in descending order.- * @param {string[]} [options.fields] If provided then returned objects will only contain specified keys- * @param {string} [options.unwind] If provided then objects will be unwound based on provided field.- * @return {Promise<Array<object>>}- */- map(iteratee: DatasetMapper, options?: {- desc?: boolean;- fields?: string[];- unwind?: string;- } | undefined): Promise<any[]>;- /**- * Reduces a list of values down to a single value.- *- * Memo is the initial state of the reduction, and each successive step of it should be returned by `iteratee()`.- * The `iteratee()` is passed three arguments: the `memo`, then the `value` and `index` of the iteration.- *- * If no `memo` is passed to the initial invocation of reduce, the `iteratee()` is not invoked on the first element of the list.- * The first element is instead passed as the memo in the invocation of the `iteratee()` on the next element in the list.- *- * If `iteratee()` returns a `Promise` then it's awaited before a next call.- *- * @param {DatasetReducer} iteratee- * @param {object} memo Initial state of the reduction.- * @param {Object} [options] All `reduce()` parameters are passed- * via an options object with the following keys:- * @param {boolean} [options.desc=false] If `true` then the objects are sorted by createdAt in descending order.- * @param {string[]} [options.fields] If provided then returned objects will only contain specified keys- * @param {string} [options.unwind] If provided then objects will be unwound based on provided field.- * @return {Promise<object>}- */- reduce(iteratee: DatasetReducer, memo: any, options?: {- desc?: boolean;- fields?: string[];- unwind?: string;- } | undefined): Promise<any>;- /**- * Removes the dataset either from the Apify cloud storage or from the local directory,- * depending on the mode of operation.- *- * @return {Promise<void>}- */- drop(): Promise<void>;- /** @ignore */- delete(): Promise<void>;-}-/**- * This is a local emulation of a dataset.- *- * @ignore- */-export class DatasetLocal {- constructor(datasetId: any, localStorageDir: any);- localStoragePath: string;- counter: number | null;- datasetId: any;- createdAt: any;- modifiedAt: any;- accessedAt: any;- initializationPromise: any;- _initialize(): any;- pushData(data: any): any;- getData(opts?: {}): Promise<{- items: any[];- total: number | null;- offset: any;- count: number;- limit: any;- }>;- getInfo(): Promise<{- id: any;- name: any;- userId: string | null;- createdAt: any;- modifiedAt: any;- accessedAt: any;- itemCount: number | null;- cleanItemCount: number | null;- }>;- forEach(iteratee: any): Promise<void>;- map(iteratee: any): Promise<any[]>;- reduce(iteratee: any, memo: any): Promise<any>;- drop(): Promise<void>;- delete(): Promise<void>;- /**- * Returns an array of item indexes for given offset and limit.- */- _getItemIndexes(offset?: number, limit?: number | null): number[];- /**- * Reads and parses file for given index.- */- _readAndParseFile(index: any): Promise<any>;- _updateMetadata(isModified: any): void;-}-export function openDataset(datasetIdOrName?: string | undefined, options?: {- forceCloud?: boolean;-} | undefined): Promise<Dataset>;-export function pushData(item: any): Promise<void>;-export type DatasetContent = {- /**- * Dataset entries based on chosen format parameter.- */- items: any[];- /**- * Total count of entries in the dataset.- */- total: number;- /**- * Position of the first returned entry in the dataset.- */- offset: number;- /**- * Count of dataset entries returned in this set.- */- count: number;- /**- * Maximum number of dataset entries requested.- */- limit: number;-};-/**- * User-function used in the `Dataset.forEach()` API.- */-export type DatasetConsumer = (item: any, index: number) => any;-/**- * User-function used in the `Dataset.map()` API.- */-export type DatasetMapper = (item: any, index: number) => any;-/**- * User-function used in the `Dataset.reduce()` API.- */-export type DatasetReducer = (memo: any, item: any, index: number) => any;diff --git a/types/enqueue_links/click_elements.d.ts b/types/enqueue_links/click_elements.d.tsdeleted file mode 100644index 01cd2d711..000000000--- a/types/enqueue_links/click_elements.d.ts+++ /dev/null@@ -1,157 +0,0 @@-/**- * The function finds elements matching a specific CSS selector in a Puppeteer page,- * clicks all those elements using a mouse move and a left mouse button click and intercepts- * all the navigation requests that are subsequently produced by the page. The intercepted- * requests, including their methods, headers and payloads are then enqueued to a provided- * {@link RequestQueue}. This is useful to crawl JavaScript heavy pages where links are not available- * in `href` elements, but rather navigations are triggered in click handlers.- * If you're looking to find URLs in `href` attributes of the page, see {@link utils#enqueueLinks}.- *- * Optionally, the function allows you to filter the target links' URLs using an array of {@link PseudoUrl} objects- * and override settings of the enqueued {@link Request} objects.- *- * **IMPORTANT**: To be able to do this, this function uses various mutations on the page,- * such as changing the Z-index of elements being clicked and their visibility. Therefore,- * it is recommended to only use this function as the last operation in the page.- *- * **USING HEADFUL BROWSER**: When using a headful browser, this function will only be able to click elements- * in the focused tab, effectively limiting concurrency to 1. In headless mode, full concurrency can be achieved.- *- * **PERFORMANCE**: Clicking elements with a mouse and intercepting requests is not a low level operation- * that takes nanoseconds. It's not very CPU intensive, but it takes time. We strongly recommend limiting- * the scope of the clicking as much as possible by using a specific selector that targets only the elements- * that you assume or know will produce a navigation. You can certainly click everything by using- * the `*` selector, but be prepared to wait minutes to get results on a large and complex page.- *- * **Example usage**- *- * ```javascript- * const Apify = require('apify');- *- * const browser = await Apify.launchPuppeteer();- * const page = await browser.goto('https://www.example.com');- * const requestQueue = await Apify.openRequestQueue();- *- * await Apify.utils.enqueueLinksByClickingElements({- * page,- * requestQueue,- * selector: 'a.product-detail',- * pseudoUrls: [- * 'https://www.example.com/handbags/[.*]'- * 'https://www.example.com/purses/[.*]'- * ],- * });- * ```- * @param {Object} options- * All `enqueueLinksByClickingElements()` parameters are passed- * via an options object with the following keys:- * @param {Page} options.page- * Puppeteer [`Page`](https://pptr.dev/#?product=Puppeteer&show=api-class-page) object.- * @param {RequestQueue} options.requestQueue- * A request queue to which the URLs will be enqueued.- * @param {string} options.selector- * A CSS selector matching elements to be clicked on. Unlike in {@link utils#enqueueLinks}, there is no default- * value. This is to prevent suboptimal use of this function by using it too broadly.- * @param {Array<(string|RegExp|Object)>} [options.pseudoUrls]- * An array of {@link PseudoUrl}s matching the URLs to be enqueued,- * or an array of strings or RegExps or plain Objects from which the {@link PseudoUrl}s can be constructed.- *- * The plain objects must include at least the `purl` property, which holds the pseudo-URL string or RegExp.- * All remaining keys will be used as the `requestTemplate` argument of the {@link PseudoUrl} constructor,- * which lets you specify special properties for the enqueued {@link Request} objects.- *- * If `pseudoUrls` is an empty array, `null` or `undefined`, then the function- * enqueues all links found on the page.- * @param {RequestTransform} [options.transformRequestFunction]- * Just before a new {@link Request} is constructed and enqueued to the {@link RequestQueue}, this function can be used- * to remove it or modify its contents such as `userData`, `payload` or, most importantly `uniqueKey`. This is useful- * when you need to enqueue multiple `Requests` to the queue that share the same URL, but differ in methods or payloads,- * or to dynamically update or create `userData`.- *- * For example: by adding `useExtendedUniqueKey: true` to the `request` object, `uniqueKey` will be computed from- * a combination of `url`, `method` and `payload` which enables crawling of websites that navigate using form submits- * (POST requests).- *- * **Example:**- * ```javascript- * {- * transformRequestFunction: (request) => {- * request.userData.foo = 'bar';- * request.useExtendedUniqueKey = true;- * return request;- * }- * }- * ```- * @param {number} [options.waitForPageIdleSecs=1]- * Clicking in the page triggers various asynchronous operations that lead to new URLs being shown- * by the browser. It could be a simple JavaScript redirect or opening of a new tab in the browser.- * These events often happen only some time after the actual click. Requests typically take milliseconds- * while new tabs open in hundreds of milliseconds.- *- * To be able to capture all those events, the `enqueueLinksByClickingElements()` function repeatedly waits- * for the `waitForPageIdleSecs`. By repeatedly we mean that whenever a relevant event is triggered, the timer- * is restarted. As long as new events keep coming, the function will not return, unless- * the below `maxWaitForPageIdleSecs` timeout is reached.- *- * You may want to reduce this for example when you're sure that your clicks do not open new tabs,- * or increase when you're not getting all the expected URLs.- * @param {number} [options.maxWaitForPageIdleSecs=5]- * This is the maximum period for which the function will keep tracking events, even if more events keep coming.- * Its purpose is to prevent a deadlock in the page by periodic events, often unrelated to the clicking itself.- * See `waitForPageIdleSecs` above for an explanation.- * @return {Promise<Array<QueueOperationInfo>>}- * Promise that resolves to an array of {@link QueueOperationInfo} objects.- * @memberOf puppeteer- * @name enqueueLinksByClickingElements- * @function- */-export function enqueueLinksByClickingElements(options?: {- page: Page;- requestQueue: RequestQueue;- selector: string;- pseudoUrls?: (string | Object | RegExp)[];- transformRequestFunction?: RequestTransform;- waitForPageIdleSecs?: number;- maxWaitForPageIdleSecs?: number;-}): Promise<QueueOperationInfo[]>;-/**- * Clicks all elements of given page matching given selector.- * Catches and intercepts all initiated navigation requests and opened pages.- * Returns a list of all target URLs.- *- * @param {Object} options- * @param {Page} options.page- * @param {string} options.selector- * @return {Promise<Array<object>>}- * @ignore- */-export function clickElementsAndInterceptNavigationRequests(options: {- page: Page;- selector: string;-}): Promise<any[]>;-/**- * We're only interested in pages created by the page we're currently clicking in.- * There will generally be a lot of other targets being created in the browser.- * @param {Page} page- * @param {Target} target- * @return {boolean}- */-export function isTargetRelevant(page: Page, target: Target): boolean;-/**- * Click all elements matching the given selector. To be able to do this using- * Puppeteer's `.click()` we need to make sure the elements are reachable by mouse,- * so we first move them to the top of the page's stacking context and then click.- * We do all in series to prevent elements from hiding one another. Therefore,- * for large element sets, this will take considerable amount of time.- *- * @param {Page} page- * @param {string} selector- * @return {Promise<void>}- * @ignore- */-export function clickElements(page: Page, selector: string): Promise<void>;-import { Page } from "puppeteer";-import { RequestQueue } from "../request_queue";-import { RequestTransform } from "./shared";-import { QueueOperationInfo } from "../request_queue";-import { Target } from "puppeteer";diff --git a/types/enqueue_links/enqueue_links.d.ts b/types/enqueue_links/enqueue_links.d.tsdeleted file mode 100644index 7219d8008..000000000--- a/types/enqueue_links/enqueue_links.d.ts+++ /dev/null@@ -1,114 +0,0 @@-/**- * The function finds elements matching a specific CSS selector (HTML anchor (`<a>`) by default)- * either in a Puppeteer page, or in a Cheerio object (parsed HTML),- * and enqueues the URLs in their `href` attributes to the provided {@link RequestQueue}.- * If you're looking to find URLs in JavaScript heavy pages where links are not available- * in `href` elements, but rather navigations are triggered in click handlers- * see {@link puppeteer#enqueueLinksByClickingElements}.- *- * Optionally, the function allows you to filter the target links' URLs using an array of {@link PseudoUrl} objects- * and override settings of the enqueued {@link Request} objects.- *- * **Example usage**- *- * ```javascript- * const Apify = require('apify');- *- * const browser = await Apify.launchPuppeteer();- * const page = await browser.goto('https://www.example.com');- * const requestQueue = await Apify.openRequestQueue();- *- * await Apify.utils.enqueueLinks({- * page,- * requestQueue,- * selector: 'a.product-detail',- * pseudoUrls: [- * 'https://www.example.com/handbags/[.*]',- * 'https://www.example.com/purses/[.*]'- * ],- * });- * ```- *- * @param {Object} options- * All `enqueueLinks()` parameters are passed- * via an options object with the following keys:- * @param {Page} [options.page]- * Puppeteer [`Page`](https://pptr.dev/#?product=Puppeteer&show=api-class-page) object.- * Either `page` or `$` option must be provided.- * @param {CheerioStatic} [options.$]- * [`Cheerio`](https://github.com/cheeriojs/cheerio) function with loaded HTML.- * Either `page` or `$` option must be provided.- * @param {RequestQueue} options.requestQueue- * A request queue to which the URLs will be enqueued.- * @param {string} [options.selector='a']- * A CSS selector matching links to be enqueued.- * @param {string} [options.baseUrl]- * A base URL that will be used to resolve relative URLs when using Cheerio. Ignored when using Puppeteer,- * since the relative URL resolution is done inside the browser automatically.- * @param {Array<Object>|Array<string>} [options.pseudoUrls]- * An array of {@link PseudoUrl}s matching the URLs to be enqueued,- * or an array of strings or RegExps or plain Objects from which the {@link PseudoUrl}s can be constructed.- *- * The plain objects must include at least the `purl` property, which holds the pseudo-URL string or RegExp.- * All remaining keys will be used as the `requestTemplate` argument of the {@link PseudoUrl} constructor,- * which lets you specify special properties for the enqueued {@link Request} objects.- *- * If `pseudoUrls` is an empty array, `null` or `undefined`, then the function- * enqueues all links found on the page.- * @param {RequestTransform} [options.transformRequestFunction]- * Just before a new {@link Request} is constructed and enqueued to the {@link RequestQueue}, this function can be used- * to remove it or modify its contents such as `userData`, `payload` or, most importantly `uniqueKey`. This is useful- * when you need to enqueue multiple `Requests` to the queue that share the same URL, but differ in methods or payloads,- * or to dynamically update or create `userData`.- *- * For example: by adding `keepUrlFragment: true` to the `request` object, URL fragments will not be removed- * when `uniqueKey` is computed.- *- * **Example:**- * ```javascript- * {- * transformRequestFunction: (request) => {- * request.userData.foo = 'bar';- * request.keepUrlFragment = true;- * return request;- * }- * }- * ```- * @return {Promise<Array<QueueOperationInfo>>}- * Promise that resolves to an array of {@link QueueOperationInfo} objects.- * @memberOf utils- * @name enqueueLinks- * @function- */-export function enqueueLinks(options?: {- page?: Page;- $?: CheerioStatic;- requestQueue: RequestQueue;- selector?: string;- baseUrl?: string;- pseudoUrls?: string[] | Object[];- transformRequestFunction?: RequestTransform;-}): Promise<QueueOperationInfo[]>;-/**- * Extracts URLs from a given Puppeteer Page.- *- * @param {Page} page- * @param {string} selector- * @return {Promise<Array<string>>}- * @ignore- */-export function extractUrlsFromPage(page: Page, selector: string): Promise<string[]>;-/**- * Extracts URLs from a given Cheerio object.- *- * @param {CheerioStatic} $- * @param {string} selector- * @param {string} baseUrl- * @return {string[]}- * @ignore- */-export function extractUrlsFromCheerio($: CheerioStatic, selector: string, baseUrl: string): string[];-import { Page } from "puppeteer";-import { RequestQueue } from "../request_queue";-import { RequestTransform } from "./shared";-import { QueueOperationInfo } from "../request_queue";diff --git a/types/enqueue_links/shared.d.ts b/types/enqueue_links/shared.d.tsdeleted file mode 100644index 901f3b971..000000000--- a/types/enqueue_links/shared.d.ts+++ /dev/null@@ -1,40 +0,0 @@-/**- * Helper factory used in the `enqueueLinks()` and enqueueLinksByClickingElements() function.- * @param {Array<(string|Object)>} pseudoUrls- * @return {Array<PseudoUrl>}- * @ignore- */-export function constructPseudoUrlInstances(pseudoUrls: (string | Object)[]): PseudoUrl[];-/**- * @param {Array<(string|Object)>} requestOptions- * @param {Array<PseudoUrl>} pseudoUrls- * @return {Array<Request>}- * @ignore- */-export function createRequests(requestOptions: (string | Object)[], pseudoUrls: PseudoUrl[]): Request[];-/**- * @param {Array<(string|Object)>} sources- * @param {Object} [userData]- * @ignore- */-export function createRequestOptions(sources: (string | Object)[], userData?: Object | undefined): (Object | {- url: string;-})[];-/**- * @param {Array<Request>} requests- * @param {RequestQueue} requestQueue- * @param {number} batchSize- * @return {Promise<Array<QueueOperationInfo>>}- * @ignore- */-export function addRequestsToQueueInBatches(requests: Request[], requestQueue: RequestQueue, batchSize?: number): Promise<QueueOperationInfo[]>;-/**- * Takes an Apify {RequestOptions} object and changes it's attributes in a desired way. This user-function is used- * {@link utils#enqueueLinks} to modify requests before enqueuing them.- */-export type RequestTransform = (original: RequestOptions) => RequestOptions;-import PseudoUrl from "../pseudo_url";-import Request from "../request";-import { RequestQueue } from "../request_queue";-import { QueueOperationInfo } from "../request_queue";-import { RequestOptions } from "../request";diff --git a/types/errors.d.ts b/types/errors.d.tsdeleted file mode 100644index d5833ef48..000000000--- a/types/errors.d.ts+++ /dev/null@@ -1,29 +0,0 @@-export const APIFY_CALL_ERROR_NAME: "ApifyCallError";-/**- * The class represents exceptions thrown- * by the {@link Apify#call} function.- *- * @property {string} message- * Error message- * @property {ActorRun} run- * Object representing the failed actor run.- * @property {string} name- * Contains `"ApifyCallError"`- */-export class ApifyCallError extends Error {- /**- * @param {ActorRun} run- * @param {string} [message]- */- constructor(run: ActorRun, message?: string | undefined);- run: ActorRun;-}-/**- * TimeoutError class.- * This error should be thrown after request timeout from `requestAsBrowser`.- * @ignore- */-export class TimeoutError extends Error {- constructor(message?: string | undefined);-}-import { ActorRun } from "./typedefs";diff --git a/types/events.d.ts b/types/events.d.tsdeleted file mode 100644index fd46571f5..000000000--- a/types/events.d.ts+++ /dev/null@@ -1,9 +0,0 @@-export default events;-export function initializeEvents(): void;-export function stopEvents(): void;-/**- * Event emitter providing events from underlying Actor infrastructure and Apify package.- * @ignore- */-declare const events: EventEmitter;-import { EventEmitter } from "events";diff --git a/types/index.d.ts b/types/index.d.tsdeleted file mode 100644index 28db16310..000000000--- a/types/index.d.ts+++ /dev/null@@ -1,3 +0,0 @@-export default Apify;-export * from "./main";-import * as Apify from "./main";diff --git a/types/key_value_store.d.ts b/types/key_value_store.d.tsdeleted file mode 100644index 5a2f07757..000000000--- a/types/key_value_store.d.ts+++ /dev/null@@ -1,277 +0,0 @@-export const LOCAL_STORAGE_SUBDIR: string;-export function maybeStringify(value: any, options: any): any;-/**- * The `KeyValueStore` class represents a key-value store, a simple data storage that is used- * for saving and reading data records or files. Each data record is- * represented by a unique key and associated with a MIME content type. Key-value stores are ideal- * for saving screenshots, actor inputs and outputs, web pages, PDFs or to persist the state of crawlers.- *- * Do not instantiate this class directly, use the- * {@link Apify#openKeyValueStore} function instead.- *- * Each actor run is associated with a default key-value store, which is created exclusively- * for the run. By convention, the actor input and output are stored into the- * default key-value store under the `INPUT` and `OUTPUT` key, respectively.- * Typically, input and output are JSON files, although it can be any other format.- * To access the default key-value store directly, you can use the- * {@link Apify#getValue} and {@link Apify#setValue} convenience functions.- *- * To access the input, you can also use the {@link Apify#getInput} convenience function.- *- * `KeyValueStore` stores its data either on local disk or in the Apify cloud,- * depending on whether the [`APIFY_LOCAL_STORAGE_DIR`](/docs/guides/environment-variables#APIFY_LOCAL_STORAGE_DIR)- * or [`APIFY_TOKEN`](/docs/guides/environment-variables#APIFY_TOKEN) environment variables are set.- *- * If the `APIFY_LOCAL_STORAGE_DIR` environment variable is set, the data is stored in- * the local directory in the following files:- * ```- * {APIFY_LOCAL_STORAGE_DIR}/key_value_stores/{STORE_ID}/{INDEX}.{EXT}- * ```- * Note that `{STORE_ID}` is the name or ID of the key-value store. The default key value store has ID: `default`,- * unless you override it by setting the `APIFY_DEFAULT_KEY_VALUE_STORE_ID` environment variable.- * The `{KEY}` is the key of the record and `{EXT}` corresponds to the MIME content type of the data value.- *- * If the [`APIFY_TOKEN`](/docs/guides/environment-variables#APIFY_TOKEN) environment variable is set but- * [`APIFY_LOCAL_STORAGE_DIR`](/docs/guides/environment-variables#APIFY_LOCAL_STORAGE_DIR) not,- * the data is stored in the [Apify Key-value store](https://docs.apify.com/storage/key-value-store)- * cloud storage. Note that you can force usage of the cloud storage also by passing the `forceCloud`- * option to {@link Apify#openKeyValueStore} function, even if the- * [`APIFY_LOCAL_STORAGE_DIR`](/docs/guides/environment-variables#APIFY_LOCAL_STORAGE_DIR) variable is set.- *- * **Example usage:**- *- * ```javascript- * // Get actor input from the default key-value store- * const input = await Apify.getInput();- * const otherValue = Apify.getValue('my-key');- *- * // Write actor output to the default key-value store.- * await Apify.setValue('OUTPUT', { myResult: 123 });- *- * // Open a named key-value store- * const store = await Apify.openKeyValueStore('some-name');- *- * // Write a record. JavaScript object is automatically converted to JSON,- * // strings and binary buffers are stored as they are- * await store.setValue('some-key', { foo: 'bar' });- *- * // Read a record. Note that JSON is automatically parsed to a JavaScript object,- * // text data returned as a string and other data is returned as binary buffer- * const value = await store.getValue('some-key');- *- * // Drop (delete) the store- * await store.drop();- * ```- * @hideconstructor- */-export class KeyValueStore {- /**- * @param {string} storeId- * @param {string} storeName- */- constructor(storeId: string, storeName: string);- storeId: string;- storeName: string;- /**- * Gets a value from the key-value store.- *- * The function returns a `Promise` that resolves to the record value,- * whose JavaScript type depends on the MIME content type of the record.- * Records with the `application/json`- * content type are automatically parsed and returned as a JavaScript object.- * Similarly, records with `text/plain` content types are returned as a string.- * For all other content types, the value is returned as a raw- * [`Buffer`](https://nodejs.org/api/buffer.html) instance.- *- * If the record does not exist, the function resolves to `null`.- *- * To save or delete a value in the key-value store, use the- * {@link KeyValueStore#setValue} function.- *- * **Example usage:**- *- * ```javascript- * const store = await Apify.openKeyValueStore();- * const buffer = await store.getValue('screenshot1.png');- * ```- * @param {string} key- * Unique key of the record. It can be at most 256 characters long and only consist- * of the following characters: `a`-`z`, `A`-`Z`, `0`-`9` and `!-_.'()`- * @returns {Promise<(object|Buffer|string|null)>}- * Returns a promise that resolves to an object, string- * or [`Buffer`](https://nodejs.org/api/buffer.html), depending- * on the MIME content type of the record.- */- getValue(key: string): Promise<any>;- /**- * Saves or deletes a record in the key-value store.- * The function returns a promise that resolves once the record has been saved or deleted.- *- * **Example usage:**- *- * ```javascript- * const store = await Apify.openKeyValueStore();- * await store.setValue('OUTPUT', { foo: 'bar' });- * ```- *- * Beware that the key can be at most 256 characters long and only contain the following characters: `a-zA-Z0-9!-_.'()`- *- * By default, `value` is converted to JSON and stored with the- * `application/json; charset=utf-8` MIME content type.- * To store the value with another content type, pass it in the options as follows:- * ```javascript- * const store = await Apify.openKeyValueStore('my-text-store');- * await store.setValue('RESULTS', 'my text data', { contentType: 'text/plain' });- * ```- * If you set custom content type, `value` must be either a string or- * [`Buffer`](https://nodejs.org/api/buffer.html), otherwise an error will be thrown.- *- * If `value` is `null`, the record is deleted instead. Note that the `setValue()` function succeeds- * regardless whether the record existed or not.- *- * To retrieve a value from the key-value store, use the- * {@link KeyValueStore#getValue} function.- *- * **IMPORTANT:** Always make sure to use the `await` keyword when calling `setValue()`,- * otherwise the actor process might finish before the value is stored!- *- * @param {string} key- * Unique key of the record. It can be at most 256 characters long and only consist- * of the following characters: `a`-`z`, `A`-`Z`, `0`-`9` and `!-_.'()`- * @param {(Object|string|Buffer|null)} value- * Record data, which can be one of the following values:- * <ul>- * <li>If `null`, the record in the key-value store is deleted.</li>- * <li>If no `options.contentType` is specified, `value` can be any JavaScript object and it will be stringified to JSON.</li>- * <li>If `options.contentType` is specified, `value` is considered raw data and it must be either a `String`- * or [`Buffer`](https://nodejs.org/api/buffer.html).</li>- * </ul>- * For any other value an error will be thrown.- * @param {Object} [options]- * @param {string} [options.contentType]- * Specifies a custom MIME content type of the record.- * @returns {Promise<void>}- *- */- setValue(key: string, value: string | Object | Buffer | null, options?: {- contentType?: string;- } | undefined): Promise<void>;- /**- * Removes the key-value store either from the Apify cloud storage or from the local directory,- * depending on the mode of operation.- *- * @return {Promise<void>}- */- drop(): Promise<void>;- /** @ignore */- delete(): Promise<void>;- /**- * Returns a URL for the given key that may be used to publicly- * access the value in the remote key value store.- *- * @param {string} key- * @return {string}- */- getPublicUrl(key: string): string;- /**- * Iterates over key value store keys, yielding each in turn to an `iteratee` function.- * Each invocation of `iteratee` is called with three arguments: `(key, index, info)`, where `key`- * is the record key, `index` is a zero-based index of the key in the current iteration- * (regardless of `options.exclusiveStartKey`) and `info` is an object that contains a single property `size`- * indicating size of the record in bytes.- *- * If the `iteratee` function returns a Promise then it is awaited before the next call.- * If it throws an error, the iteration is aborted and the `forEachKey` function throws the error.- *- * **Example usage**- * ```javascript- * const keyValueStore = await Apify.openKeyValueStore();- * await keyValueStore.forEachKey(async (key, index, info) => {- * console.log(`Key at ${index}: ${key} has size ${info.size}`);- * });- * ```- *- * @param {KeyConsumer} iteratee A function that is called for every key in the key value store.- * @param {Object} [options] All `forEachKey()` parameters are passed- * via an options object with the following keys:- * @param {string} [options.exclusiveStartKey] All keys up to this one (including) are skipped from the result.- * @return {Promise<void>}- */- forEachKey(iteratee: KeyConsumer, options?: {- exclusiveStartKey?: string;- } | undefined, index?: number): Promise<void>;-}-export function getFileNameRegexp(key: string): RegExp;-/**- * This is a local representation of a key-value store.- *- * @ignore- */-export class KeyValueStoreLocal {- constructor(storeId: any, localStorageDir: any);- localStoragePath: string;- storeId: any;- initializationPromise: any;- getValue(key: any): Promise<any>;- setValue(key: any, value: any, options?: {}): Promise<void>;- delete(): Promise<void>;- drop(): Promise<void>;- forEachKey(iteratee: any, options?: {}, index?: number): Promise<void>;- /**- * Helper function to handle files. Accepts a promisified 'fs' function as a second parameter- * which will be executed against the file saved under the key. Since the file's extension and thus- * full path is not known, it first performs a check against common extensions. If no file is found,- * it will read a full list of files in the directory and attempt to find the file again.- *- * Returns an object when a file is found and handler executes successfully, null otherwise.- *- * @param {string} key- * @param {Function} handler- * @returns {Promise<*>} null or object in the following format:- * {- * returnValue: return value of the handler function,- * fileName: name of the file including found extension- * }- * @ignore- */- _handleFile(key: string, handler: Function): Promise<any>;- /**- * Performs a lookup for a file in the local emulation directory's file list.- * @param {string} key- * @param {Function} handler- * @returns {Promise<*>}- * @ignore- */- _fullDirectoryLookup(key: string, handler: Function): Promise<any>;- /**- * Helper function to resolve file paths.- * @param {string} fileName- * @returns {string}- * @ignore- */- _getPath(fileName: string): string;- /**- * Returns a file:// URL for the given fileName that may be used to- * access the value on the local drive.- *- * Unlike in the remote store where key is sufficient, a full fileName- * must be provided here including the extension for the URL to be valid.- *- * @param {string} fileName- * @return {string}- * @ignore- */- getPublicUrl(fileName: string): string;-}-export function openKeyValueStore(storeIdOrName?: string | undefined, options?: {- forceCloud?: boolean;-} | undefined): Promise<KeyValueStore>;-export function getValue(key: string): Promise<any>;-export function setValue(key: string, value: any, options?: {- contentType?: string;-} | undefined): Promise<void>;-export function getInput(): Promise<any>;-/**- * User-function used in the {@link KeyValueStore#forEachKey} method.- */-export type KeyConsumer = (key: string, index: number, info: any, size: number) => any;diff --git a/types/live_view/live_view_server.d.ts b/types/live_view/live_view_server.d.tsdeleted file mode 100644index b48791cdd..000000000--- a/types/live_view/live_view_server.d.ts+++ /dev/null@@ -1,144 +0,0 @@-/// <reference types="node" />-export default LiveViewServer;-/**- * `LiveViewServer` enables serving of browser snapshots via web sockets. It includes its own client- * that provides a simple frontend to viewing the captured snapshots. A snapshot consists of three- * pieces of information, the currently opened URL, the content of the page (HTML) and its screenshot.- *- * ```json- * {- * "pageUrl": "https://www.example.com",- * "htmlContent": "<html><body> ....",- * "screenshotIndex": 3,- * "createdAt": "2019-04-18T11:50:40.060Z"- * }- * ```- *- * `LiveViewServer` is useful when you want to be able to inspect the current browser status on demand.- * When no client is connected, the webserver consumes very low resources so it should have a close- * to zero impact on performance. Only once a client connects the server will start serving snapshots.- * Once no longer needed, it can be disabled again in the client to remove any performance impact.- *- * NOTE: Screenshot taking in browser typically takes around 300ms. So having the `LiveViewServer`- * always serve snapshots will have a significant impact on performance.- *- * When using {@link PuppeteerPool}, the `LiveViewServer` can be- * easily used just by providing the `useLiveView = true` option to the {@link PuppeteerPool}.- * It can also be initiated via {@link PuppeteerCrawler} `puppeteerPoolOptions`.- *- * It will take snapshots of the first page of the latest browser. Taking snapshots of only a- * single page improves performance and stability dramatically in high concurrency situations.- *- * When running locally, it is often best to use a headful browser for debugging, since it provides- * a better view into the browser, including DevTools, but `LiveViewServer` works too.- */-declare class LiveViewServer {- /**- * @param {Object} [options]- * All `LiveViewServer` parameters are passed- * via an options object with the following keys:- * @param {string} [options.screenshotDirectoryPath]- * By default, the screenshots are saved to- * the `live_view` directory in the Apify local storage directory.- * Provide a different absolute path to change the settings.- * @param {number} [options.maxScreenshotFiles=10]- * Limits the number of screenshots stored- * by the server. This is to prevent using up too much disk space.- * @param {number} [options.snapshotTimeoutSecs=3]- * If a snapshot is not made within the timeout,- * its creation will be aborted. This is to prevent- * pages from being hung up by a stalled screenshot.- * @param {number} [options.maxSnapshotFrequencySecs=2]- * Use this parameter to further decrease the resource consumption- * of `LiveViewServer` by limiting the frequency at which it'll- * serve snapshots.- */- constructor(options?: {- screenshotDirectoryPath?: string;- maxScreenshotFiles?: number;- snapshotTimeoutSecs?: number;- maxSnapshotFrequencySecs?: number;- } | undefined);- screenshotDirectoryPath: string;- maxScreenshotFiles: number;- snapshotTimeoutMillis: number;- maxSnapshotFrequencyMillis: number;- /**- * @type {?Snapshot}- * @private- */- lastSnapshot: Snapshot | null;- lastScreenshotIndex: number;- clientCount: number;- _isRunning: boolean;- httpServer: http.Server | null;- socketio: socketio.Server | null;- servingSnapshot: boolean;- /**- * Starts the HTTP server with web socket connections enabled.- * Snapshots will not be created until a client has connected.- * @return {Promise<void>}- */- start(): Promise<void>;- /**- * Prevents the server from receiving more connections. Existing connections- * will not be terminated, but the server will not prevent a process exit.- * @return {Promise<void>}- */- stop(): Promise<void>;- /**- * Serves a snapshot to all connected clients.- * Screenshots are not served directly, only their index number- * which is used by client to retrieve the screenshot.- *- * Will time out and throw in `options.snapshotTimeoutSecs`.- *- * @param {Page} page- * @return {Promise<void>}- */- serve(page: Page): Promise<void>;- /**- * @return {boolean}- */- isRunning(): boolean;- /**- * @return {boolean}- */- hasClients(): boolean;- /**- * Returns an absolute path to the screenshot with the given index.- * @param {number} screenshotIndex- * @return {string}- * @private- */- _getScreenshotPath(screenshotIndex: number): string;- /**- * @param {Page} page- * @return {Promise<Snapshot>}- * @private- */- _makeSnapshot(page: Page): Promise<Snapshot>;- /**- * @param {Snapshot} snapshot- * @private- */- _pushSnapshot(snapshot: Snapshot): void;- /**- * Initiates an async delete and does not wait for it to complete.- * @param {number} screenshotIndex- * @private- */- _deleteScreenshot(screenshotIndex: number): void;- _setupHttpServer(): void;- port: number | undefined;- liveViewUrl: string | undefined;- /**- * @param {socketio.Socket} socket- * @private- */- _socketConnectionHandler(socket: socketio.Socket): void;-}-import Snapshot from "./snapshot";-import * as http from "http";-import * as socketio from "socket.io";-import { Page } from "puppeteer";diff --git a/types/live_view/snapshot.d.ts b/types/live_view/snapshot.d.tsdeleted file mode 100644index d578bfe0d..000000000--- a/types/live_view/snapshot.d.ts+++ /dev/null@@ -1,29 +0,0 @@-/**- * Represents a live view snapshot to be served by {@link LiveViewServer}.- * @property {string} pageUrl- * @property {string} htmlContent- * @property {number} screenshotIndex- * @property {Date} createdAt- * @ignore- */-export default class Snapshot {- /**- * @param {Object} props- * @param {string} props.pageUrl- * @param {string} props.htmlContent- * @param {number} props.screenshotIndex- */- constructor(props: {- pageUrl: string;- htmlContent: string;- screenshotIndex: number;- });- pageUrl: string;- htmlContent: string;- screenshotIndex: number;- createdAt: Date;- /**- * @return {number}- */- age(): number;-}diff --git a/types/main.d.ts b/types/main.d.tsdeleted file mode 100644index 2e29c5895..000000000--- a/types/main.d.ts+++ /dev/null@@ -1,139 +0,0 @@-/// <reference types="node" />-import { main } from "./actor";-import { getEnv } from "./actor";-import { call } from "./actor";-import { callTask } from "./actor";-import { metamorph } from "./actor";-import { getMemoryInfo } from "./utils";-import { getApifyProxyUrl } from "./actor";-import { isAtHome } from "./utils";-import { apifyClient } from "./utils";-import { addWebhook } from "./actor";-import AutoscaledPool from "./autoscaling/autoscaled_pool";-import BasicCrawler from "./crawlers/basic_crawler";-import CheerioCrawler from "./crawlers/cheerio_crawler";-import { pushData } from "./dataset";-import { openDataset } from "./dataset";-import events from "./events";-import { initializeEvents } from "./events";-import { stopEvents } from "./events";-import { getValue } from "./key_value_store";-import { setValue } from "./key_value_store";-import { getInput } from "./key_value_store";-import { openKeyValueStore } from "./key_value_store";-import { launchPuppeteer } from "./puppeteer";-import PuppeteerPool from "./puppeteer_pool";-import PuppeteerCrawler from "./crawlers/puppeteer_crawler";-import PseudoUrl from "./pseudo_url";-import Request from "./request";-import { RequestList } from "./request_list";-import { openRequestList } from "./request_list";-import { openRequestQueue } from "./request_queue";-import { openSessionPool } from "./session_pool/session_pool";-import LiveViewServer from "./live_view/live_view_server";-import { Session } from "./session_pool/session";-declare const exportedUtils: {- isDocker: (forceReset: boolean) => Promise<boolean>;- sleep: (millis: number) => Promise<void>;- downloadListOfUrls: ({ url, encoding, urlRegExp }: {- url: string;- encoding?: string;- urlRegExp?: RegExp;- }) => Promise<string[]>;- extractUrls: ({ string, urlRegExp }: {- string: string;- urlRegExp?: RegExp;- }) => string[];- getRandomUserAgent: () => string;- htmlToText: (html: string | CheerioStatic) => string;- URL_NO_COMMAS_REGEX: RegExp;- URL_WITH_COMMAS_REGEX: RegExp;- createRequestDebugInfo: (request: Request | import("./request").RequestOptions, response?: import("http").IncomingMessage | import("puppeteer").Response | undefined, additionalFields?: Object | undefined) => any;- parseContentTypeFromResponse: (response: import("http").IncomingMessage) => {- type: string;- charset: string;- };-} & {- puppeteer: {- hideWebDriver: (page: import("puppeteer").Page) => Promise<void>;- injectFile: (page: import("puppeteer").Page, filePath: string, options?: {- surviveNavigations?: boolean;- } | undefined) => Promise<any>;- injectJQuery: (page: import("puppeteer").Page) => Promise<any>;- injectUnderscore: (page: import("puppeteer").Page) => Promise<any>;- enqueueRequestsFromClickableElements: (page: any, selector: any, purls: any, requestQueue: any, requestOpts?: {}) => Promise<any[]>;- enqueueLinks: (...args: any[]) => Promise<import("./request_queue").QueueOperationInfo[] | undefined>;- enqueueLinksByClickingElements: typeof import("./enqueue_links/click_elements").enqueueLinksByClickingElements;- blockRequests: (page: import("puppeteer").Page, options?: {- urlPatterns?: string[];- extraUrlPatterns?: string[];- } | undefined) => Promise<void>;- blockResources: (page: any, resourceTypes?: string[]) => Promise<void>;- cacheResponses: (page: import("puppeteer").Page, cache: Object, responseUrlRules: (string | RegExp)[]) => Promise<void>;- compileScript: (scriptString: string, context?: Object) => Function;- gotoExtended: (page: import("puppeteer").Page, request: Request, gotoOptions?: import("puppeteer").DirectNavigationOptions) => Promise<import("puppeteer").Response | null>;- addInterceptRequestHandler: (page: import("puppeteer").Page, handler: import("./puppeteer_request_interception").InterceptHandler) => Promise<void>;- removeInterceptRequestHandler: (page: import("puppeteer").Page, handler: import("./puppeteer_request_interception").InterceptHandler) => Promise<void>;- infiniteScroll: (page: import("puppeteer").Page, options?: {- timeoutSecs?: number;- waitForSecs?: number;- } | undefined) => Promise<void>;- saveSnapshot: (page: import("puppeteer").Page, options?: {- key?: string;- screenshotQuality?: number;- saveScreenshot?: boolean;- saveHtml?: boolean;- keyValueStoreName?: string;- } | undefined) => Promise<void>;- };- social: {- emailsFromText: (text: string) => string[];- emailsFromUrls: (urls: string[]) => string[];- phonesFromText: (text: string) => string[];- phonesFromUrls: (urls: string[]) => string[];- parseHandlesFromHtml: (html: string, data?: Object) => import("./utils_social").SocialHandles;- EMAIL_REGEX: RegExp;- EMAIL_REGEX_GLOBAL: RegExp;- LINKEDIN_REGEX: RegExp;- LINKEDIN_REGEX_GLOBAL: RegExp;- INSTAGRAM_REGEX: RegExp;- INSTAGRAM_REGEX_GLOBAL: RegExp;- TWITTER_REGEX: RegExp;- TWITTER_REGEX_GLOBAL: RegExp;- FACEBOOK_REGEX: RegExp;- FACEBOOK_REGEX_GLOBAL: RegExp;- YOUTUBE_REGEX: RegExp;- YOUTUBE_REGEX_GLOBAL: RegExp;- };- log: typeof log;- enqueueLinks: typeof enqueueLinks;- requestAsBrowser: (options: import("./utils_request").RequestAsBrowserOptions) => Promise<import("stream").Readable | import("http").IncomingMessage>;-};-import log from "./utils_log";-import { enqueueLinks } from "./enqueue_links/enqueue_links";-export { main, getEnv, call, callTask, metamorph, getMemoryInfo, getApifyProxyUrl, isAtHome, apifyClient as client, addWebhook, AutoscaledPool, BasicCrawler, CheerioCrawler, pushData, openDataset, events, initializeEvents, stopEvents, getValue, setValue, getInput, openKeyValueStore, launchPuppeteer, PuppeteerPool, PuppeteerCrawler, PseudoUrl, Request, RequestList, openRequestList, openRequestQueue, openSessionPool, LiveViewServer, Session, exportedUtils as utils };--export { ApifyEnv, UserFunc } from "./actor";-export { AutoscaledPoolOptions } from "./autoscaling/autoscaled_pool";-export { SnapshotterOptions } from "./autoscaling/snapshotter";-export { SystemInfo, SystemStatusOptions } from "./autoscaling/system_status";-export { BasicCrawlerOptions, HandleRequest, HandleRequestInputs, HandleFailedRequest, HandleFailedRequestInput } from "./crawlers/basic_crawler";-export { CheerioCrawlerOptions, PrepareRequestInputs, PrepareRequest, CheerioHandlePageInputs, CheerioHandlePage } from "./crawlers/cheerio_crawler";-export { PuppeteerCrawlerOptions, PuppeteerHandlePageInputs, PuppeteerHandlePage, PuppeteerGotoInputs, PuppeteerGoto, LaunchPuppeteer } from "./crawlers/puppeteer_crawler";-export { DatasetContent, DatasetConsumer, DatasetMapper, DatasetReducer } from "./dataset";-export { RequestTransform } from "./enqueue_links/shared";-export { KeyConsumer } from "./key_value_store";-export { LaunchPuppeteerOptions } from "./puppeteer";-export { LaunchPuppeteerFunction, PuppeteerPoolOptions } from "./puppeteer_pool";-export { InterceptHandler } from "./puppeteer_request_interception";-export { RequestOptions } from "./request";-export { RequestListOptions, RequestListState } from "./request_list";-export { QueueOperationInfo } from "./request_queue";-export { SessionState, SessionOptions } from "./session_pool/session";-export { CreateSession, SessionPoolOptions } from "./session_pool/session_pool";-export { StealthOptions } from "./stealth/stealth";-export { ActorRun } from "./typedefs";-export { MemoryInfo } from "./utils";-export { LoggerOptions } from "./utils_log";-export { RequestAsBrowserOptions, AbortFunction } from "./utils_request";-export { SocialHandles } from "./utils_social";\ No newline at end of filediff --git a/types/pseudo_url.d.ts b/types/pseudo_url.d.tsdeleted file mode 100644index ecc2e36a8..000000000--- a/types/pseudo_url.d.ts+++ /dev/null@@ -1,85 +0,0 @@-export default PseudoUrl;-/**- * Represents a pseudo-URL (PURL) - an URL pattern used by web crawlers- * to specify which URLs should the crawler visit.- * This class is used by the {@link utils#enqueueLinks} function.- *- * A PURL is simply a URL with special directives enclosed in `[]` brackets.- * Currently, the only supported directive is `[RegExp]`,- * which defines a JavaScript-style regular expression to match against the URL.- *- * The `PseudoUrl` class can be constructed either using a pseudo-URL string- * or a regular expression (an instance of the `RegExp` object).- * With a pseudo-URL string, the matching is always case-insensitive.- * If you need case-sensitive matching, use an appropriate `RegExp` object.- *- * For example, a PURL `http://www.example.com/pages/[(\w|-)*]` will match all of the following URLs:- *- * <ul>- * <li><code>http://www.example.com/pages/</code></li>- * <li><code>http://www.example.com/pages/my-awesome-page</code></li>- * <li><code>http://www.example.com/pages/something</code></li>- * </ul>- *- * Be careful to correctly escape special characters in the pseudo-URL string.- * If either `[` or `]` is part of the normal query string, it must be encoded as `[\x5B]` or `[\x5D]`,- * respectively. For example, the following PURL:- * ```http- * http://www.example.com/search?do[\x5B]load[\x5D]=1- * ```- * will match the URL:- * ```http- * http://www.example.com/search?do[load]=1- * ```- *- * If the regular expression in the pseudo-URL contains a backslash character (\),- * you need to escape it with another back backslash, as shown in the example below.- *- * **Example usage:**- *- * ```javascript- * // Using a pseudo-URL string- * const purl = new Apify.PseudoUrl('http://www.example.com/pages/[(\\w|-)+]', {- * userData: { foo: 'bar' },- * });- *- * // Using a regular expression- * const purl2 = new Apify.PseudoUrl(/http:\/\/www\.example\.com\/pages\/(\w|-)+/);- *- * if (purl.matches('http://www.example.com/pages/my-awesome-page')) console.log('Match!');- * ```- */-declare class PseudoUrl {- /**- * @param {(string|RegExp)} purl- * A pseudo-URL string or a regular expression object.- * Using a `RegExp` instance enables more granular control,- * such as making the matching case sensitive.- * @param {RequestOptions} requestTemplate- * Options for the new {@link Request} instances created for matching URLs- * by the {@link utils#enqueueLinks} function.- */- constructor(purl: string | RegExp, requestTemplate?: RequestOptions);- regex: RegExp;- requestTemplate: RequestOptions;- /**- * Determines whether a URL matches this pseudo-URL pattern.- *- * @param {string} url URL to be matched.- * @return {boolean} Returns `true` if given URL matches pseudo-URL.- */- matches(url: string): boolean;- /**- * Creates a Request object from a provided `requestTemplate` and a given URL- * or an object that specifies ${@link Request} properties. In case of a collision- * the properties will override the template, except for `userData`, which will- * be merged together, with the `userData` property having preference over the template.- * This enables dynamic overriding of the template.- *- * @param {(string|Object)} urlOrProps- * @return {Request}- */- createRequest(urlOrProps: string | Object): Request;-}-import { RequestOptions } from "./request";-import Request from "./request";diff --git a/types/puppeteer.d.ts b/types/puppeteer.d.tsdeleted file mode 100644index 3817d259d..000000000--- a/types/puppeteer.d.ts+++ /dev/null@@ -1,73 +0,0 @@-export function launchPuppeteer(options?: LaunchPuppeteerOptions | undefined): Promise<Browser>;-/**- * Apify extends the launch options of Puppeteer.- * You can use any of the Puppeteer compatible- * [`LaunchOptions`](https://pptr.dev/#?product=Puppeteer&show=api-puppeteerlaunchoptions)- * options in the {@link Apify#launchPuppeteer}- * function and in addition, all the options available below.- */-export type LaunchPuppeteerOptions = {- /**- * URL to a HTTP proxy server. It must define the port number,- * and it may also contain proxy username and password.- *- * Example: `http://bob:[email protected]:1234`.- */- proxyUrl?: string;- /**- * The `User-Agent` HTTP header used by the browser.- * If not provided, the function sets `User-Agent` to a reasonable default- * to reduce the chance of detection of the crawler.- */- userAgent?: string;- /**- * If `true` and `executablePath` is not set,- * Puppeteer will launch full Google Chrome browser available on the machine- * rather than the bundled Chromium. The path to Chrome executable- * is taken from the `APIFY_CHROME_EXECUTABLE_PATH` environment variable if provided,- * or defaults to the typical Google Chrome executable location specific for the operating system.- * By default, this option is `false`.- */- useChrome?: boolean;- /**- * If set to `true`, Puppeteer will be configured to use- * [Apify Proxy](https://my.apify.com/proxy) for all connections.- * For more information, see the [documentation](https://docs.apify.com/proxy)- */- useApifyProxy?: boolean;- /**- * An array of proxy groups to be used- * by the [Apify Proxy](https://docs.apify.com/proxy).- * Only applied if the `useApifyProxy` option is `true`.- */- apifyProxyGroups?: string[];- /**- * Apify Proxy session identifier to be used by all the Chrome browsers.- * All HTTP requests going through the proxy with the same session identifier- * will use the same target proxy server (i.e. the same IP address).- * The identifier can only contain the following characters: `0-9`, `a-z`, `A-Z`, `"."`, `"_"` and `"~"`.- * Only applied if the `useApifyProxy` option is `true`.- */- apifyProxySession?: string;- /**- * Either a require path (`string`) to a package to be used instead of default `puppeteer`,- * or an already required module (`Object`). This enables usage of various Puppeteer- * wrappers such as `puppeteer-extra`.- *- * Take caution, because it can cause all kinds of unexpected errors and weird behavior.- * Apify SDK is not tested with any other library besides `puppeteer` itself.- */- puppeteerModule?: string | Object;- /**- * This setting hides most of the known properties that identify headless Chrome and makes it nearly undetectable.- * It is recommended to use it together with the `useChrome` set to `true`.- */- stealth?: boolean;- /**- * Using this configuration, you can disable some of the hiding tricks.- * For these settings to take effect `stealth` must be set to true- */- stealthOptions?: StealthOptions;-};-import { Browser } from "puppeteer";-import { StealthOptions } from "./stealth/stealth";diff --git a/types/puppeteer_pool.d.ts b/types/puppeteer_pool.d.tsdeleted file mode 100644index b7b368a24..000000000--- a/types/puppeteer_pool.d.ts+++ /dev/null@@ -1,348 +0,0 @@-export const BROWSER_SESSION_KEY_NAME: "APIFY_SESSION";-export default PuppeteerPool;-export type LaunchPuppeteerFunction = (options: LaunchPuppeteerOptions) => Promise<Browser>;-export type PuppeteerPoolOptions = {- /**- * Enables the use of a preconfigured {@link LiveViewServer} that serves snapshots- * just before a page would be recycled by `PuppeteerPool`. If there are no clients- * connected, it has close to zero impact on performance.- */- useLiveView?: boolean;- /**- * Maximum number of open pages (i.e. tabs) per browser. When this limit is reached, new pages are loaded in a new browser instance.- */- maxOpenPagesPerInstance?: number;- /**- * Maximum number of requests that can be processed by a single browser instance.- * After the limit is reached, the browser is retired and new requests are- * handled by a new browser instance.- */- retireInstanceAfterRequestCount?: number;- /**- * All browser management operations such as launching a new browser, opening a new page- * or closing a page will timeout after the set number of seconds and the connected- * browser will be retired.- */- puppeteerOperationTimeoutSecs?: number;- /**- * Indicates how often are the open Puppeteer instances checked whether they can be closed.- */- instanceKillerIntervalSecs?: number;- /**- * When Puppeteer instance reaches the `retireInstanceAfterRequestCount` limit then- * it is considered retired and no more tabs will be opened. After the last tab is closed the- * whole browser is closed too. This parameter defines a time limit between the last tab was opened and- * before the browser is closed even if there are pending open tabs.- */- killInstanceAfterSecs?: number;- /**- * Overrides the default function to launch a new Puppeteer instance.- * The function must return a promise resolving to- * [`Browser`](https://github.com/GoogleChrome/puppeteer/blob/master/docs/api.md#class-browser) instance.- * See the source code on- * [GitHub](https://github.com/apifytech/apify-js/blob/master/src/puppeteer_pool.js#L28)- * for the default implementation.- */- launchPuppeteerFunction?: LaunchPuppeteerFunction;- /**- * Options used by {@link Apify#launchPuppeteer} to start new Puppeteer instances.- */- launchPuppeteerOptions?: LaunchPuppeteerOptions;- /**- * Enables recycling of disk cache directories by Chrome instances.- * When a browser instance is closed, its disk cache directory is not deleted but it's used by a newly opened browser instance.- * This is useful to reduce amount of data that needs to be downloaded to speed up crawling and reduce proxy usage.- * Note that the new browser starts with empty cookies, local storage etc. so this setting doesn't affect anonymity of your crawler.- *- * Beware that the disk cache directories can consume a lot of disk space.- * To limit the space consumed, you can pass the `--disk-cache-size=X` argument to `launchPuppeteerargs`,- * where `X` is the approximate maximum number of bytes for disk cache.- *- * Do not use the `recycleDiskCache` setting together with `--disk-cache-dir`- * argument in `launchPuppeteerargs`, the behavior is undefined.- */- recycleDiskCache?: boolean;- /**- * With this option selected, all pages will be opened in a new incognito browser context, which means- * that they will not share cookies or cache and their resources will not be throttled by one another.- */- useIncognitoPages?: boolean;- /**- * An array of custom proxy URLs to be used by the `PuppeteerPool` instance.- * The provided custom proxies' order will be randomized and the resulting list rotated.- * Custom proxies are not compatible with Apify Proxy and an attempt to use both- * configuration options will cause an error to be thrown on startup.- */- proxyUrls?: string[];-};-/**- * @callback LaunchPuppeteerFunction- * @param {LaunchPuppeteerOptions} options- * @returns {Promise<Browser>}- */-/**- * @typedef PuppeteerPoolOptions- * @property {boolean} [useLiveView]- * Enables the use of a preconfigured {@link LiveViewServer} that serves snapshots- * just before a page would be recycled by `PuppeteerPool`. If there are no clients- * connected, it has close to zero impact on performance.- * @property {number} [maxOpenPagesPerInstance=50]- * Maximum number of open pages (i.e. tabs) per browser. When this limit is reached, new pages are loaded in a new browser instance.- * @property {number} [retireInstanceAfterRequestCount=100]- * Maximum number of requests that can be processed by a single browser instance.- * After the limit is reached, the browser is retired and new requests are- * handled by a new browser instance.- * @property {number} [puppeteerOperationTimeoutSecs=15]- * All browser management operations such as launching a new browser, opening a new page- * or closing a page will timeout after the set number of seconds and the connected- * browser will be retired.- * @property {number} [instanceKillerIntervalSecs=60]- * Indicates how often are the open Puppeteer instances checked whether they can be closed.- * @property {number} [killInstanceAfterSecs=300]- * When Puppeteer instance reaches the `retireInstanceAfterRequestCount` limit then- * it is considered retired and no more tabs will be opened. After the last tab is closed the- * whole browser is closed too. This parameter defines a time limit between the last tab was opened and- * before the browser is closed even if there are pending open tabs.- * @property {LaunchPuppeteerFunction} [launchPuppeteerFunction]- * Overrides the default function to launch a new Puppeteer instance.- * The function must return a promise resolving to- * [`Browser`](https://github.com/GoogleChrome/puppeteer/blob/master/docs/api.md#class-browser) instance.- * See the source code on- * [GitHub](https://github.com/apifytech/apify-js/blob/master/src/puppeteer_pool.js#L28)- * for the default implementation.- * @property {LaunchPuppeteerOptions} [launchPuppeteerOptions]- * Options used by {@link Apify#launchPuppeteer} to start new Puppeteer instances.- * @property {boolean} [recycleDiskCache=false]- * Enables recycling of disk cache directories by Chrome instances.- * When a browser instance is closed, its disk cache directory is not deleted but it's used by a newly opened browser instance.- * This is useful to reduce amount of data that needs to be downloaded to speed up crawling and reduce proxy usage.- * Note that the new browser starts with empty cookies, local storage etc. so this setting doesn't affect anonymity of your crawler.- *- * Beware that the disk cache directories can consume a lot of disk space.- * To limit the space consumed, you can pass the `--disk-cache-size=X` argument to `launchPuppeteerargs`,- * where `X` is the approximate maximum number of bytes for disk cache.- *- * Do not use the `recycleDiskCache` setting together with `--disk-cache-dir`- * argument in `launchPuppeteerargs`, the behavior is undefined.- * @property {boolean} [useIncognitoPages]- * With this option selected, all pages will be opened in a new incognito browser context, which means- * that they will not share cookies or cache and their resources will not be throttled by one another.- * @property {string[]} [proxyUrls]- * An array of custom proxy URLs to be used by the `PuppeteerPool` instance.- * The provided custom proxies' order will be randomized and the resulting list rotated.- * Custom proxies are not compatible with Apify Proxy and an attempt to use both- * configuration options will cause an error to be thrown on startup.- */-/**- * Manages a pool of Chrome browser instances controlled using- * [Puppeteer](https://github.com/GoogleChrome/puppeteer).- *- * `PuppeteerPool` reuses Chrome instances and tabs using specific browser rotation and retirement policies.- * This is useful in order to facilitate rotation of proxies, cookies- * or other settings in order to prevent detection of your web scraping bot,- * access web pages from various countries etc.- *- * Additionally, the reuse of browser instances instances speeds up crawling,- * and the retirement of instances helps mitigate effects of memory leaks in Chrome.- *- * `PuppeteerPool` is internally used by the {@link PuppeteerCrawler} class.- *- * **Example usage:**- *- * ```javascript- * const puppeteerPool = new PuppeteerPool({- * launchPuppeteerFunction: () => {- * // Use a new proxy with a new IP address for each new Chrome instance- * return Apify.launchPuppeteer({- * useApifyProxy: true,- * apifyProxySession: Math.random(),- * });- * },- * });- *- * const page1 = await puppeteerPool.newPage();- * const page2 = await puppeteerPool.newPage();- * const page3 = await puppeteerPool.newPage();- *- * // ... do something with the pages ...- *- * // Close all browsers.- * await puppeteerPool.destroy();- * ```- */-declare class PuppeteerPool {- /**- * @param {PuppeteerPoolOptions} [options]- * All `PuppeteerPool` parameters are passed- * via an options object.- */- constructor(options?: PuppeteerPoolOptions | undefined);- sessionPool: any;- reusePages: boolean;- maxOpenPagesPerInstance: any;- retireInstanceAfterRequestCount: any;- puppeteerOperationTimeoutMillis: number;- killInstanceAfterMillis: any;- /**- * @type {*}- * @ignore- */- recycledDiskCacheDirs: any;- useIncognitoPages: any;- proxyUrls: any[] | null;- liveViewServer: LiveViewServer | null;- launchPuppeteerFunction: () => Promise<any>;- browserCounter: number;- activeInstances: {};- retiredInstances: {};- lastUsedProxyUrlIndex: number;- instanceKillerInterval: NodeJS.Timeout;- idlePages: any[];- closedPages: WeakSet<object>;- pagesToInstancesMap: WeakMap<object, any>;- liveViewSnapshotsInProgress: WeakMap<object, any>;- sigintListener: () => void;- _retireBrowserWithSession(session: any): Promise<void>;- /**- * Launches new browser instance.- *- * @ignore- */- _launchInstance(): PuppeteerInstance;- /**- * Takes care of async processes in PuppeteerInstance construction with a Browser.- * @param {Promise<Browser>} browserPromise- * @param {PuppeteerInstance} instance- * @returns {Promise<void>}- * @ignore- */- _initBrowser(browserPromise: Promise<Browser>, instance: PuppeteerInstance): Promise<void>;- /**- * Retires some of the instances for example due to many uses.- *- * @ignore- */- _retireInstance(instance: any): void;- /**- * Kills all the retired instances that:- * - have all tabs closed- * - or are inactive for more then killInstanceAfterMillis.- *- * @ignore- */- _killRetiredInstances(): void;- /**- * Kills given browser instance.- *- * @ignore- */- _killInstance(instance: any): Promise<void>;- /**- * Kills all running PuppeteerInstances.- * @ignore- */- _killAllInstances(): void;- /**- * Updates the instance metadata when a new page is opened.- *- * @param {PuppeteerInstance} instance- * @ignore- */- _incrementPageCount(instance: PuppeteerInstance): void;- /**- * Produces a new page instance either by reusing an idle page that currently isn't processing- * any request or by spawning a new page (new browser tab) in one of the available- * browsers when no idle pages are available.- *- * To spawn a new browser tab for each page, set the `reusePages` constructor option to false.- *- * @return {Promise<Page>}- */- newPage(): Promise<Page>;- /**- * Opens new tab in one of the browsers in the pool and returns a `Promise`- * that resolves to an instance of a Puppeteer- * [`Page`](https://pptr.dev/#?product=Puppeteer&show=api-class-page).- *- * @return {Promise<Page>}- * @ignore- */- _openNewTab(): Promise<Page>;- /**- * Adds the necessary boilerplate to allow page reuse and also- * captures page.close() errors to prevent meaningless log clutter.- * @param {Page} page- * @ignore- */- _decoratePage(page: Page): Page;- /**- * Tells Chromium to focus oldest tab. This is to work around Chromium- * throttling CPU and network in inactive tabs.- *- * @param {Browser} browser- * @ignore- */- _focusOldestTab(browser: Browser): Promise<void>;- /**- * Closes all open browsers.- * @return {Promise<void>}- */- destroy(): Promise<void>;- /**- * Finds a PuppeteerInstance given a Puppeteer Browser running in the instance.- * @param {Browser} browser- * @return {Promise<*>}- * @ignore- */- _findInstanceByBrowser(browser: Browser): Promise<any>;- /**- * Manually retires a Puppeteer- * [`Browser`](https://pptr.dev/#?product=Puppeteer&show=api-class-browser)- * instance from the pool. The browser will continue to process open pages so that they may gracefully finish.- * This is unlike `browser.close()` which will forcibly terminate the browser and all open pages will be closed.- * @param {Browser} browser- * @return {Promise<void>}- */- retire(browser: Browser): Promise<void>;- /**- * Closes the page, unless the `reuseTabs` option is set to true.- * Then it would only flag the page for a future reuse, without actually closing it.- *- * NOTE: LiveView snapshotting is tied to this function. When `useLiveView` option- * is set to true, a snapshot of the page will be taken just before closing the page- * or flagging it for reuse.- *- * @param {Page} page- * @return {Promise<void>}- */- recyclePage(page: Page): Promise<void>;- /**- * Tells the connected LiveViewServer to serve a snapshot when available.- *- * @param {Page} page- * @return {Promise<void>}- */- serveLiveViewSnapshot(page: Page): Promise<void>;- _findInstancesBySession(session: any): any[];- _killInstanceWithNoPages(instance: any): void;-}-import { LaunchPuppeteerOptions } from "./puppeteer";-import { Browser } from "puppeteer";-import LiveViewServer from "./live_view/live_view_server";-/**- * Internal representation of Puppeteer instance.- *- * @ignore- */-declare class PuppeteerInstance {- constructor(id: any, browserPromise: any);- id: any;- activePages: number;- totalPages: number;- browserPromise: any;- lastPageOpenedAt: number;- killed: boolean;- childProcess: any;- recycleDiskCacheDir: any;-}-import { Page } from "puppeteer";diff --git a/types/puppeteer_request_interception.d.ts b/types/puppeteer_request_interception.d.tsdeleted file mode 100644index 8cb356bec..000000000--- a/types/puppeteer_request_interception.d.ts+++ /dev/null@@ -1,5 +0,0 @@-export function addInterceptRequestHandler(page: Page, handler: InterceptHandler): Promise<void>;-export function removeInterceptRequestHandler(page: Page, handler: InterceptHandler): Promise<void>;-export type InterceptHandler = (request: PuppeteerRequest) => any;-import { Page } from "puppeteer";-import { Request as PuppeteerRequest } from "puppeteer";diff --git a/types/puppeteer_utils.d.ts b/types/puppeteer_utils.d.tsdeleted file mode 100644index e25ce83da..000000000--- a/types/puppeteer_utils.d.ts+++ /dev/null@@ -1,52 +0,0 @@-export function gotoExtended(page: Page, request: Request, gotoOptions?: DirectNavigationOptions): Promise<Response | null>;-export function infiniteScroll(page: Page, options?: {- timeoutSecs?: number;- waitForSecs?: number;-} | undefined): Promise<void>;-export namespace puppeteerUtils {- export { hideWebDriver };- export { injectFile };- export { injectJQuery };- export { injectUnderscore };- export { enqueueRequestsFromClickableElements };- export function enqueueLinks(...args: any[]): Promise<import("./request_queue").QueueOperationInfo[] | undefined>;- export { enqueueLinksByClickingElements };- export { blockRequests };- export { blockResources };- export { cacheResponses };- export { compileScript };- export { gotoExtended };- export { addInterceptRequestHandler };- export { removeInterceptRequestHandler };- export { infiniteScroll };- export { saveSnapshot };-}-import { Page } from "puppeteer";-import Request from "./request";-import { DirectNavigationOptions } from "puppeteer";-import { Response } from "puppeteer";-declare function hideWebDriver(page: Page): Promise<void>;-declare function injectFile(page: Page, filePath: string, options?: {- surviveNavigations?: boolean;-} | undefined): Promise<any>;-declare function injectJQuery(page: Page): Promise<any>;-declare function injectUnderscore(page: Page): Promise<any>;-declare function enqueueRequestsFromClickableElements(page: any, selector: any, purls: any, requestQueue: any, requestOpts?: {}): Promise<any[]>;-import { enqueueLinksByClickingElements } from "./enqueue_links/click_elements";-declare function blockRequests(page: Page, options?: {- urlPatterns?: string[];- extraUrlPatterns?: string[];-} | undefined): Promise<void>;-declare function blockResources(page: any, resourceTypes?: string[]): Promise<void>;-declare function cacheResponses(page: Page, cache: Object, responseUrlRules: (string | RegExp)[]): Promise<void>;-declare function compileScript(scriptString: string, context?: Object): Function;-import { addInterceptRequestHandler } from "./puppeteer_request_interception";-import { removeInterceptRequestHandler } from "./puppeteer_request_interception";-declare function saveSnapshot(page: Page, options?: {- key?: string;- screenshotQuality?: number;- saveScreenshot?: boolean;- saveHtml?: boolean;- keyValueStoreName?: string;-} | undefined): Promise<void>;-export {};diff --git a/types/request.d.ts b/types/request.d.tsdeleted file mode 100644index a4aa13f10..000000000--- a/types/request.d.ts+++ /dev/null@@ -1,177 +0,0 @@-export function computeUniqueKey({ url, method, payload, keepUrlFragment, useExtendedUniqueKey }: {- url: any;- method: any;- payload: any;- keepUrlFragment: any;- useExtendedUniqueKey: any;-}): any;-export function hashPayload(payload: any): string;-export default Request;-/**- * Specifies required and optional fields for constructing a {@link Request}.- */-export type RequestOptions = {- /**- * URL of the web page to crawl. It must be a non-empty string.- */- url: string;- /**- * A unique key identifying the request.- * Two requests with the same `uniqueKey` are considered as pointing to the same URL.- *- * If `uniqueKey` is not provided, then it is automatically generated by normalizing the URL.- * For example, the URL of `HTTP://www.EXAMPLE.com/something/` will produce the `uniqueKey`- * of `http://www.example.com/something`.- *- * The `keepUrlFragment` option determines whether URL hash fragment is included in the `uniqueKey` or not.- *- * The `useExtendedUniqueKey` options determines whether method and payload are included in the `uniqueKey`,- * producing a `uniqueKey` in the following format: `METHOD(payloadHash):normalizedUrl`. This is useful- * when requests point to the same URL, but with different methods and payloads. For example: form submits.- *- * Pass an arbitrary non-empty text value to the `uniqueKey` property- * to override the default behavior and specify which URLs shall be considered equal.- */- uniqueKey?: string;- method?: string;- /**- * HTTP request payload, e.g. for POST requests.- */- payload?: string | Buffer;- /**- * HTTP headers in the following format:- * ```- * {- * Accept: 'text/html',- * 'Content-Type': 'application/json'- * }- * ```- */- headers?: Object;- /**- * Custom user data assigned to the request. Use this to save any request related data to the- * request's scope, keeping them accessible on retries, failures etc.- */- userData?: any;- /**- * If `false` then the hash part of a URL is removed when computing the `uniqueKey` property.- * For example, this causes the `http://www.example.com#foo` and `http://www.example.com#bar` URLs- * to have the same `uniqueKey` of `http://www.example.com` and thus the URLs are considered equal.- * Note that this option only has an effect if `uniqueKey` is not set.- */- keepUrlFragment?: boolean;- /**- * If `true` then the `uniqueKey` is computed not only from the URL, but also from the method and payload- * properties. This is useful when making requests to the same URL that are differentiated by method- * or payload, such as form submit navigations in browsers.- */- useExtendedUniqueKey?: boolean;-};-/**- * Represents a URL to be crawled, optionally including HTTP method, headers, payload and other metadata.- * The `Request` object also stores information about errors that occurred during processing of the request.- *- * Each `Request` instance has the `uniqueKey` property, which can be either specified- * manually in the constructor or generated automatically from the URL. Two requests with the same `uniqueKey`- * are considered as pointing to the same web resource. This behavior applies to all Apify SDK classes,- * such as {@link RequestList}, {@link RequestQueue} or {@link PuppeteerCrawler}.- *- * Example use:- *- * ```javascript- * const request = new Apify.Request({- * url: 'http://www.example.com',- * headers: { Accept: 'application/json' },- * });- *- * ...- *- * request.userData.foo = 'bar';- * request.pushErrorMessage(new Error('Request failed!'));- *- * ...- *- * const foo = request.userData.foo;- * ```- *- * @property {string} id- * Request ID- * @property {string} url- * URL of the web page to crawl.- * @property {string} loadedUrl- * An actually loaded URL after redirects, if present. HTTP redirects are guaranteed- * to be included.- *- * When using {@link PuppeteerCrawler}, meta tag and JavaScript redirects may,- * or may not be included, depending on their nature. This generally means that redirects,- * which happen immediately will most likely be included, but delayed redirects will not.- * @property {string} uniqueKey- * A unique key identifying the request.- * Two requests with the same `uniqueKey` are considered as pointing to the same URL.- * @property {string} method- * HTTP method, e.g. `GET` or `POST`.- * @property {(string|Buffer)} payload- * HTTP request payload, e.g. for POST requests.- * @property {boolean} noRetry- * The `true` value indicates that the request will not be automatically retried on error.- * @property {number} retryCount- * Indicates the number of times the crawling of the request has been retried on error.- * @property {string[]} errorMessages- * An array of error messages from request processing.- * @property {Object} headers- * Object with HTTP headers. Key is header name, value is the value.- * @property {object} userData- * Custom user data assigned to the request.- * @property {Date} handledAt- * Indicates the time when the request has been processed.- * Is `null` if the request has not been crawled yet.- */-declare class Request {- /**- * @param {RequestOptions} options- * `Request` parameters including the URL, HTTP method and headers, and others.- */- constructor(options?: RequestOptions);- id: any;- url: string;- loadedUrl: any;- uniqueKey: any;- method: string;- payload: any;- noRetry: any;- retryCount: any;- errorMessages: any;- headers: any;- userData: any;- handledAt: Date | null;- /**- * Stores information about an error that occurred during processing of this request.- *- * You should always use Error instances when throwing errors in JavaScript.- *- * Nevertheless, to improve the debugging experience when using third party libraries- * that may not always throw an Error instance, the function performs a type- * inspection of the passed argument and attempts to extract as much information- * as possible, since just throwing a bad type error makes any debugging rather difficult.- *- * @param {(Error|string)} errorOrMessage Error object or error message to be stored in the request.- * @param {Object} [options]- * @param {boolean} [options.omitStack=false] Only push the error message without stack trace when true.- */- pushErrorMessage(errorOrMessage: string | Error, options?: {- omitStack?: boolean;- } | undefined): void;- /**- * Flags the request with no retry which prevents {@link BasicCrawler}- * (as well as {@PuppeteerCrawler} and {@CheerioCrawler}, since they use {@BasicCrawler} internally)- * from retrying the request after an error occurs.- *- * Optionally accepts a message that will be used to construct- * and throw an Error.- *- * @param {string} [message]- * @deprecated 2019/06/26- * @ignore- */- doNotRetry(message?: string | undefined): void;-}diff --git a/types/request_list.d.ts b/types/request_list.d.tsdeleted file mode 100644index d0802847f..000000000--- a/types/request_list.d.ts+++ /dev/null@@ -1,533 +0,0 @@-export const STATE_PERSISTENCE_KEY: "REQUEST_LIST_STATE";-export const REQUESTS_PERSISTENCE_KEY: "REQUEST_LIST_REQUESTS";-/**- * @typedef RequestListOptions- * @property {Array<RequestOptions|Request|string>} [sources]- * An array of sources of URLs for the {@link RequestList}. It can be either an array of strings,- * plain objects that define at least the `url` property, or an array of {@link Request} instances.- *- * **IMPORTANT:** The `sources` array will be consumed (left empty) after `RequestList` initializes.- * This is a measure to prevent memory leaks in situations when millions of sources are- * added.- *- * Additionally, the `requestsFromUrl` property may be used instead of `url`,- * which will instruct `RequestList` to download the source URLs from a given remote location.- * The URLs will be parsed from the received response.- *- * ```- * [- * // A single URL- * 'http://example.com/a/b',- *- * // Modify Request options- * { method: PUT, 'https://example.com/put, payload: { foo: 'bar' }}- *- * // Batch import of URLs from a file hosted on the web,- * // where the URLs should be requested using the HTTP POST request- * { method: 'POST', requestsFromUrl: 'http://example.com/urls.txt' },- *- * // Batch import from remote file, using a specific regular expression to extract the URLs.- * { requestsFromUrl: 'http://example.com/urls.txt', regex: /https:\/\/example.com\/.+/ },- *- * // Get list of URLs from a Google Sheets document. Just add "/gviz/tq?tqx=out:csv" to the Google Sheet URL.- * // For details, see https://help.apify.com/en/articles/2906022-scraping-a-list-of-urls-from-a-google-sheets-document- * { requestsFromUrl: 'https://docs.google.com/spreadsheets/d/1GA5sSQhQjB_REes8I5IKg31S-TuRcznWOPjcpNqtxmU/gviz/tq?tqx=out:csv' }- * ]- * ```- * @property {Function} [sourcesFunction]- * A function that will be called to get the sources for the `RequestList`, but only if `RequestList`- * was not able to fetch their persisted version (see {@link RequestListOptions.persistRequestsKey}).- * It must return an `Array` of {@link Request} or {@link RequestOptions}.- *- * This is very useful in a scenario when getting the sources is a resource intensive or time consuming- * task, such as fetching URLs from multiple sitemaps or parsing URLs from large datasets. Using the- * `sourcesFunction` in combination with `persistStateKey` and `persistRequestsKey` will allow you to- * fetch and parse those URLs only once, saving valuable time when your actor migrates or restarts.- *- * If both {@link RequestListOptions.sources} and {@link RequestListOptions.sourcesFunction} are provided,- * the sources returned by the function will be added after the `sources`.- *- * **Example:**- * ```javascript- * // Let's say we want to scrape URLs extracted from sitemaps.- *- * const sourcesFunction = async () => {- * // With super large sitemaps, this operation could take very long- * // and big websites typically have multiple sitemaps.- * const sitemaps = await downloadHugeSitemaps();- * return parseUrlsFromSitemaps(sitemaps);- * }- *- * // Sitemaps can change in real-time, so it's important to persist- * // the URLs we collected. Otherwise we might lose our scraping- * // state in case of an actor migration / failure / time-out.- * const requestList = new RequestList({- * sourcesFunction,- * persistStateKey: 'state-key',- * persistRequestsKey: 'requests-key',- * })- *- * // The sourcesFunction is called now and the Requests are persisted.- * // If something goes wrong and we need to start again, RequestList- * // will load the persisted Requests from storage and will NOT- * // call the sourcesFunction again, saving time and resources.- * await requestList.initialize();- * ```- * @property {string} [persistStateKey]- * Identifies the key in the default key-value store under which `RequestList` periodically stores its- * state (i.e. which URLs were crawled and which not).- * If the actor is restarted, `RequestList` will read the state- * and continue where it left off.- *- * If `persistStateKey` is not set, `RequestList` will always start from the beginning,- * and all the source URLs will be crawled again.- * @property {string} [persistRequestsKey]- * Identifies the key in the default key-value store under which the `RequestList` persists its- * Requests during the {@link RequestList#initialize} call.- * This is necessary if `persistStateKey` is set and the source URLs might potentially change,- * to ensure consistency of the source URLs and state object. However, it comes with some- * storage and performance overheads.- *- * If `persistRequestsKey` is not set, {@link RequestList#initialize} will always fetch the sources- * from their origin, check that they are consistent with the restored state (if any)- * and throw an error if they are not.- * @property {RequestListState} [state]- * The state object that the `RequestList` will be initialized from.- * It is in the form as returned by `RequestList.getState()`, such as follows:- *- * ```- * {- * nextIndex: 5,- * nextUniqueKey: 'unique-key-5'- * inProgress: {- * 'unique-key-1': true,- * 'unique-key-4': true,- * },- * }- * ```- *- * Note that the preferred (and simpler) way to persist the state of crawling of the `RequestList`- * is to use the `stateKeyPrefix` parameter instead.- * @property {boolean} [keepDuplicateUrls=false]- * By default, `RequestList` will deduplicate the provided URLs. Default deduplication is based- * on the `uniqueKey` property of passed source {@link Request} objects.- *- * If the property is not present, it is generated by normalizing the URL. If present, it is kept intact.- * In any case, only one request per `uniqueKey` is added to the `RequestList` resulting in removal- * of duplicate URLs / unique keys.- *- * Setting `keepDuplicateUrls` to `true` will append an additional identifier to the `uniqueKey`- * of each request that does not already include a `uniqueKey`. Therefore, duplicate- * URLs will be kept in the list. It does not protect the user from having duplicates in user set- * `uniqueKey`s however. It is the user's responsibility to ensure uniqueness of their unique keys- * if they wish to keep more than just a single copy in the `RequestList`.- */-/**- * Represents a static list of URLs to crawl.- * The URLs can be provided either in code or parsed from a text file hosted on the web.- *- * Each URL is represented using an instance of the {@link Request} class.- * The list can only contain unique URLs. More precisely, it can only contain `Request` instances- * with distinct `uniqueKey` properties. By default, `uniqueKey` is generated from the URL, but it can also be overridden.- * To add a single URL to the list multiple times, corresponding {@link Request} objects will need to have different- * `uniqueKey` properties. You can use the `keepDuplicateUrls` option to do this for you when initializing the- * `RequestList` from sources.- *- * Once you create an instance of `RequestList`, you need to call the {@link RequestList#initialize} function- * before the instance can be used. After that, no more URLs can be added to the list.- *- * `RequestList` is used by {@link BasicCrawler}, {@link CheerioCrawler}- * and {@link PuppeteerCrawler} as a source of URLs to crawl.- * Unlike {@link RequestQueue}, `RequestList` is static but it can contain even millions of URLs.- *- * `RequestList` has an internal state where it stores information about which requests were already handled,- * which are in progress and which were reclaimed. The state may be automatically persisted to the default- * {@link KeyValueStore} by setting the `persistStateKey` option so that if the Node.js process is restarted,- * the crawling can continue where it left off. The automated persisting is launched upon receiving the `persistState`- * event that is periodically emitted by {@link events|Apify.events}.- *- * The internal state is closely tied to the provided sources (URLs). If the sources change on actor restart, the state will become corrupted and- * `RequestList` will raise an exception. This typically happens when the sources is a list of URLs downloaded from the web.- * In such case, use the `persistRequestsKey` option in conjunction with `persistStateKey`,- * to make the `RequestList` store the initial sources to the default key-value store and load them after restart,- * which will prevent any issues that a live list of URLs might cause.- *- * **Basic usage:**- * ```javascript- * // Use a helper function to simplify request list initialization.- * // State and sources are automatically persisted.- * const requestList = await Apify.openRequestList('my-request-list', [- * 'http://www.example.com/page-1',- * { url: 'http://www.example.com/page-2', method: 'POST', userData: { foo: 'bar' }},- * { requestsFromUrl: 'http://www.example.com/my-url-list.txt', userData: { isFromUrl: true } },- * ]);- * ```- *- * **Advanced usage:**- * ```javascript- * // Use the constructor to get more control over the initialization.- * const requestList = new Apify.RequestList({- * sources: [- * // Separate requests- * { url: 'http://www.example.com/page-1', method: 'GET', headers: { ... } },- * { url: 'http://www.example.com/page-2', userData: { foo: 'bar' }},- *- * // Bulk load of URLs from file `http://www.example.com/my-url-list.txt`- * // Note that all URLs must start with http:// or https://- * { requestsFromUrl: 'http://www.example.com/my-url-list.txt', userData: { isFromUrl: true } },- * ],- *- * // Persist only state in cases where the original sources are immutable to improve performance.- * persistStateKey: 'my-state',- * });- *- * await requestList.initialize();- * ```- */-export class RequestList {- /**- * @param {RequestListOptions} options All `RequestList` configuration options- */- constructor(options?: RequestListOptions);- requests: any[];- nextIndex: number;- uniqueKeyToIndex: {};- inProgress: {};- reclaimed: {};- persistStateKey: string;- persistRequestsKey: any;- initialState: RequestListState;- keepDuplicateUrls: boolean;- isStatePersisted: boolean;- areRequestsPersisted: boolean;- isLoading: boolean;- isInitialized: boolean;- sources: (string | Request | RequestOptions)[];- sourcesFunction: Function;- /**- * Loads all remote sources of URLs and potentially starts periodic state persistence.- * This function must be called before you can start using the instance in a meaningful way.- *- * @returns {Promise<void>}- */- initialize(): Promise<void>;- /**- * Adds previously persisted Requests, as retrieved from the key-value store.- * This needs to be done in a memory efficient way. We should update the input- * to a Stream once apify-client supports streams.- * @param {Buffer} persistedRequests- * @ignore- */- _addPersistedRequests(persistedRequests: Buffer): Promise<void>;- /**- * Add Requests from both options.sources and options.sourcesFunction.- * This function is called only when persisted sources were not loaded.- * We need to avoid keeping both sources and requests in memory- * to reduce memory footprint with very large sources.- * @returns {Promise<void>}- * @ignore- */- _addRequestsFromSources(): Promise<void>;- /**- * Persists the current state of the `RequestList` into the default {@link KeyValueStore}.- * The state is persisted automatically in regular intervals, but calling this method manually- * is useful in cases where you want to have the most current state available after you pause- * or stop fetching its requests. For example after you pause or abort a crawl. Or just before- * a server migration.- *- * @return {Promise<void>}- */- persistState(): Promise<void>;- /**- * Unlike persistState(), this is used only internally, since the sources- * are automatically persisted at RequestList initialization (if the persistRequestsKey is set),- * but there's no reason to persist it again afterwards, because RequestList is immutable.- *- * @return {Promise<void>}- * @ignore- */- _persistRequests(): Promise<void>;- /**- * Restores RequestList state from a state object.- *- * @param {RequestListState} state- * @ignore- */- _restoreState(state: RequestListState): void;- /**- * Attempts to load state and requests using the `RequestList` configuration- * and returns a tuple of [state, requests] where each may be null if not loaded.- *- * @return {Promise<Array<(RequestListState|null)>>}- * @ignore- */- _loadStateAndPersistedRequests(): Promise<(RequestListState | null)[]>;- /**- * Returns an object representing the internal state of the `RequestList` instance.- * Note that the object's fields can change in future releases.- *- * @returns {RequestListState}- */- getState(): RequestListState;- /**- * Resolves to `true` if the next call to {@link RequestList#fetchNextRequest} function- * would return `null`, otherwise it resolves to `false`.- * Note that even if the list is empty, there might be some pending requests currently being processed.- *- * @returns {Promise<Boolean>}- */- isEmpty(): Promise<boolean>;- /**- * Returns `true` if all requests were already handled and there are no more left.- *- * @returns {Promise<Boolean>}- */- isFinished(): Promise<boolean>;- /**- * Gets the next {@link Request} to process. First, the function gets a request previously reclaimed- * using the {@link RequestList#reclaimRequest} function, if there is any.- * Otherwise it gets the next request from sources.- *- * The function's `Promise` resolves to `null` if there are no more- * requests to process.- *- * @returns {Promise<(Request|null)>}- */- fetchNextRequest(): Promise<Request | null>;- /**- * Marks request as handled after successful processing.- *- * @param {Request} request- * @returns {Promise<void>}- */- markRequestHandled(request: Request): Promise<void>;- /**- * Reclaims request to the list if its processing failed.- * The request will become available in the next `this.fetchNextRequest()`.- *- * @param {Request} request- * @returns {Promise<void>}- */- reclaimRequest(request: Request): Promise<void>;- /**- * Adds all fetched requests from a URL from a remote resource.- *- * @ignore- */- _addFetchedRequests(source: any, fetchedRequests: any): Promise<void>;- /**- * Fetches URLs from requestsFromUrl and returns them in format of list of requests- * @param source- * @return {Promise<Array<RequestOptions>>}- * @ignore- */- _fetchRequestsFromUrl(source: any): Promise<RequestOptions[]>;- /**- * Adds given request.- * If the `source` parameter is a string or plain object and not an instance- * of a `Request`, then the function creates a `Request` instance.- *- * @param {string|Request|object} source- * @ignore- */- _addRequest(source: any): void;- /**- * Helper function that validates unique key.- * Throws an error if uniqueKey is not a non-empty string.- *- * @ignore- */- _ensureUniqueKeyValid(uniqueKey: any): void;- /**- * Checks that request is not reclaimed and throws an error if so.- *- * @ignore- */- _ensureInProgressAndNotReclaimed(uniqueKey: any): void;- /**- * Throws an error if request list wasn't initialized.- *- * @ignore- */- _ensureIsInitialized(): void;- /**- * Returns the total number of unique requests present in the `RequestList`.- *- * @returns {number}- */- length(): number;- /**- * Returns number of handled requests.- *- * @returns {number}- */- handledCount(): number;-}-export function openRequestList(listName: string | null, sources: (string | Request | RequestOptions)[], options?: RequestListOptions | undefined): Promise<RequestList>;-export type RequestListOptions = {- /**- * An array of sources of URLs for the {@link RequestList}. It can be either an array of strings,- * plain objects that define at least the `url` property, or an array of {@link Request} instances.- *- * **IMPORTANT:** The `sources` array will be consumed (left empty) after `RequestList` initializes.- * This is a measure to prevent memory leaks in situations when millions of sources are- * added.- *- * Additionally, the `requestsFromUrl` property may be used instead of `url`,- * which will instruct `RequestList` to download the source URLs from a given remote location.- * The URLs will be parsed from the received response.- *- * ```- * [- * // A single URL- * 'http://example.com/a/b',- *- * // Modify Request options- * { method: PUT, 'https://example.com/put, payload: { foo: 'bar' }}- *- * // Batch import of URLs from a file hosted on the web,- * // where the URLs should be requested using the HTTP POST request- * { method: 'POST', requestsFromUrl: 'http://example.com/urls.txt' },- *- * // Batch import from remote file, using a specific regular expression to extract the URLs.- * { requestsFromUrl: 'http://example.com/urls.txt', regex: /https:\/\/example.com\/.+/ },- *- * // Get list of URLs from a Google Sheets document. Just add "/gviz/tq?tqx=out:csv" to the Google Sheet URL.- * // For details, see https://help.apify.com/en/articles/2906022-scraping-a-list-of-urls-from-a-google-sheets-document- * { requestsFromUrl: 'https://docs.google.com/spreadsheets/d/1GA5sSQhQjB_REes8I5IKg31S-TuRcznWOPjcpNqtxmU/gviz/tq?tqx=out:csv' }- * ]- * ```- */- sources?: (string | Request | RequestOptions)[];- /**- * A function that will be called to get the sources for the `RequestList`, but only if `RequestList`- * was not able to fetch their persisted version (see {@link RequestListOptions.persistRequestsKey}).- * It must return an `Array` of {@link Request} or {@link RequestOptions}.- *- * This is very useful in a scenario when getting the sources is a resource intensive or time consuming- * task, such as fetching URLs from multiple sitemaps or parsing URLs from large datasets. Using the- * `sourcesFunction` in combination with `persistStateKey` and `persistRequestsKey` will allow you to- * fetch and parse those URLs only once, saving valuable time when your actor migrates or restarts.- *- * If both {@link RequestListOptions.sources} and {@link RequestListOptions.sourcesFunction} are provided,- * the sources returned by the function will be added after the `sources`.- *- * **Example:**- * ```javascript- * // Let's say we want to scrape URLs extracted from sitemaps.- *- * const sourcesFunction = async () => {- * // With super large sitemaps, this operation could take very long- * // and big websites typically have multiple sitemaps.- * const sitemaps = await downloadHugeSitemaps();- * return parseUrlsFromSitemaps(sitemaps);- * }- *- * // Sitemaps can change in real-time, so it's important to persist- * // the URLs we collected. Otherwise we might lose our scraping- * // state in case of an actor migration / failure / time-out.- * const requestList = new RequestList({- * sourcesFunction,- * persistStateKey: 'state-key',- * persistRequestsKey: 'requests-key',- * })- *- * // The sourcesFunction is called now and the Requests are persisted.- * // If something goes wrong and we need to start again, RequestList- * // will load the persisted Requests from storage and will NOT- * // call the sourcesFunction again, saving time and resources.- * await requestList.initialize();- * ```- */- sourcesFunction?: Function;- /**- * Identifies the key in the default key-value store under which `RequestList` periodically stores its- * state (i.e. which URLs were crawled and which not).- * If the actor is restarted, `RequestList` will read the state- * and continue where it left off.- *- * If `persistStateKey` is not set, `RequestList` will always start from the beginning,- * and all the source URLs will be crawled again.- */- persistStateKey?: string;- /**- * Identifies the key in the default key-value store under which the `RequestList` persists its- * Requests during the {@link RequestList#initialize} call.- * This is necessary if `persistStateKey` is set and the source URLs might potentially change,- * to ensure consistency of the source URLs and state object. However, it comes with some- * storage and performance overheads.- *- * If `persistRequestsKey` is not set, {@link RequestList#initialize} will always fetch the sources- * from their origin, check that they are consistent with the restored state (if any)- * and throw an error if they are not.- */- persistRequestsKey?: string;- /**- * The state object that the `RequestList` will be initialized from.- * It is in the form as returned by `RequestList.getState()`, such as follows:- *- * ```- * {- * nextIndex: 5,- * nextUniqueKey: 'unique-key-5'- * inProgress: {- * 'unique-key-1': true,- * 'unique-key-4': true,- * },- * }- * ```- *- * Note that the preferred (and simpler) way to persist the state of crawling of the `RequestList`- * is to use the `stateKeyPrefix` parameter instead.- */- state?: RequestListState;- /**- * By default, `RequestList` will deduplicate the provided URLs. Default deduplication is based- * on the `uniqueKey` property of passed source {@link Request} objects.- *- * If the property is not present, it is generated by normalizing the URL. If present, it is kept intact.- * In any case, only one request per `uniqueKey` is added to the `RequestList` resulting in removal- * of duplicate URLs / unique keys.- *- * Setting `keepDuplicateUrls` to `true` will append an additional identifier to the `uniqueKey`- * of each request that does not already include a `uniqueKey`. Therefore, duplicate- * URLs will be kept in the list. It does not protect the user from having duplicates in user set- * `uniqueKey`s however. It is the user's responsibility to ensure uniqueness of their unique keys- * if they wish to keep more than just a single copy in the `RequestList`.- */- keepDuplicateUrls?: boolean;-};-/**- * Represents state of a {@link RequestList}. It can be used to resume a {@link RequestList} which has been previously processed.- * You can obtain the state by calling {@link RequestList#getState} and receive an object with- * the following structure:- *- * ```- * {- * nextIndex: 5,- * nextUniqueKey: 'unique-key-5'- * inProgress: {- * 'unique-key-1': true,- * 'unique-key-4': true- * },- * }- * ```- */-export type RequestListState = {- /**- * Position of the next request to be processed.- */- nextIndex: number;- /**- * Key of the next request to be processed.- */- nextUniqueKey: string;- /**- * An object mapping request keys to a boolean value respresenting whether they are being processed at the moment.- */- inProgress: {- [x: string]: boolean;- };-};-import Request from "./request";-import { RequestOptions } from "./request";diff --git a/types/request_queue.d.ts b/types/request_queue.d.tsdeleted file mode 100644index 54543be4a..000000000--- a/types/request_queue.d.ts+++ /dev/null@@ -1,364 +0,0 @@-export const LOCAL_STORAGE_SUBDIR: string;-export const QUERY_HEAD_MIN_LENGTH: 100;-export const QUERY_HEAD_BUFFER: 3;-export const API_PROCESSED_REQUESTS_DELAY_MILLIS: number;-export const MAX_QUERIES_FOR_CONSISTENCY: 6;-export const STORAGE_CONSISTENCY_DELAY_MILLIS: 3000;-/**- * A helper class that is used to report results from various- * {@link RequestQueue} functions as well as- * {@link utils#enqueueLinks}.- *- * @typedef QueueOperationInfo- * @property {boolean} wasAlreadyPresent Indicates if request was already present in the queue.- * @property {boolean} wasAlreadyHandled Indicates if request was already marked as handled.- * @property {string} requestId The ID of the added request- * @property {Request} request The original {@link Request} object passed to the `RequestQueue` function.- */-/**- * Represents a queue of URLs to crawl, which is used for deep crawling of websites- * where you start with several URLs and then recursively- * follow links to other pages. The data structure supports both breadth-first and depth-first crawling orders.- *- * Each URL is represented using an instance of the {@link Request} class.- * The queue can only contain unique URLs. More precisely, it can only contain {@link Request} instances- * with distinct `uniqueKey` properties. By default, `uniqueKey` is generated from the URL, but it can also be overridden.- * To add a single URL multiple times to the queue,- * corresponding {@link Request} objects will need to have different `uniqueKey` properties.- *- * Do not instantiate this class directly, use the- * {@link Apify#openRequestQueue} function instead.- *- * `RequestQueue` is used by {@link BasicCrawler}, {@link CheerioCrawler}- * and {@link PuppeteerCrawler} as a source of URLs to crawl.- * Unlike {@link RequestList}, `RequestQueue` supports dynamic adding and removing of requests.- * On the other hand, the queue is not optimized for operations that add or remove a large number of URLs in a batch.- *- * `RequestQueue` stores its data either on local disk or in the Apify Cloud,- * depending on whether the `APIFY_LOCAL_STORAGE_DIR` or `APIFY_TOKEN` environment variable is set.- *- * If the `APIFY_LOCAL_STORAGE_DIR` environment variable is set, the queue data is stored in- * that local directory as follows:- * ```- * {APIFY_LOCAL_STORAGE_DIR}/request_queues/{QUEUE_ID}/{STATE}/{NUMBER}.json- * ```- * Note that `{QUEUE_ID}` is the name or ID of the request queue. The default queue has ID: `default`,- * unless you override it by setting the `APIFY_DEFAULT_REQUEST_QUEUE_ID` environment variable.- * Each request in the queue is stored as a separate JSON file, where `{STATE}` is either `handled` or `pending`,- * and `{NUMBER}` is an integer indicating the position of the request in the queue.- *- * If the `APIFY_TOKEN` environment variable is set but `APIFY_LOCAL_STORAGE_DIR` not, the data is stored in the- * [Apify Request Queue](https://docs.apify.com/storage/request-queue)- * cloud storage. Note that you can force usage of the cloud storage also by passing the `forceCloud`- * option to {@link Apify#openRequestQueue} function,- * even if the `APIFY_LOCAL_STORAGE_DIR` variable is set.- *- * **Example usage:**- *- * ```javascript- * // Open the default request queue associated with the actor run- * const queue = await Apify.openRequestQueue();- *- * // Open a named request queue- * const queueWithName = await Apify.openRequestQueue('some-name');- *- * // Enqueue few requests- * await queue.addRequest({ url: 'http://example.com/aaa' });- * await queue.addRequest({ url: 'http://example.com/bbb' });- * await queue.addRequest({ url: 'http://example.com/foo/bar' }, { forefront: true });- *- * // Get requests from queue- * const request1 = await queue.fetchNextRequest();- * const request2 = await queue.fetchNextRequest();- * const request3 = await queue.fetchNextRequest();- *- * // Mark a request as handled- * await queue.markRequestHandled(request1);- *- * // If processing of a request fails then reclaim it back to the queue, so that it's crawled again- * await queue.reclaimRequest(request2);- * ```- * @hideconstructor- */-export class RequestQueue {- /**- * @param {string} queueId- * @param {string} [queueName]- * @param {string} [clientKey]- */- constructor(queueId: string, queueName?: string | undefined, clientKey?: string | undefined);- clientKey: string;- queueId: string;- queueName: string | undefined;- /**- * @type {*}- * @ignore- */- queueHeadDict: any;- queryQueueHeadPromise: any;- inProgress: Set<any>;- recentlyHandled: any;- assumedTotalCount: number;- assumedHandledCount: number;- requestsCache: any;- /**- * @ignore- */- inProgressCount(): number;- /**- * Adds a request to the queue.- *- * If a request with the same `uniqueKey` property is already present in the queue,- * it will not be updated. You can find out whether this happened from the resulting- * {@link QueueOperationInfo} object.- *- * To add multiple requests to the queue by extracting links from a webpage,- * see the {@link utils#enqueueLinks} helper function.- *- * @param {(Request|RequestOptions)} request {@link Request} object or vanilla object with request data.- * Note that the function sets the `uniqueKey` and `id` fields to the passed object.- * @param {Object} [options]- * @param {boolean} [options.forefront=false] If `true`, the request will be added to the foremost position in the queue.- * @return {Promise<QueueOperationInfo>}- */- addRequest(request: Request | RequestOptions, options?: {- forefront?: boolean;- } | undefined): Promise<QueueOperationInfo>;- /**- * Gets the request from the queue specified by ID.- *- * @param {string} requestId ID of the request.- * @return {Promise<(Request | null)>} Returns the request object, or `null` if it was not found.- */- getRequest(requestId: string): Promise<Request | null>;- /**- * Returns a next request in the queue to be processed, or `null` if there are no more pending requests.- *- * Once you successfully finish processing of the request, you need to call- * {@link RequestQueue#markRequestHandled}- * to mark the request as handled in the queue. If there was some error in processing the request,- * call {@link RequestQueue#reclaimRequest} instead,- * so that the queue will give the request to some other consumer in another call to the `fetchNextRequest` function.- *- * Note that the `null` return value doesn't mean the queue processing finished,- * it means there are currently no pending requests.- * To check whether all requests in queue were finished,- * use {@link RequestQueue#isFinished} instead.- *- * @returns {Promise<(Request|null)>}- * Returns the request object or `null` if there are no more pending requests.- */- fetchNextRequest(): Promise<Request | null>;- /**- * Marks a request that was previously returned by the- * {@link RequestQueue#fetchNextRequest}- * function as handled after successful processing.- * Handled requests will never again be returned by the `fetchNextRequest` function.- *- * @param {Request} request- * @return {Promise<QueueOperationInfo>}- */- markRequestHandled(request: Request): Promise<QueueOperationInfo>;- /**- * Reclaims a failed request back to the queue, so that it can be returned for processed later again- * by another call to {@link RequestQueue#fetchNextRequest}.- * The request record in the queue is updated using the provided `request` parameter.- * For example, this lets you store the number of retries or error messages for the request.- *- * @param {Request} request- * @param {Object} [options]- * @param {boolean} [options.forefront=false]- * If `true` then the request it placed to the beginning of the queue, so that it's returned- * in the next call to {@link RequestQueue#fetchNextRequest}.- * By default, it's put to the end of the queue.- * @return {Promise<QueueOperationInfo>}- */- reclaimRequest(request: Request, options?: {- forefront?: boolean;- } | undefined): Promise<QueueOperationInfo>;- /**- * Resolves to `true` if the next call to {@link RequestQueue#fetchNextRequest}- * would return `null`, otherwise it resolves to `false`.- * Note that even if the queue is empty, there might be some pending requests currently being processed.- * If you need to ensure that there is no activity in the queue, use {@link RequestQueue#isFinished}.- *- * @returns {Promise<boolean>}- */- isEmpty(): Promise<boolean>;- /**- * Resolves to `true` if all requests were already handled and there are no more left.- * Due to the nature of distributed storage used by the queue,- * the function might occasionally return a false negative,- * but it will never return a false positive.- *- * @returns {Promise<boolean>}- */- isFinished(): Promise<boolean>;- /**- * Caches information about request to beware of unneeded addRequest() calls.- *- * @ignore- */- _cacheRequest(cacheKey: any, queueOperationInfo: any): void;- /**- * We always request more items than is in progress to ensure that something falls into head.- *- * @param {boolean} [ensureConsistency=false] If true then query for queue head is retried until queueModifiedAt- * is older than queryStartedAt by at least API_PROCESSED_REQUESTS_DELAY_MILLIS to ensure that queue- * head is consistent.- * @param {number} [limit] How many queue head items will be fetched.- * @param {number} [iteration] Used when this function is called recursively to limit the recursion.- * @return {Promise<boolean>} Indicates if queue head is consistent (true) or inconsistent (false).- * @ignore- */- _ensureHeadIsNonEmpty(ensureConsistency?: boolean | undefined, limit?: number | undefined, iteration?: number | undefined): Promise<boolean>;- /**- * Adds a request straight to the queueHeadDict, to improve performance.- * @private- */- _maybeAddRequestToQueueHead(requestId: any, forefront: any): void;- /**- * Removes the queue either from the Apify Cloud storage or from the local directory,- * depending on the mode of operation.- *- * @return {Promise<void>}- */- drop(): Promise<void>;- /** @ignore */- delete(): Promise<void>;- /**- * Returns the number of handled requests.- *- * This function is just a convenient shortcut for:- *- * ```javascript- * const { handledRequestCount } = await queue.getInfo();- * ```- *- * @return {Promise<number>}- */- handledCount(): Promise<number>;- /**- * Returns an object containing general information about the request queue.- *- * The function returns the same object as the Apify API Client's- * [getQueue](https://docs.apify.com/api/apify-client-js/latest#ApifyClient-requestQueues)- * function, which in turn calls the- * [Get request queue](https://apify.com/docs/api/v2#/reference/request-queues/queue/get-request-queue)- * API endpoint.- *- * **Example:**- * ```- * {- * id: "WkzbQMuFYuamGv3YF",- * name: "my-queue",- * userId: "wRsJZtadYvn4mBZmm",- * createdAt: new Date("2015-12-12T07:34:14.202Z"),- * modifiedAt: new Date("2015-12-13T08:36:13.202Z"),- * accessedAt: new Date("2015-12-14T08:36:13.202Z"),- * totalRequestCount: 25,- * handledRequestCount: 5,- * pendingRequestCount: 20,- * }- * ```- *- * @returns {Promise<object>}- */- getInfo(): Promise<any>;-}-/**- * Local directory-based implementation of the `RequestQueue` class.- * TODO: We should implement this class using the RequestQueueRemote, just replace- * the underlying API calls with their emulation on filesystem. That will bring- * all the goodies such as caching and will enable better and more consistent testing- *- * @ignore- */-export class RequestQueueLocal {- constructor(queueId: any, localStorageDir: any);- queueId: any;- localStoragePath: string;- localHandledEmulationPath: string;- localPendingEmulationPath: string;- queueOrderNoCounter: number;- pendingCount: number;- _handledCount: number;- inProgressCount: number;- requestIdToQueueOrderNo: {};- queueOrderNoInProgress: {};- requestsBeingWrittenToFile: Map<any, any>;- createdAt: Date | null;- modifiedAt: Date | null;- accessedAt: Date | null;- initializationPromise: Promise<void>;- _initialize(): Promise<void>;- _saveRequestIdToQueueOrderNo(filepath: any): Promise<void>;- _getFilePath(queueOrderNo: any, isHandled?: boolean): string;- _getQueueOrderNo(forefront?: boolean): number;- _getRequestByQueueOrderNo(queueOrderNo: any): Promise<Request>;- addRequest(request: any, opts?: {}): Promise<{- requestId: any;- wasAlreadyHandled: any;- wasAlreadyPresent: boolean;- request: any;- }>;- getRequest(requestId: any): Promise<any>;- fetchNextRequest(): Promise<Request | null>;- markRequestHandled(request: any): Promise<{- requestId: any;- wasAlreadyHandled: boolean;- wasAlreadyPresent: boolean;- request: any;- }>;- reclaimRequest(request: any, opts?: {}): Promise<{- requestId: any;- wasAlreadyHandled: boolean;- wasAlreadyPresent: boolean;- request: any;- }>;- isEmpty(): Promise<boolean>;- isFinished(): Promise<boolean>;- drop(): Promise<void>;- delete(): Promise<void>;- handledCount(): Promise<number>;- getInfo(): Promise<{- id: any;- name: any;- userId: string | null;- createdAt: Date | null;- modifiedAt: Date | null;- accessedAt: Date | null;- totalRequestCount: number;- handledRequestCount: number;- pendingRequestCount: number;- }>;- _updateMetadata(isModified: any): void;-}-export function openRequestQueue(queueIdOrName?: string | undefined, options?: {- forceCloud?: boolean;-} | undefined): Promise<RequestQueue>;-/**- * A helper class that is used to report results from various- * {@link RequestQueue} functions as well as- * {@link utils#enqueueLinks}.- */-export type QueueOperationInfo = {- /**- * Indicates if request was already present in the queue.- */- wasAlreadyPresent: boolean;- /**- * Indicates if request was already marked as handled.- */- wasAlreadyHandled: boolean;- /**- * The ID of the added request- */- requestId: string;- /**- * The original {@link Request} object passed to the `RequestQueue` function.- */- request: Request;-};-import Request from "./request";-import { RequestOptions } from "./request";diff --git a/types/serialization.d.ts b/types/serialization.d.tsdeleted file mode 100644index 05ee8a4e2..000000000--- a/types/serialization.d.ts+++ /dev/null@@ -1,4 +0,0 @@-export function serializeArray(data: any[]): Promise<Buffer>;-export function deserializeArray(compressedData: Buffer): Promise<any[]>;-export function createDeserialize(compressedData: any): stream.Readable;-import * as stream from "stream";diff --git a/types/session_pool/errors.d.ts b/types/session_pool/errors.d.tsdeleted file mode 100644index 115a6952b..000000000--- a/types/session_pool/errors.d.ts+++ /dev/null@@ -1,7 +0,0 @@-export class CookieParseError extends Error {- /**- * @param {string} cookieHeaderString- */- constructor(cookieHeaderString: string);- cookieHeaderString: string;-}diff --git a/types/session_pool/events.d.ts b/types/session_pool/events.d.tsdeleted file mode 100644index 5cf171881..000000000--- a/types/session_pool/events.d.ts+++ /dev/null@@ -1,4 +0,0 @@-declare namespace _default {- export const SESSION_RETIRED: string;-}-export default _default;diff --git a/types/session_pool/session.d.ts b/types/session_pool/session.d.tsdeleted file mode 100644index 2b451e8f7..000000000--- a/types/session_pool/session.d.ts+++ /dev/null@@ -1,256 +0,0 @@-/// <reference types="node" />-/**- * Persistable {@link Session} state.- * @typedef SessionState- * @property {string} id- * @property {CookieJar} cookieJar- * @property {object} userData- * @property {number} errorScore- * @property {number} maxErrorScore- * @property {number} errorScoreDecrement- * @property {number} usageCount- * @property {string} expiresAt- * @property {string} createdAt- */-/**- * @typedef SessionOptions- * @property {string} [id] - Id of session used for generating fingerprints. It is used as proxy session name.- * @property {number} [maxAgeSecs=3000] - Number of seconds after which the session is considered as expired.- * @property {object} [userData] - Object where custom user data can be stored. For example custom headers.- * @property {number} [maxErrorScore=3] - Maximum number of marking session as blocked usage.- * If the `errorScore` reaches the `maxErrorScore` session is marked as block and it is thrown away.- * It starts at 0. Calling the `markBad` function increases the `errorScore` by 1.- * Calling the `markGood` will decrease the `errorScore` by `errorScoreDecrement`- * @property {number} [errorScoreDecrement=0.5] - It is used for healing the session.- * For example: if your session is marked bad two times, but it is successful on the third attempt it's errorScore is decremented by this- * number.- * @property {Date} [createdAt] - Date of creation.- * @property {Date} [expiresAt] - Date of expiration.- * @property {number} [usageCount=0] - Indicates how many times the session has been used.- * @property {number} [errorCount=0] - Indicates how many times the session is marked bad.- * @property {number} [maxUsageCount=50] - Session should be used only a limited amount of times.- * This number indicates how many times the session is going to be used, before it is thrown away.- * @property {SessionPool} sessionPool - SessionPool instance. Session will emit the `sessionRetired` event on this instance.- */-/**- * Sessions are used to store information such as cookies and can be used for generating fingerprints and proxy sessions.- * You can imagine each session as a specific user, with its own cookies, IP (via proxy) and potentially a unique browser fingerprint.- * Session internal state can be enriched with custom user data for example some authorization tokens and specific headers in general.- *- */-export class Session {- /**- * Session configuration.- *- * @param {SessionOptions} options- */- constructor(options?: SessionOptions);- /**- * @type {CookieJar}- * @private- */- cookieJar: CookieJar;- id: string;- maxAgeSecs: number;- userData: any;- maxErrorScore: number;- errorScoreDecrement: number;- expiresAt: Date;- createdAt: Date;- usageCount: number;- errorScore: any;- maxUsageCount: number;- sessionPool: SessionPool;- /**- * indicates whether the session is blocked.- * Session is blocked once it reaches the `maxErrorScore`.- * @return {boolean}- */- isBlocked(): boolean;- /**- * Indicates whether the session is expired.- * Session expiration is determined by the `maxAgeSecs`.- * Once the session is older than `createdAt + maxAgeSecs` the session is considered expired.- * @return {boolean}- */- isExpired(): boolean;- /**- * Indicates whether the session is used maximum number of times.- * Session maximum usage count can be changed by `maxUsageCount` parameter.- * @return {boolean}- */- isMaxUsageCountReached(): boolean;- /**- * Indicates whether the session can be used for next requests.- * Session is usable when it is not expired, not blocked and the maximum usage count has not be reached.- * @return {boolean}- */- isUsable(): boolean;- /**- * This method should be called after a successful session usage.- * It increases `usageCount` and potentially lowers the `errorScore` by the `errorScoreDecrement`.- */- markGood(): void;- /**- * Gets session state for persistence in KeyValueStore.- * @return {SessionState} represents session internal state.- */- getState(): SessionState;- /**- * Marks session as blocked and emits event on the `SessionPool`- * This method should be used if the session usage was unsuccessful- * and you are sure that it is because of the session configuration and not any external matters.- * For example when server returns 403 status code.- * If the session does not work due to some external factors as server error such as 5XX you probably want to use `markBad` method.- */- retire(): void;- /**- * Increases usage and error count.- * Should be used when the session has been used unsuccessfully. For example because of timeouts.- */- markBad(): void;- /**- * With certain status codes: `401`, `403` or `429` we can be certain- * that the target website is blocking us. This function helps to do this conveniently- * by retiring the session when such code is received. Optionally the default status- * codes can be extended in the second parameter.- * @param statusCode {number} - HTTP status code- * @param [blockedStatusCodes] {number[]} - Custom HTTP status codes that means blocking on particular website.- * @return {boolean} whether the session was retired.- */- retireOnBlockedStatusCodes(statusCode: number, blockedStatusCodes?: number[] | undefined): boolean;- /**- * Saves cookies from an HTTP response to be used with the session.- * It expects an object with a `headers` property that's either an `Object`- * (typical Node.js responses) or a `Function` (Puppeteer Response).- *- * It then parses and saves the cookies from the `set-cookie` header, if available.-- * @param {(PuppeteerResponse|IncomingMessage)} response- */- setCookiesFromResponse(response: IncomingMessage | PuppeteerResponse): void;- /**- * Saves an array with cookie objects to be used with the session.- * The objects should be in the format that- * [Puppeteer uses](https://pptr.dev/#?product=Puppeteer&version=v2.0.0&show=api-pagecookiesurls),- * but you can also use this function to set cookies manually:- *- * ```- * [- * { name: 'cookie1', value: 'my-cookie' },- * { name: 'cookie2', value: 'your-cookie' }- * ]- * ```- *- * @param {PuppeteerCookie[]} cookies- * @param {string} url- */- setPuppeteerCookies(cookies: PuppeteerCookie[], url: string): void;- /**- * Returns cookies in a format compatible with puppeteer and ready to be used with `page.setCookie`.- * @param {string} url website url. Only cookies stored for this url will be returned- * @return {PuppeteerCookie[]}- */- getPuppeteerCookies(url: string): PuppeteerCookie[];- /**- * Returns cookies saved with the session in the typical- * key1=value1; key2=value2 format, ready to be used in- * a cookie header or elsewhere.- * @param {string} url- * @return {string} - represents `Cookie` header.- */- getCookieString(url: string): string;- /**- * Transforms puppeteer cookie to tough-cookie.- * @param {PuppeteerCookie} puppeteerCookie Cookie from puppeteer `page.cookies method.- * @return {Cookie}- * @private- */- _puppeteerCookieToTough(puppeteerCookie: PuppeteerCookie): Cookie;- /**- * Transforms tough-cookie to puppeteer cookie .- * @param {Cookie} toughCookie - Cookie from CookieJar- * @return {PuppeteerCookie} - Cookie from Puppeteer- * @private- */- _toughCookieToPuppeteer(toughCookie: Cookie): PuppeteerCookie;- /**- * Sets cookies.- * @param {Cookie[]} cookies- * @param {string} url- * @private- */- _setCookies(cookies: Cookie[], url: string): void;-}-/**- * Persistable {@link Session} state.- */-export type SessionState = {- id: string;- cookieJar: CookieJar;- userData: any;- errorScore: number;- maxErrorScore: number;- errorScoreDecrement: number;- usageCount: number;- expiresAt: string;- createdAt: string;-};-export type SessionOptions = {- /**- * - Id of session used for generating fingerprints. It is used as proxy session name.- */- id?: string;- /**- * - Number of seconds after which the session is considered as expired.- */- maxAgeSecs?: number;- /**- * - Object where custom user data can be stored. For example custom headers.- */- userData?: any;- /**- * - Maximum number of marking session as blocked usage.- * If the `errorScore` reaches the `maxErrorScore` session is marked as block and it is thrown away.- * It starts at 0. Calling the `markBad` function increases the `errorScore` by 1.- * Calling the `markGood` will decrease the `errorScore` by `errorScoreDecrement`- */- maxErrorScore?: number;- /**- * - It is used for healing the session.- * For example: if your session is marked bad two times, but it is successful on the third attempt it's errorScore is decremented by this- * number.- */- errorScoreDecrement?: number;- /**- * - Date of creation.- */- createdAt?: Date;- /**- * - Date of expiration.- */- expiresAt?: Date;- /**- * - Indicates how many times the session has been used.- */- usageCount?: number;- /**- * - Indicates how many times the session is marked bad.- */- errorCount?: number;- /**- * - Session should be used only a limited amount of times.- * This number indicates how many times the session is going to be used, before it is thrown away.- */- maxUsageCount?: number;- /**- * - SessionPool instance. Session will emit the `sessionRetired` event on this instance.- */- sessionPool: SessionPool;-};-import { CookieJar } from "tough-cookie";-import { SessionPool } from "./session_pool";-import { IncomingMessage } from "http";-import { Response as PuppeteerResponse } from "puppeteer";-import { Cookie as PuppeteerCookie } from "puppeteer";-import { Cookie } from "tough-cookie";diff --git a/types/session_pool/session_pool.d.ts b/types/session_pool/session_pool.d.tsdeleted file mode 100644index 555a00ea5..000000000--- a/types/session_pool/session_pool.d.ts+++ /dev/null@@ -1,208 +0,0 @@-/**- * Factory user-function which creates customized {@link Session} instances.- * @callback CreateSession- * @param {SessionPool} sessionPool Pool requesting the new session.- * @returns {Session}- */-/**- * @typedef SessionPoolOptions- * @property {number} [maxPoolSize=1000] - Maximum size of the pool.- * Indicates how many sessions are rotated.- * @property {SessionOptions} [sessionOptions] The configuration options for {Session} instances.- * @property {string} [persistStateKeyValueStoreId] - Name or Id of `KeyValueStore` where is the `SessionPool` state stored.- * @property {string} [persistStateKey="SESSION_POOL_STATE"] - Session pool persists it's state under this key in Key value store.- * @property {CreateSession} [createSessionFunction] - Custom function that should return `Session` instance.- * Function receives `SessionPool` instance as a parameter- */-/**- * Handles the sessions rotation, creation and persistence.- * Creates a pool of {@link Session} instances, that are randomly rotated.- * When some session is marked as blocked. It is removed and new one is created instead.- * Learn more in the [`Session management guide`](/docs/guides/session-management).- *- * Session pool is by default persisted in default {@link KeyValueStore}.- * If you want to have one pool for all runs you have to specify- * {@link SessionPoolOptions.persistStateKeyValueStoreId}.- *- * **Example usage:**- *- * ```javascript- * const sessionPool = new SessionPool({- * maxPoolSize: 25,- * sessionOptions:{- * maxAgeSecs: 10,- * maxUsageCount: 150, // for example when you know that the site blocks after 150 requests.- * },- * persistStateKeyValueStoreId: 'my-key-value-store-for-sessions',- * persistStateKey: 'my-session-pool',- * });- *- * // Now you have to initialize the `SessionPool`.- * // If you already have a persisted state in the selected `KeyValueState`.- * // The Session pool is recreated, otherwise it creates a new one.- * // It also attaches listener to `Apify.events` so it is persisted periodically and not after every change.- * await sessionPool.initialize();- *- * // Get random session from the pool- * const session1 = await sessionPool.getSession();- * const session2 = await sessionPool.getSession();- * const session3 = await sessionPool.getSession();- *- * // Now you can mark the session either failed of successful- *- * // Marks session as bad after unsuccessful usage -> it increases error count (soft retire)- * session1.markBad()- *- * // Marks as successful.- * session2.markGood()- *- * // Retires session -> session is removed from the pool- * session3.retire()- *- * ```- * @hideconstructor- */-export class SessionPool extends EventEmitter {- /**- * Session pool configuration.- * @param {SessionPoolOptions} [options] All `SessionPool` configuration options.- */- constructor(options?: SessionPoolOptions | undefined);- maxPoolSize: number;- createSessionFunction: any;- sessionOptions: {};- persistStateKeyValueStoreId: any;- persistStateKey: string;- keyValueStore: import("../key_value_store").KeyValueStore | null;- sessions: any[];- /**- * Gets count of usable sessions in the pool.- * @return {number}- */- get usableSessionsCount(): number;- /**- * Gets count of retired sessions in the pool.- * @return {number}- */- get retiredSessionsCount(): number;- /**- * Starts periodic state persistence and potentially loads SessionPool state from {@link KeyValueStore}.- * This function must be called before you can start using the instance in a meaningful way.- *- * @return {Promise<void>}- */- initialize(): Promise<void>;- _listener: (() => Promise<void>) | undefined;- /**- * Gets session.- * If there is space for new session, it creates and return new session.- * If the session pool is full, it picks a session from the pool,- * If the picked session is usable it is returned, otherwise it creates and returns a new one.- *- * @return {Promise<Session>}- */- getSession(): Promise<Session>;- /**- * Returns an object representing the internal state of the `SessionPool` instance.- * Note that the object's fields can change in future releases.- */- getState(): {- usableSessionsCount: number;- retiredSessionsCount: number;- sessions: any[];- };- /**- * Persists the current state of the `SessionPool` into the default {@link KeyValueStore}.- * The state is persisted automatically in regular intervals.- *- * @return {Promise<void>}- */- persistState(): Promise<void>;- /**- * Removes listener from `persistState` event.- * This function should be called after you are done with using the `SessionPool` instance.- */- teardown(): Promise<void>;- /**- * Removes `Session` instance from `SessionPool`.- * @param {Session} session - Session to be removed- * @private- */- _removeSession(session: Session): void;- /**- * Adds `Session` instance to `SessionPool`.- * @param {Session} newSession `Session` instance to be added.- * @private- */- _addSession(newSession: Session): void;- /**- * Gets random index.- * @return {number}- * @private- */- _getRandomIndex(): number;- /**- * Creates new session without any extra behavior.- * @param {SessionPool} sessionPool- * @return {Session} - New session.- * @private- */- _defaultCreateSessionFunction(sessionPool: SessionPool): Session;- /**- * Creates new session and adds it to the pool.- * @return {Promise<Session>} - Newly created `Session` instance.- * @private- */- _createSession(): Promise<Session>;- /**- * Decides whether there is enough space for creating new session.- * @return {boolean}- * @private- */- _hasSpaceForSession(): boolean;- /**- * Picks random session from the `SessionPool`.- * @return {Session} - Picked `Session`- * @private- */- _pickSession(): Session;- /**- * Potentially loads `SessionPool`.- * If the state was persisted it loads the `SessionPool` from the persisted state.- * @return {Promise<void>}- * @private- */- _maybeLoadSessionPool(): Promise<void>;-}-export function openSessionPool(sessionPoolOptions: SessionPoolOptions): Promise<SessionPool>;-/**- * Factory user-function which creates customized {@link Session} instances.- */-export type CreateSession = (sessionPool: SessionPool) => Session;-export type SessionPoolOptions = {- /**- * - Maximum size of the pool.- * Indicates how many sessions are rotated.- */- maxPoolSize?: number;- /**- * The configuration options for {Session} instances.- */- sessionOptions?: SessionOptions;- /**- * - Name or Id of `KeyValueStore` where is the `SessionPool` state stored.- */- persistStateKeyValueStoreId?: string;- /**- * - Session pool persists it's state under this key in Key value store.- */- persistStateKey?: string;- /**- * - Custom function that should return `Session` instance.- * Function receives `SessionPool` instance as a parameter- */- createSessionFunction?: CreateSession;-};-import { EventEmitter } from "events";-import { Session } from "./session";-import { SessionOptions } from "./session";diff --git a/types/session_pool/session_utils.d.ts b/types/session_pool/session_utils.d.tsdeleted file mode 100644index 2e79425a2..000000000--- a/types/session_pool/session_utils.d.ts+++ /dev/null@@ -1,4 +0,0 @@-/// <reference types="node" />-export function getCookiesFromResponse(response: IncomingMessage | PuppeteerResponse): any[] | undefined;-import { IncomingMessage } from "http";-import { Response as PuppeteerResponse } from "puppeteer";diff --git a/types/stealth/hiding_tricks.d.ts b/types/stealth/hiding_tricks.d.tsdeleted file mode 100644index cad783ad8..000000000--- a/types/stealth/hiding_tricks.d.ts+++ /dev/null@@ -1,23 +0,0 @@-declare namespace _default {- export { addPlugins };- export { emulateWindowFrame };- export { emulateWebGL };- export { emulateConsoleDebug };- export { addLanguage };- export { hideWebDriver };- export { hackPermissions };- export { mockChrome };- export { mockChromeInIframe };- export { mockDeviceMemory };-}-export default _default;-declare function addPlugins(): void;-declare function emulateWindowFrame(): void;-declare function emulateWebGL(): void;-declare function emulateConsoleDebug(): void;-declare function addLanguage(): void;-declare function hideWebDriver(): void;-declare function hackPermissions(): void;-declare function mockChrome(): void;-declare function mockChromeInIframe(): void;-declare function mockDeviceMemory(): void;diff --git a/types/stealth/stealth.d.ts b/types/stealth/stealth.d.tsdeleted file mode 100644index 2d185f69f..000000000--- a/types/stealth/stealth.d.ts+++ /dev/null@@ -1,54 +0,0 @@-/**- * The main purpose of this function is to override newPage function and attach selected tricks.- * @param {Browser} browser - puppeteer browser instance- * @param {StealthOptions} options- * @returns {Promise<Browser>} - Instance of Browser from puppeteer package- */-export default function applyStealthToBrowser(browser: Browser, options: StealthOptions): Promise<Browser>;-/**- * Configuration of stealth tricks for a proper hiding effect all of them should be set to true.- * These tricks are applied only when the `stealth` option is set to `true`.- */-export type StealthOptions = {- /**- * - If plugins should be added to the navigator.- */- addPlugins?: boolean;- /**- * - Emulates window Iframe.- */- emulateWindowFrame?: boolean;- /**- * - Emulates graphic card.- */- emulateWebGL?: boolean;- /**- * - Emulates console.debug to return null.- */- emulateConsoleDebug?: boolean;- /**- * - Adds languages to the navigator.- */- addLanguage?: boolean;- /**- * - Hides the webdriver by changing the navigator proto.- */- hideWebDriver?: boolean;- /**- * - Fakes interaction with permissions.- */- hackPermissions?: boolean;- /**- * - Adds the chrome runtime properties.- */- mockChrome?: boolean;- /**- * - Adds the chrome runtime properties inside the every newly created iframe.- */- mockChromeInIframe?: boolean;- /**- * - Sets device memory to other value than 0.- */- mockDeviceMemory?: boolean;-};-import { Browser } from "puppeteer";diff --git a/types/typedefs.d.ts b/types/typedefs.d.tsdeleted file mode 100644index 3c48b3d81..000000000--- a/types/typedefs.d.ts+++ /dev/null@@ -1,117 +0,0 @@-/**- * Represents information about an actor run, as returned by the- * {@link Apify#call} or {@link Apify#callTask} function.- * The object is almost equivalent to the JSON response- * of the- * [Actor run](https://apify.com/docs/api/v2#/reference/actors/run-collection/run-actor)- * Apify API endpoint and extended with certain fields.- * For more details, see- * [Runs.](https://docs.apify.com/actor/run)- */-export type ActorRun = {- /**- * Actor run ID- */- id: string;- /**- * Actor ID- */- actId: string;- /**- * Time when the actor run started- */- startedAt: Date;- /**- * Time when the actor run finished. Contains `null` for running actors.- */- finishedAt: Date;- /**- * Status of the run. For possible values, see- * [Run lifecycle](https://docs.apify.com/actor/run#lifecycle)- * in Apify actor documentation.- */- status: string;- /**- * Actor run meta-data. For example:- * ```- * {- * "origin": "API",- * "clientIp": "1.2.3.4",- * "userAgent": "ApifyClient/0.2.13 (Linux; Node/v8.11.3)"- * }- * ```- */- meta: any;- /**- * An object containing various actor run statistics. For example:- * ```- * {- * "inputBodyLen": 22,- * "restartCount": 0,- * "workersUsed": 1,- * }- * ```- * Beware that object fields might change in future releases.- */- stats: any;- /**- * Actor run options. For example:- * ```- * {- * "build": "latest",- * "waitSecs": 0,- * "memoryMbytes": 256,- * "diskMbytes": 512- * }- * ```- */- options: any;- /**- * ID of the actor build used for the run. For details, see- * [Builds](https://docs.apify.com/actor/build)- * in Apify actor documentation.- */- buildId: string;- /**- * Number of the actor build used for the run. For example, `0.0.10`.- */- buildNumber: string;- /**- * Exit code of the actor run process. It's `null` if actor is still running.- */- exitCode: number;- /**- * ID of the default key-value store associated with the actor run. See {@link KeyValueStore} for details.- */- defaultKeyValueStoreId: string;- /**- * ID of the default dataset associated with the actor run. See {@link Dataset} for details.- */- defaultDatasetId: string;- /**- * ID of the default request queue associated with the actor run. See {@link RequestQueue} for details.- */- defaultRequestQueueId: string;- /**- * URL on which the web server running inside actor run's Docker container can be accessed.- * For more details, see- * [Container web server](https://docs.apify.com/actor/run#container-web-server)- * in Apify actor documentation.- */- containerUrl: string;- /**- * Contains output of the actor run. The value is `null` or `undefined` in case the actor is still running,- * or if you pass `false` to the `fetchOutput` option of {@link Apify#call}.- *- * For example:- * ```- * {- * "contentType": "application/json; charset=utf-8",- * "body": {- * "message": "Hello world!"- * }- * }- * ```- */- output: any;-};diff --git a/types/utils.d.ts b/types/utils.d.tsdeleted file mode 100644index 896ee376d..000000000--- a/types/utils.d.ts+++ /dev/null@@ -1,113 +0,0 @@-/// <reference types="node" />-export function newClient(): any;-export function logSystemInfo(): void;-/**- * Gets the default instance of the `ApifyClient` class provided- * <a href="https://docs.apify.com/api/apify-client-js/latest"- * target="_blank">apify-client</a> by the NPM package.- * The instance is created automatically by the Apify SDK and it is configured using the- * `APIFY_API_BASE_URL`, `APIFY_USER_ID` and `APIFY_TOKEN` environment variables.- *- * The instance is used for all underlying calls to the Apify API in functions such as- * {@link Apify#getValue} or {@link Apify#call}.- * The settings of the client can be globally altered by calling the- * <a href="https://docs.apify.com/api/apify-client-js/latest#ApifyClient-setOptions"- * target="_blank">`Apify.client.setOptions()`</a> function.- * Beware that altering these settings might have unintended effects on the entire Apify SDK package.- *- * @type {*}- *- * @memberof module:Apify- * @name client- */-export const apifyClient: any;-export function newPromise(): Promise<void>;-export function addCharsetToContentType(contentType: string): string;-export function isDocker(forceReset: boolean): Promise<boolean>;-export function sum(arr: number[]): number;-export function avg(arr: number[]): number;-export function weightedAvg(arrValues: number[], arrWeights: number[]): number;-export function getMemoryInfo(): Promise<MemoryInfo>;-export function isPromise(maybePromise: any): boolean;-export function isProduction(): boolean;-export function ensureDirExists(dirPath: any): any;-export function getFirstKey(dict: any): string | undefined;-export function getTypicalChromeExecutablePath(): string;-export function addTimeoutToPromise(promise: Promise<any>, timeoutMillis: number, errorMessage: string): Promise<any>;-export function isAtHome(): boolean;-export function sleep(millis: number): Promise<void>;-export function openLocalStorage(idOrName: any, defaultIdEnvVar: any, LocalClass: any, cache: any): Promise<any>;-export function openRemoteStorage(idOrName: any, defaultIdEnvVar: any, RemoteClass: any, cache: any, getOrCreateFunction: any): Promise<any>;-export function ensureTokenOrLocalStorageEnvExists(storageName: any): void;-export function snakeCaseToCamelCase(snakeCaseStr: string): string;-export function printOutdatedSdkWarning(): void;-export function parseContentTypeFromResponse(response: IncomingMessage): {- type: string;- charset: string;-};-export namespace publicUtils {- export { isDocker };- export { sleep };- export { downloadListOfUrls };- export { extractUrls };- export { getRandomUserAgent };- export { htmlToText };- export { URL_NO_COMMAS_REGEX };- export { URL_WITH_COMMAS_REGEX };- export { createRequestDebugInfo };- export { parseContentTypeFromResponse };-}-/**- * Describes memory usage of an Actor.- */-export type MemoryInfo = {- /**- * Total memory available in the system or container- */- totalBytes: number;- /**- * Amount of free memory in the system or container- */- freeBytes: number;- /**- * Amount of memory used (= totalBytes - freeBytes)- */- usedBytes: number;- /**- * Amount of memory used the current Node.js process- */- mainProcessBytes: number;- /**- * Amount of memory used by child processes of the current Node.js process- */- childProcessesBytes: number;-};-import { IncomingMessage } from "http";-declare function downloadListOfUrls({ url, encoding, urlRegExp }: {- url: string;- encoding?: string;- urlRegExp?: RegExp;-}): Promise<string[]>;-declare function extractUrls({ string, urlRegExp }: {- string: string;- urlRegExp?: RegExp;-}): string[];-declare function getRandomUserAgent(): string;-declare function htmlToText(html: string | CheerioStatic): string;-/**- * Default regular expression to match URLs in a string that may be plain text, JSON, CSV or other. It supports common URL characters- * and does not support URLs containing commas or spaces. The URLs also may contain Unicode letters (not symbols).- * @memberOf utils- */-declare const URL_NO_COMMAS_REGEX: RegExp;-/**- * Regular expression that, in addition to the default regular expression `URL_NO_COMMAS_REGEX`, supports matching commas in URL path and query.- * Note, however, that this may prevent parsing URLs from comma delimited lists, or the URLs may become malformed.- * @memberOf utils- */-declare const URL_WITH_COMMAS_REGEX: RegExp;-declare function createRequestDebugInfo(request: Request | RequestOptions, response?: IncomingMessage | PuppeteerResponse | undefined, additionalFields?: Object | undefined): any;-import Request from "./request";-import { RequestOptions } from "./request";-import { Response as PuppeteerResponse } from "puppeteer";-export {};diff --git a/types/utils_log.d.ts b/types/utils_log.d.tsdeleted file mode 100644index e85489005..000000000--- a/types/utils_log.d.ts+++ /dev/null@@ -1,35 +0,0 @@-/// <reference path="../types-apify/apify-shared/log.d.ts" />-export default Log;-export type LoggerOptions = {- /**- * Sets the log level to the given value, preventing messages from less important log levels- * from being printed to the console. Use in conjunction with the `log.LEVELS` constants.- */- level?: number;- /**- * Max depth of data object that will be logged. Anything deeper than the limit will be stripped off.- */- maxDepth?: number;- /**- * Max length of the string to be logged. Longer strings will be truncated.- */- maxStringLength?: number;- /**- * Prefix to be prepended the each logged line.- */- prefix?: string;- /**- * Suffix that will be appended the each logged line.- */- suffix?: string;- /**- * Logger implementation to be used. Default one is log.LoggerText to log messages as easily readable- * strings. Optionally you can use `log.LoggerJson` that formats each log line as a JSON.- */- logger?: Object;- /**- * Additional data to be added to each log line.- */- data?: Object;-};-import * as Log from "apify-shared/log";diff --git a/types/utils_request.d.ts b/types/utils_request.d.tsdeleted file mode 100644index d6a61ba79..000000000--- a/types/utils_request.d.ts+++ /dev/null@@ -1,48 +0,0 @@-/// <reference types="node" />-export const FIREFOX_MOBILE_USER_AGENT: "Mozilla/5.0 (Android; Mobile; rv:14.0) Gecko/14.0 Firefox/14.0";-export const FIREFOX_DESKTOP_USER_AGENT: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:68.0) Gecko/20100101 Firefox/68.0";-export function requestAsBrowser(options: RequestAsBrowserOptions): Promise<Readable | IncomingMessage>;-/**- * [@apify/http-request](https://www.npmjs.com/package/@apify/http-request) NPM package.- */-export type RequestAsBrowserOptions = {- /**- * URL of the target endpoint. Supports both HTTP and HTTPS schemes.- */- url: string;- /**- * HTTP method.- */- method?: string;- /**- * Additional HTTP headers to add. It's only recommended to use this option,- * with headers that are typically added by websites, such as cookies. Overriding- * default browser headers will remove the masking this function provides.- */- headers?: Object;- /**- * An HTTP proxy to be passed down to the HTTP request. Supports proxy authentication with Basic Auth.- */- proxyUrl?: string;- /**- * Two-letter ISO 639 language code.- */- languageCode?: string;- /**- * Two-letter ISO 3166 country code.- */- countryCode?: string;- /**- * If `true`, the function uses User-Agent of a mobile browser.- */- useMobileVersion?: boolean;- /**- * Function accepts `response` object as a single parameter and should return true or false.- * If function returns true request gets aborted. This function is passed to the- * [- */- abortFunction?: AbortFunction;-};-export type AbortFunction = (response: IncomingMessage) => boolean;-import { Readable } from "stream";-import { IncomingMessage } from "http";diff --git a/types/utils_social.d.ts b/types/utils_social.d.tsdeleted file mode 100644index 5ec254edb..000000000--- a/types/utils_social.d.ts+++ /dev/null@@ -1,87 +0,0 @@-export namespace socialUtils {- export { emailsFromText };- export { emailsFromUrls };- export { phonesFromText };- export { phonesFromUrls };- export { parseHandlesFromHtml };- export { EMAIL_REGEX };- export { EMAIL_REGEX_GLOBAL };- export { LINKEDIN_REGEX };- export { LINKEDIN_REGEX_GLOBAL };- export { INSTAGRAM_REGEX };- export { INSTAGRAM_REGEX_GLOBAL };- export { TWITTER_REGEX };- export { TWITTER_REGEX_GLOBAL };- export { FACEBOOK_REGEX };- export { FACEBOOK_REGEX_GLOBAL };- export { YOUTUBE_REGEX };- export { YOUTUBE_REGEX_GLOBAL };-}-/**- * Representation of social handles parsed from a HTML page.- *- * The object has the following structure:- *- * ```- * {- * emails: String[],- * phones: String[],- * phonesUncertain: String[],- * linkedIns: String[],- * twitters: String[],- * instagrams: String[],- * facebooks: String[],- * youtubes: String[],- * }- * ```- */-export type SocialHandles = {- emails: string[];- phones: string[];- phonesUncertain: string[];- linkedIns: string[];- twitters: string[];- instagrams: string[];- facebooks: string[];- youtubes: string[];-};-declare function emailsFromText(text: string): string[];-declare function emailsFromUrls(urls: string[]): string[];-declare function phonesFromText(text: string): string[];-declare function phonesFromUrls(urls: string[]): string[];-declare function parseHandlesFromHtml(html: string, data?: Object): SocialHandles;-/**- * Regular expression to exactly match a single email address.- * It has the following form: `/^...$/i`.- * @type {RegExp}- * @memberOf social- */-declare const EMAIL_REGEX: RegExp;-/**- * Regular expression to find multiple email addresses in a text.- * It has the following form: `/.../ig`.- * @type {RegExp}- * @memberOf social- */-declare const EMAIL_REGEX_GLOBAL: RegExp;-/** @type RegExp */-declare let LINKEDIN_REGEX: RegExp;-/** @type RegExp */-declare let LINKEDIN_REGEX_GLOBAL: RegExp;-/** @type RegExp */-declare let INSTAGRAM_REGEX: RegExp;-/** @type RegExp */-declare let INSTAGRAM_REGEX_GLOBAL: RegExp;-/** @type RegExp */-declare let TWITTER_REGEX: RegExp;-/** @type RegExp */-declare let TWITTER_REGEX_GLOBAL: RegExp;-/** @type RegExp */-declare let FACEBOOK_REGEX: RegExp;-/** @type RegExp */-declare let FACEBOOK_REGEX_GLOBAL: RegExp;-/** @type RegExp */-declare let YOUTUBE_REGEX: RegExp;-/** @type RegExp */-declare let YOUTUBE_REGEX_GLOBAL: RegExp;-export {};