@crawlee/playwright 4.0.0-beta.3 → 4.0.0-beta.300

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/README.md +18 -14
  2. package/index.d.ts +4 -3
  3. package/index.js +2 -2
  4. package/internals/adaptive-playwright-crawler.d.ts +149 -94
  5. package/internals/adaptive-playwright-crawler.js +561 -274
  6. package/internals/enqueue-links/click-elements.d.ts +37 -55
  7. package/internals/enqueue-links/click-elements.js +65 -55
  8. package/internals/playwright-browser-pool.d.ts +55 -0
  9. package/internals/playwright-browser-pool.js +34 -0
  10. package/internals/playwright-crawler.d.ts +184 -172
  11. package/internals/playwright-crawler.js +125 -60
  12. package/internals/playwright-launcher.d.ts +30 -20
  13. package/internals/playwright-launcher.js +24 -18
  14. package/internals/utils/playwright-utils.d.ts +74 -48
  15. package/internals/utils/playwright-utils.js +159 -158
  16. package/internals/utils/rendering-type-prediction.d.ts +41 -16
  17. package/internals/utils/rendering-type-prediction.js +101 -37
  18. package/package.json +19 -18
  19. package/index.d.ts.map +0 -1
  20. package/index.js.map +0 -1
  21. package/internals/adaptive-playwright-crawler.d.ts.map +0 -1
  22. package/internals/adaptive-playwright-crawler.js.map +0 -1
  23. package/internals/enqueue-links/click-elements.d.ts.map +0 -1
  24. package/internals/enqueue-links/click-elements.js.map +0 -1
  25. package/internals/playwright-crawler.d.ts.map +0 -1
  26. package/internals/playwright-crawler.js.map +0 -1
  27. package/internals/playwright-launcher.d.ts.map +0 -1
  28. package/internals/playwright-launcher.js.map +0 -1
  29. package/internals/utils/playwright-utils.d.ts.map +0 -1
  30. package/internals/utils/playwright-utils.js.map +0 -1
  31. package/internals/utils/rendering-type-prediction.d.ts.map +0 -1
  32. package/internals/utils/rendering-type-prediction.js.map +0 -1
  33. package/tsconfig.build.tsbuildinfo +0 -1
package/README.md CHANGED
@@ -1,19 +1,23 @@
1
1
  <h1 align="center">
2
2
  <a href="https://crawlee.dev">
3
3
  <picture>
4
- <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/apify/crawlee/master/website/static/img/crawlee-dark.svg?sanitize=true">
5
- <img alt="Crawlee" src="https://raw.githubusercontent.com/apify/crawlee/master/website/static/img/crawlee-light.svg?sanitize=true" width="500">
4
+ <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/apify/crawlee/master/website/static/img/crawlee-dark.svg?sanitize=true" />
5
+ <img alt="Crawlee" src="https://raw.githubusercontent.com/apify/crawlee/master/website/static/img/crawlee-light.svg?sanitize=true" width="500" />
6
6
  </picture>
7
7
  </a>
8
- <br>
8
+ <br />
9
9
  <small>A web scraping and browser automation library</small>
10
10
  </h1>
11
11
 
12
- <p align=center>
13
- <a href="https://www.npmjs.com/package/@crawlee/core" rel="nofollow"><img src="https://img.shields.io/npm/v/@crawlee/core.svg" alt="NPM latest version" data-canonical-src="https://img.shields.io/npm/v/@crawlee/core/next.svg" style="max-width: 100%;"></a>
14
- <a href="https://www.npmjs.com/package/@crawlee/core" rel="nofollow"><img src="https://img.shields.io/npm/dm/@crawlee/core.svg" alt="Downloads" data-canonical-src="https://img.shields.io/npm/dm/@crawlee/core.svg" style="max-width: 100%;"></a>
15
- <a href="https://discord.gg/jyEM2PRvMU" rel="nofollow"><img src="https://img.shields.io/discord/801163717915574323?label=discord" alt="Chat on discord" data-canonical-src="https://img.shields.io/discord/801163717915574323?label=discord" style="max-width: 100%;"></a>
16
- <a href="https://github.com/apify/crawlee/actions/workflows/test-ci.yml"><img src="https://github.com/apify/crawlee/actions/workflows/test-ci.yml/badge.svg?branch=master" alt="Build Status" style="max-width: 100%;"></a>
12
+ <p align="center">
13
+ <a href="https://trendshift.io/repositories/5179" target="_blank"><img src="https://trendshift.io/api/badge/repositories/5179" alt="apify%2Fcrawlee | Trendshift" width="250" height="55"/></a>
14
+ </p>
15
+
16
+ <p align="center">
17
+ <a href="https://www.npmjs.com/package/@crawlee/core" rel="nofollow"><img src="https://img.shields.io/npm/v/@crawlee/core.svg" alt="NPM latest version" data-canonical-src="https://img.shields.io/npm/v/@crawlee/core/next.svg" /></a>
18
+ <a href="https://www.npmjs.com/package/@crawlee/core" rel="nofollow"><img src="https://img.shields.io/npm/dm/@crawlee/core.svg" alt="Downloads" data-canonical-src="https://img.shields.io/npm/dm/@crawlee/core.svg" /></a>
19
+ <a href="https://discord.gg/jyEM2PRvMU" rel="nofollow"><img src="https://img.shields.io/discord/801163717915574323?label=discord" alt="Chat on discord" data-canonical-src="https://img.shields.io/discord/801163717915574323?label=discord" /></a>
20
+ <a href="https://github.com/apify/crawlee/actions/workflows/test-ci.yml"><img src="https://github.com/apify/crawlee/actions/workflows/test-ci.yml/badge.svg?branch=master" alt="Build Status" /></a>
17
21
  </p>
18
22
 
19
23
  Crawlee covers your crawling and scraping end-to-end and **helps you build reliable scrapers. Fast.**
@@ -24,13 +28,13 @@ Crawlee is available as the [`crawlee`](https://www.npmjs.com/package/crawlee) N
24
28
 
25
29
  > 👉 **View full documentation, guides and examples on the [Crawlee project website](https://crawlee.dev)** 👈
26
30
 
27
- > Crawlee for Python is open for early adopters. 🐍 [👉 Checkout the source code 👈](https://github.com/apify/crawlee-python).
31
+ > Do you prefer 🐍 Python instead of JavaScript? [👉 Checkout Crawlee for Python 👈](https://github.com/apify/crawlee-python).
28
32
 
29
33
  ## Installation
30
34
 
31
35
  We recommend visiting the [Introduction tutorial](https://crawlee.dev/js/docs/introduction) in Crawlee documentation for more information.
32
36
 
33
- > Crawlee requires **Node.js 16 or higher**.
37
+ > Crawlee requires **Node.js 22.13 or higher**.
34
38
 
35
39
  ### With Crawlee CLI
36
40
 
@@ -85,7 +89,7 @@ By default, Crawlee stores data to `./storage` in the current working directory.
85
89
  We provide automated beta builds for every merged code change in Crawlee. You can find them in the npm [list of releases](https://www.npmjs.com/package/crawlee?activeTab=versions). If you want to test new features or bug fixes before we release them, feel free to install a beta build like this:
86
90
 
87
91
  ```bash
88
- npm install crawlee@3.12.3-beta.13
92
+ npm install crawlee@next
89
93
  ```
90
94
 
91
95
  If you also use the [Apify SDK](https://github.com/apify/apify-sdk-js), you need to specify dependency overrides in your `package.json` file so that you don't end up with multiple versions of Crawlee installed:
@@ -94,9 +98,9 @@ If you also use the [Apify SDK](https://github.com/apify/apify-sdk-js), you need
94
98
  {
95
99
  "overrides": {
96
100
  "apify": {
97
- "@crawlee/core": "3.12.3-beta.13",
98
- "@crawlee/types": "3.12.3-beta.13",
99
- "@crawlee/utils": "3.12.3-beta.13"
101
+ "@crawlee/core": "$crawlee",
102
+ "@crawlee/types": "$crawlee",
103
+ "@crawlee/utils": "$crawlee"
100
104
  }
101
105
  }
102
106
  }
package/index.d.ts CHANGED
@@ -1,10 +1,11 @@
1
1
  export * from '@crawlee/browser';
2
+ export * from './internals/playwright-browser-pool.js';
2
3
  export * from './internals/playwright-crawler.js';
3
- export * from './internals/playwright-launcher.js';
4
+ export { launchPlaywright } from './internals/playwright-launcher.js';
5
+ export type { PlaywrightLaunchContext } from './internals/playwright-launcher.js';
4
6
  export * from './internals/adaptive-playwright-crawler.js';
5
7
  export { RenderingTypePredictor } from './internals/utils/rendering-type-prediction.js';
6
8
  export * as playwrightUtils from './internals/utils/playwright-utils.js';
7
9
  export * as playwrightClickElements from './internals/enqueue-links/click-elements.js';
8
10
  export type { DirectNavigationOptions as PlaywrightDirectNavigationOptions } from './internals/utils/playwright-utils.js';
9
- export type { RenderingType } from './internals/utils/rendering-type-prediction.js';
10
- //# sourceMappingURL=index.d.ts.map
11
+ export type { IRenderingTypePredictor, RenderingType } from './internals/utils/rendering-type-prediction.js';
package/index.js CHANGED
@@ -1,8 +1,8 @@
1
1
  export * from '@crawlee/browser';
2
+ export * from './internals/playwright-browser-pool.js';
2
3
  export * from './internals/playwright-crawler.js';
3
- export * from './internals/playwright-launcher.js';
4
+ export { launchPlaywright } from './internals/playwright-launcher.js';
4
5
  export * from './internals/adaptive-playwright-crawler.js';
5
6
  export { RenderingTypePredictor } from './internals/utils/rendering-type-prediction.js';
6
7
  export * as playwrightUtils from './internals/utils/playwright-utils.js';
7
8
  export * as playwrightClickElements from './internals/enqueue-links/click-elements.js';
8
- //# sourceMappingURL=index.js.map
@@ -1,52 +1,60 @@
1
- import type { BrowserHook, LoadedContext, RouterHandler } from '@crawlee/browser';
2
- import type { BaseHttpResponseData, GetUserDataFromRequest, RestrictedCrawlingContext, RouterRoutes, StatisticsOptions, StatisticState } from '@crawlee/core';
3
- import { Configuration, RequestHandlerResult, Statistics } from '@crawlee/core';
4
- import type { Awaitable, Dictionary } from '@crawlee/types';
5
- import { type CheerioRoot } from '@crawlee/utils';
6
- import { type Cheerio } from 'cheerio';
1
+ import type { BrowserHook, LoadedRequest, RouterHandler, RouteSchemas, RoutesFromSchemas } from '@crawlee/browser';
2
+ import type { BasicCrawlerOptions, CrawlingContext, EnqueueLinksOptions, GetUserDataFromRequest, RouterRoutes } from '@crawlee/basic';
3
+ import { BasicCrawler } from '@crawlee/basic';
4
+ import { CrawlingRequest } from '@crawlee/browser';
5
+ import type { StorageTransactionView } from '@crawlee/core';
6
+ import type { Dictionary, Awaitable } from '@crawlee/types';
7
+ import { type Cheerio, type CheerioAPI } from 'cheerio';
8
+ import type { AnyNode } from 'domhandler';
7
9
  // @ts-ignore optional peer dependency or compatibility with es2022
8
10
  import type { Page } from 'playwright';
9
- import type { Log } from '@apify/log';
11
+ import { z } from 'zod';
10
12
  import type { PlaywrightCrawlerOptions, PlaywrightCrawlingContext, PlaywrightGotoOptions } from './playwright-crawler.js';
11
- import { PlaywrightCrawler } from './playwright-crawler.js';
12
- import { RenderingTypePredictor } from './utils/rendering-type-prediction.js';
13
- type Result<TResult> = {
14
- result: TResult;
15
- ok: true;
16
- logs?: LogProxyCall[];
17
- } | {
18
- error: unknown;
19
- ok: false;
20
- logs?: LogProxyCall[];
13
+ import { type IRenderingTypePredictor } from './utils/rendering-type-prediction.js';
14
+ declare const adaptiveStatisticStateSchema: z.ZodObject<{
15
+ httpOnlyRequestHandlerRuns: z.ZodDefault<z.ZodNumber>;
16
+ browserRequestHandlerRuns: z.ZodDefault<z.ZodNumber>;
17
+ renderingTypeMispredictions: z.ZodDefault<z.ZodNumber>;
18
+ }, z.core.$strip>;
19
+ /**
20
+ * The extra statistics fields {@link AdaptivePlaywrightCrawler} tracks on top of the built-in
21
+ * {@link StatisticState} ones. They are available on `crawler.statistics.state` and are persisted with the rest of
22
+ * the statistics.
23
+ */
24
+ export type AdaptivePlaywrightCrawlerStatisticState = z.infer<typeof adaptiveStatisticStateSchema>;
25
+ /**
26
+ * The {@link AdaptivePlaywrightCrawlerStatisticState} fields as a {@link Statistics} state extension, defaults
27
+ * and all. A {@link Statistics} instance to be injected into an {@link AdaptivePlaywrightCrawler} has to carry
28
+ * them - `deserialize.extend()` your own fields onto this one and pass the result as `stateExtension`.
29
+ */
30
+ export declare const adaptivePlaywrightCrawlerStatisticState: {
31
+ deserialize: z.ZodObject<{
32
+ httpOnlyRequestHandlerRuns: z.ZodDefault<z.ZodNumber>;
33
+ browserRequestHandlerRuns: z.ZodDefault<z.ZodNumber>;
34
+ renderingTypeMispredictions: z.ZodDefault<z.ZodNumber>;
35
+ }, z.core.$strip>;
21
36
  };
22
- interface AdaptivePlaywrightCrawlerStatisticState extends StatisticState {
23
- httpOnlyRequestHandlerRuns?: number;
24
- browserRequestHandlerRuns?: number;
25
- renderingTypeMispredictions?: number;
26
- }
27
- declare class AdaptivePlaywrightCrawlerStatistics extends Statistics {
28
- state: AdaptivePlaywrightCrawlerStatisticState;
29
- constructor(options?: StatisticsOptions);
30
- reset(): void;
31
- protected _maybeLoadStatistics(): Promise<void>;
32
- trackHttpOnlyRequestHandlerRun(): void;
33
- trackBrowserRequestHandlerRun(): void;
34
- trackRenderingTypeMisprediction(): void;
35
- }
36
- export interface AdaptivePlaywrightCrawlerContext<UserData extends Dictionary = Dictionary> extends RestrictedCrawlingContext<UserData> {
37
+ export interface AdaptivePlaywrightCrawlerContext<UserData extends Dictionary = any> extends CrawlingContext<UserData> {
38
+ request: LoadedRequest<CrawlingRequest<UserData>>;
37
39
  /**
38
40
  * The HTTP response, either from the HTTP client or from the initial request from playwright's navigation.
39
41
  */
40
- response: BaseHttpResponseData;
42
+ response: Response;
41
43
  /**
42
44
  * Playwright Page object. If accessed in HTTP-only rendering, this will throw an error and make the AdaptivePlaywrightCrawlerContext retry the request in a browser.
43
45
  */
44
46
  page: Page;
45
47
  /**
46
- * Wait for an element matching the selector to appear and return a Cheerio object of matched elements.
48
+ * Wait for an element matching the selector to appear and return a Cheerio object of all matched elements.
49
+ * Throws when nothing matches - in the HTTP-only run, that makes the crawler retry the request in a browser.
47
50
  * Timeout defaults to 5s.
48
51
  */
49
- querySelector<T = any>(selector: string, timeoutMs?: number): Promise<Cheerio<T>>;
52
+ querySelectorAll(selector: string, timeoutMs?: number): Promise<Cheerio<AnyNode>>;
53
+ /**
54
+ * Like {@link AdaptivePlaywrightCrawlerContext.querySelectorAll|`querySelectorAll`}, but returns only the
55
+ * first match.
56
+ */
57
+ querySelectorOne(selector: string, timeoutMs?: number): Promise<Cheerio<AnyNode>>;
50
58
  /**
51
59
  * Wait for an element matching the selector to appear.
52
60
  * Timeout defaults to 5s.
@@ -73,67 +81,90 @@ export interface AdaptivePlaywrightCrawlerContext<UserData extends Dictionary =
73
81
  * });
74
82
  * ```
75
83
  */
76
- parseWithCheerio(selector?: string, timeoutMs?: number): Promise<CheerioRoot>;
84
+ parseWithCheerio(selector?: string, timeoutMs?: number): Promise<CheerioAPI>;
85
+ enqueueLinks(options?: EnqueueLinksOptions): Promise<unknown>;
77
86
  }
78
- interface AdaptiveHook extends BrowserHook<Pick<AdaptivePlaywrightCrawlerContext, 'id' | 'request' | 'session' | 'proxyInfo' | 'log'> & {
87
+ interface AdaptiveHookContext extends Pick<AdaptivePlaywrightCrawlerContext, 'id' | 'session' | 'proxyInfo' | 'log' | 'extendTimeout'> {
79
88
  page?: Page;
80
- }, PlaywrightGotoOptions> {
89
+ request: CrawlingRequest;
90
+ gotoOptions?: PlaywrightGotoOptions;
81
91
  }
82
- export interface AdaptivePlaywrightCrawlerOptions extends Omit<PlaywrightCrawlerOptions, 'requestHandler' | 'preNavigationHooks' | 'postNavigationHooks'> {
92
+ type AdaptiveHook<ContextExtension = Dictionary<never>> = BrowserHook<AdaptiveHookContext, ContextExtension>;
93
+ type AdaptivePostNavigationHook<ContextExtension = Dictionary<never>> = BrowserHook<Omit<AdaptiveHookContext, 'request'> & {
94
+ request: LoadedRequest<CrawlingRequest>;
95
+ }, ContextExtension>;
96
+ /** Passed to {@link AdaptivePlaywrightCrawlerOptions.resultChecker} and `resultComparator` alongside the results. */
97
+ export interface AdaptiveResultContext {
98
+ /** The request whose handler produced the results. */
99
+ request: CrawlingRequest;
100
+ }
101
+ export interface AdaptivePlaywrightCrawlerOptions<ContextExtension = Dictionary<never>, ExtendedContext extends AdaptivePlaywrightCrawlerContext = AdaptivePlaywrightCrawlerContext & ContextExtension, Routes extends Record<keyof Routes, Dictionary> = Record<string, GetUserDataFromRequest<AdaptivePlaywrightCrawlerContext['request']>>, StatisticStateExtension extends AdaptivePlaywrightCrawlerStatisticState = AdaptivePlaywrightCrawlerStatisticState> extends Omit<BasicCrawlerOptions<AdaptivePlaywrightCrawlerContext, ContextExtension, ExtendedContext, Routes, StatisticStateExtension>, 'preNavigationHooks' | 'postNavigationHooks' | 'contextPipelineBuilder'>, Pick<PlaywrightCrawlerOptions, 'launchContext' | 'headless' | 'browserPool' | 'remoteBrowser'> {
83
102
  /**
84
- * Function that is called to process each request.
85
- *
86
- * The function receives the {@link AdaptivePlaywrightCrawlingContext} as an argument, and it must refrain from calling code with side effects,
87
- * other than the methods of the crawling context. Any other side effects may be invoked repeatedly by the crawler, which can lead to inconsistent results.
88
- *
89
- * The function must return a promise, which is then awaited by the crawler.
90
- *
91
- * If the function throws an exception, the crawler will try to re-crawl the
92
- * request later, up to `option.maxRequestRetries` times.
103
+ * Timeout for the navigation phase of each attempt, in seconds, shared by the `preNavigationHooks`, the
104
+ * navigation and the `postNavigationHooks`. Applies to both the HTTP-only and the browser attempt. When not
105
+ * set, each attempt keeps its own default: 30 seconds for HTTP-only and 60 seconds for the browser.
93
106
  */
94
- requestHandler?: (crawlingContext: LoadedContext<AdaptivePlaywrightCrawlerContext>) => Awaitable<void>;
107
+ navigationTimeoutSecs?: number;
95
108
  /**
96
109
  * Async functions that are sequentially evaluated before the navigation. Good for setting additional cookies.
97
110
  * The function accepts a subset of the crawling context. If you attempt to access the `page` property during HTTP-only crawling,
98
111
  * an exception will be thrown. If it's not caught, the request will be transparently retried in a browser.
112
+ *
113
+ * A hook may optionally return a partial object whose properties are merged into the crawling context,
114
+ * allowing the hook to override context members for subsequent hooks and pipeline stages.
99
115
  */
100
- preNavigationHooks?: AdaptiveHook[];
116
+ preNavigationHooks?: AdaptiveHook<ContextExtension>[];
101
117
  /**
102
118
  * Async functions that are sequentially evaluated after the navigation. Good for checking if the navigation was successful.
103
119
  * The function accepts a subset of the crawling context. If you attempt to access the `page` property during HTTP-only crawling,
104
120
  * an exception will be thrown. If it's not caught, the request will be transparently retried in a browser.
121
+ *
122
+ * A hook may optionally return a partial object whose properties are merged into the crawling context
123
+ * (e.g. to override `response` after solving a challenge).
105
124
  */
106
- postNavigationHooks?: AdaptiveHook[];
125
+ postNavigationHooks?: AdaptivePostNavigationHook<ContextExtension>[];
107
126
  /**
108
127
  * Specifies the frequency of rendering type detection checks - 0.1 means roughly 10% of requests.
109
128
  * Defaults to 0.1 (so 10%).
110
129
  */
111
130
  renderingTypeDetectionRatio?: number;
112
131
  /**
113
- * An optional callback that is called on dataset items found by the request handler in plain HTTP mode.
132
+ * An optional callback that is called on the storage writes recorded by the request handler in plain
133
+ * HTTP mode (exposed as a read-only {@link StorageTransactionView}).
114
134
  * If it returns false, the request is retried in a browser.
115
- * If no callback is specified, every dataset item is considered valid.
135
+ * If no callback is specified, every result is considered valid.
116
136
  */
117
- resultChecker?: (result: RequestHandlerResult) => boolean;
137
+ resultChecker?: (result: StorageTransactionView, context: AdaptiveResultContext) => boolean;
138
+ /**
139
+ * An optional callback that decides whether an error thrown during the plain HTTP request handler
140
+ * should be propagated (instead of falling back to browser navigation).
141
+ *
142
+ * If the callback returns `true`, the error is thrown, triggering the standard retry mechanism.
143
+ * If the callback returns `false` (or is not provided), the error is logged and the crawler
144
+ * falls back to browser navigation (default behavior).
145
+ *
146
+ * @default () => false
147
+ */
148
+ shouldPropagateError?: (error: Error, context: PlaywrightCrawlingContext) => Awaitable<boolean>;
118
149
  /**
119
150
  * An optional callback used in rendering type detection. On each detection, the result of the plain HTTP run is compared to that of the browser one.
120
- * If the callback returns true, the results are considered equal and the target site is considered static.
151
+ * If a callback is provided, the contract is as follows:
152
+ * It the callback returns true or 'equal', the results are considered equal and the target site is considered static.
153
+ * If it returns false or 'different', the target site is considered client-rendered.
154
+ * If it returns 'inconclusive', the detection result won't be used.
121
155
  * If no result comparator is specified, but there is a `resultChecker`, any site where the `resultChecker` returns true is considered static.
122
156
  * If neither `resultComparator` nor `resultChecker` are specified, a deep comparison of returned dataset items is used as a default.
157
+ *
158
+ * For a stricter, ready-made comparator that also takes enqueued requests and key-value store changes into account, see {@link fullResultComparator}.
123
159
  */
124
- resultComparator?: (resultA: RequestHandlerResult, resultB: RequestHandlerResult) => boolean;
125
- /**
126
- * A custom rendering type predictor
127
- */
128
- renderingTypePredictor?: Pick<RenderingTypePredictor, 'predict' | 'storeResult'>;
160
+ resultComparator?: (resultA: StorageTransactionView, resultB: StorageTransactionView, context: AdaptiveResultContext) => boolean | 'equal' | 'different' | 'inconclusive';
129
161
  /**
130
- * Prevent direct access to storage in request handlers (only allow using context helpers).
131
- * Defaults to `true`
162
+ * A custom rendering type predictor. A predictor passed here is borrowed - the crawler never drives its
163
+ * lifecycle, so set it up yourself (the built-in {@link RenderingTypePredictor} needs `initialize()`).
164
+ * Omit the option and the crawler builds its own from `renderingTypeDetectionRatio` - and initializes it.
132
165
  */
133
- preventDirectStorageAccess?: boolean;
166
+ renderingTypePredictor?: IRenderingTypePredictor;
134
167
  }
135
- declare const proxyLogMethods: readonly ["error", "exception", "softFail", "info", "debug", "perf", "warningOnce", "deprecated"];
136
- type LogProxyCall = [log: Log, method: (typeof proxyLogMethods)[number], ...args: unknown[]];
137
168
  /**
138
169
  * An extension of {@link PlaywrightCrawler} that uses a more limited request handler interface so that it is able to switch to HTTP-only crawling when it detects it may be possible.
139
170
  *
@@ -142,9 +173,9 @@ type LogProxyCall = [log: Log, method: (typeof proxyLogMethods)[number], ...args
142
173
  * ```javascript
143
174
  * const crawler = new AdaptivePlaywrightCrawler({
144
175
  * renderingTypeDetectionRatio: 0.1,
145
- * async requestHandler({ querySelector, pushData, enqueueLinks, request, log }) {
176
+ * async requestHandler({ querySelectorAll, pushData, enqueueLinks, request, log }) {
146
177
  * // This function is called to extract data from a single web page
147
- * const $prices = await querySelector('span.price')
178
+ * const $prices = await querySelectorAll('span.price')
148
179
  *
149
180
  * await pushData({
150
181
  * url: request.url,
@@ -160,34 +191,58 @@ type LogProxyCall = [log: Log, method: (typeof proxyLogMethods)[number], ...args
160
191
  * 'http://www.example.com/page-2',
161
192
  * ]);
162
193
  * ```
163
- *
164
- * @experimental
165
194
  */
166
- export declare class AdaptivePlaywrightCrawler extends PlaywrightCrawler {
167
- readonly config: Configuration;
168
- private adaptiveRequestHandler;
169
- private renderingTypePredictor;
170
- private resultChecker;
171
- private resultComparator;
172
- private preventDirectStorageAccess;
173
- readonly stats: AdaptivePlaywrightCrawlerStatistics;
174
- /**
175
- * Default {@link Router} instance that will be used if we don't specify any {@link AdaptivePlaywrightCrawlerOptions.requestHandler|`requestHandler`}.
176
- * See {@link Router.addHandler|`router.addHandler()`} and {@link Router.addDefaultHandler|`router.addDefaultHandler()`}.
195
+ export declare class AdaptivePlaywrightCrawler<ContextExtension = Dictionary<never>, ExtendedContext extends AdaptivePlaywrightCrawlerContext = AdaptivePlaywrightCrawlerContext & ContextExtension, Routes extends Record<keyof Routes, Dictionary> = Record<string, GetUserDataFromRequest<AdaptivePlaywrightCrawlerContext['request']>>, StatisticStateExtension extends AdaptivePlaywrightCrawlerStatisticState = AdaptivePlaywrightCrawlerStatisticState> extends BasicCrawler<AdaptivePlaywrightCrawlerContext, ContextExtension, ExtendedContext, Routes, StatisticStateExtension> {
196
+ #private;
197
+ constructor(options?: AdaptivePlaywrightCrawlerOptions<ContextExtension, ExtendedContext, Routes, StatisticStateExtension>);
198
+ protected init(): Promise<void>;
199
+ protected runRequestHandler(crawlingContext: CrawlingContext): Promise<void>;
200
+ /**
201
+ * Number of rendering type detections that have not settled yet, including results the predictor is
202
+ * still persisting.
177
203
  */
178
- // @ts-ignore optional peer dependency or compatibility with es2022
179
- readonly router: RouterHandler<AdaptivePlaywrightCrawlerContext>;
180
- constructor(options?: AdaptivePlaywrightCrawlerOptions, config?: Configuration);
181
- protected _runRequestHandler(crawlingContext: PlaywrightCrawlingContext): Promise<void>;
182
- protected commitResult(crawlingContext: PlaywrightCrawlingContext, { calls, keyValueStoreChanges }: RequestHandlerResult): Promise<void>;
183
- protected allowStorageAccess<R, TArgs extends any[]>(func: (...args: TArgs) => Promise<R>): (...args: TArgs) => Promise<R>;
184
- protected runRequestHandlerInBrowser(crawlingContext: PlaywrightCrawlingContext): Promise<{
185
- result: Result<RequestHandlerResult>;
186
- initialStateCopy?: Record<string, unknown>;
187
- }>;
188
- protected runRequestHandlerWithPlainHTTP(crawlingContext: PlaywrightCrawlingContext, oldStateCopy?: Dictionary): Promise<Result<RequestHandlerResult>>;
189
- private createLogProxy;
204
+ get inFlightRenderingTypeDetectionCount(): number;
205
+ /**
206
+ * Waits for in-flight rendering type detections to settle, bounded by `timeoutMillis` (defaults to the
207
+ * internal timeout).
208
+ */
209
+ drainRenderingDetections({ timeoutMillis }?: {
210
+ timeoutMillis?: number;
211
+ }): Promise<void>;
212
+ /**
213
+ * Stops the crawler immediately, but not before rendering type detections already under way (and results
214
+ * the predictor is still persisting) have settled - see
215
+ * {@link AdaptivePlaywrightCrawler.drainRenderingDetections|`drainRenderingDetections()`}. Requests
216
+ * that are still running are not waited for, unlike {@link BasicCrawler.stop|`stop()`}.
217
+ */
218
+ teardown(): Promise<void>;
219
+ destroy(): Promise<void>;
190
220
  }
191
- export declare function createAdaptivePlaywrightRouter<Context extends AdaptivePlaywrightCrawlerContext = AdaptivePlaywrightCrawlerContext, UserData extends Dictionary = GetUserDataFromRequest<Context['request']>>(routes?: RouterRoutes<Context, UserData>): RouterHandler<Context>;
221
+ export declare function createAdaptivePlaywrightRouter<Context extends AdaptivePlaywrightCrawlerContext = AdaptivePlaywrightCrawlerContext, Routes extends Record<keyof Routes, Dictionary> = Record<string, GetUserDataFromRequest<Context['request']>>>(routes?: RouterRoutes<Context, Routes>): RouterHandler<Context, Routes>;
222
+ export declare function createAdaptivePlaywrightRouter<Context extends AdaptivePlaywrightCrawlerContext = AdaptivePlaywrightCrawlerContext, UserData extends Dictionary = GetUserDataFromRequest<Context['request']>>(routes?: RouterRoutes<Context, Record<string, UserData>>): RouterHandler<Context, Record<string, UserData>>;
223
+ export declare function createAdaptivePlaywrightRouter<Context extends AdaptivePlaywrightCrawlerContext = AdaptivePlaywrightCrawlerContext, const Schemas extends RouteSchemas = RouteSchemas>(schemas: Schemas): RouterHandler<Context, RoutesFromSchemas<Schemas>>;
224
+ /**
225
+ * An opt-in {@link AdaptivePlaywrightCrawlerOptions.resultComparator|`resultComparator`} that considers two
226
+ * request handler results equal only if *all* of their observable effects match - the pushed dataset items, the
227
+ * enqueued requests, and the key-value store changes. This is stricter than the default comparator, which only
228
+ * compares dataset items.
229
+ *
230
+ * **Beware:** enqueued URLs are compared exactly. The same page rendered in a browser and via plain HTTP often
231
+ * yields links that differ only in tracking query parameters, for example:
232
+ * - `https://sdk.apify.com/docs/guides/getting-started`
233
+ * - `https://sdk.apify.com/docs/guides/getting-started?__hsfp=1136113150&__hssc=7591405.1.173549427712`
234
+ *
235
+ * Such links are treated as *different*, which will make the crawler favor browser rendering for those pages.
236
+ *
237
+ * **Example usage:**
238
+ * ```ts
239
+ * const crawler = new AdaptivePlaywrightCrawler({
240
+ * resultComparator: fullResultComparator,
241
+ * async requestHandler({ pushData, enqueueLinks }) {
242
+ * // ...
243
+ * },
244
+ * });
245
+ * ```
246
+ */
247
+ export declare function fullResultComparator(resultA: StorageTransactionView, resultB: StorageTransactionView): boolean;
192
248
  export {};
193
- //# sourceMappingURL=adaptive-playwright-crawler.d.ts.map