@crawlee/playwright 4.0.0-beta.13 → 4.0.0-beta.130

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 +17 -13
  2. package/index.d.ts +2 -2
  3. package/index.js +1 -1
  4. package/internals/adaptive-playwright-crawler.d.ts +128 -59
  5. package/internals/adaptive-playwright-crawler.js +317 -230
  6. package/internals/enqueue-links/click-elements.d.ts +37 -55
  7. package/internals/enqueue-links/click-elements.js +63 -55
  8. package/internals/playwright-browser-pool.d.ts +71 -0
  9. package/internals/playwright-browser-pool.js +61 -0
  10. package/internals/playwright-crawler.d.ts +193 -124
  11. package/internals/playwright-crawler.js +63 -62
  12. package/internals/playwright-launcher.d.ts +28 -18
  13. package/internals/playwright-launcher.js +19 -18
  14. package/internals/utils/playwright-utils.d.ts +61 -24
  15. package/internals/utils/playwright-utils.js +145 -95
  16. package/internals/utils/rendering-type-prediction.d.ts +28 -13
  17. package/internals/utils/rendering-type-prediction.js +87 -29
  18. package/package.json +18 -14
  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
@@ -1,24 +1,26 @@
1
- import type { BrowserCrawlerOptions, BrowserCrawlingContext, BrowserHook, GetUserDataFromRequest, RequestHandler, RouterRoutes } from '@crawlee/browser';
2
- import { BrowserCrawler, Configuration } from '@crawlee/browser';
3
- import type { PlaywrightController, PlaywrightPlugin } from '@crawlee/browser-pool';
1
+ import type { BrowserCrawlerOptions, BrowserCrawlingContext, BrowserHook, GetUserDataFromRequest, RequestHandler, RouterHandler, RouterRoutes, RouteSchemas, RoutesFromSchemas } from '@crawlee/browser';
2
+ import { BrowserCrawler } from '@crawlee/browser';
4
3
  import type { Dictionary } from '@crawlee/types';
5
4
  // @ts-ignore optional peer dependency or compatibility with es2022
6
- import type { LaunchOptions, Page, Response } from 'playwright';
5
+ import type { Download, LaunchOptions, Page, Response } from 'playwright';
6
+ import { z } from 'zod';
7
+ import type { EnqueueLinksByClickingElementsOptions } from './enqueue-links/click-elements.js';
7
8
  import type { PlaywrightLaunchContext } from './playwright-launcher.js';
8
- import type { DirectNavigationOptions, PlaywrightContextUtils } from './utils/playwright-utils.js';
9
- export interface PlaywrightCrawlingContext<UserData extends Dictionary = Dictionary> extends BrowserCrawlingContext<Page, Response, PlaywrightController, UserData>, PlaywrightContextUtils {
9
+ import type { BlockRequestsOptions, DirectNavigationOptions, HandleCloudflareChallengeOptions, InfiniteScrollOptions, InjectFileOptions, PlaywrightContextUtils, SaveSnapshotOptions } from './utils/playwright-utils.js';
10
+ export type PlaywrightGotoOptions = NonNullable<Parameters<Page['goto']>[1]>;
11
+ export interface PlaywrightCrawlingContext<UserData extends Dictionary = any> extends BrowserCrawlingContext<Page, Response, UserData, PlaywrightGotoOptions>, PlaywrightContextUtils {
10
12
  }
11
- // @ts-ignore optional peer dependency or compatibility with es2022
12
- export interface PlaywrightHook extends BrowserHook<PlaywrightCrawlingContext, PlaywrightGotoOptions> {
13
- }
14
- export type PlaywrightGotoOptions = Parameters<Page['goto']>[1];
15
- export interface PlaywrightCrawlerOptions<ContextExtension = {}, ExtendedContext extends PlaywrightCrawlingContext = PlaywrightCrawlingContext & ContextExtension> extends BrowserCrawlerOptions<Page, Response, PlaywrightController, PlaywrightCrawlingContext, ContextExtension, ExtendedContext, {
16
- browserPlugins: [PlaywrightPlugin];
17
- }> {
13
+ export type PlaywrightHook<UserData extends Dictionary = any> = BrowserHook<PlaywrightCrawlingContext<UserData>>;
14
+ export interface PlaywrightCrawlerOptions<ContextExtension = Dictionary<never>, ExtendedContext extends PlaywrightCrawlingContext = PlaywrightCrawlingContext & ContextExtension, Routes extends Record<keyof Routes, Dictionary> = Record<string, GetUserDataFromRequest<PlaywrightCrawlingContext['request']>>, StatisticStateExtension extends object = {}> extends BrowserCrawlerOptions<Page, Response, PlaywrightCrawlingContext, ContextExtension, ExtendedContext, Routes, StatisticStateExtension> {
18
15
  /**
19
16
  * The same options as used by {@link launchPlaywright}.
20
17
  */
21
18
  launchContext?: PlaywrightLaunchContext;
19
+ /**
20
+ * Whether to run browser in headless mode. Defaults to `true`.
21
+ * Can be also set via {@link Configuration}.
22
+ */
23
+ headless?: boolean;
22
24
  /**
23
25
  * Function that is called to process each request.
24
26
  *
@@ -26,8 +28,6 @@ export interface PlaywrightCrawlerOptions<ContextExtension = {}, ExtendedContext
26
28
  * - `request` is an instance of the {@link Request} object with details about the URL to open, HTTP method etc.
27
29
  * - `page` is an instance of the `Playwright`
28
30
  * [`Page`](https://playwright.dev/docs/api/class-page)
29
- * - `browserController` is an instance of the
30
- * [`BrowserController`](https://github.com/apify/browser-pool#browsercontroller),
31
31
  * - `response` is an instance of the `Playwright`
32
32
  * [`Response`](https://playwright.dev/docs/api/class-response),
33
33
  * which is the main resource response as returned by `page.goto(request.url)`.
@@ -43,28 +43,28 @@ export interface PlaywrightCrawlerOptions<ContextExtension = {}, ExtendedContext
43
43
  * The exceptions are logged to the request using the
44
44
  * {@link Request.pushErrorMessage} function.
45
45
  */
46
- requestHandler?: RequestHandler<ExtendedContext>;
46
+ requestHandler?: RouterHandler<ExtendedContext, Routes> | RequestHandler<ExtendedContext>;
47
47
  /**
48
48
  * Async functions that are sequentially evaluated before the navigation. Good for setting additional cookies
49
- * or browser properties before navigation. The function accepts two parameters, `crawlingContext` and `gotoOptions`,
50
- * which are passed to the `page.goto()` function the crawler calls to navigate.
49
+ * or browser properties before navigation. The function receives the `crawlingContext`; the options object
50
+ * forwarded to `page.goto()` is available as `crawlingContext.gotoOptions` and can be mutated in place.
51
+ * A hook may optionally return a partial object whose properties are merged into the crawling context
52
+ * (e.g. to override context members for subsequent hooks and pipeline stages).
51
53
  * Example:
52
54
  * ```
53
55
  * preNavigationHooks: [
54
- * async (crawlingContext, gotoOptions) => {
55
- * const { page } = crawlingContext;
56
+ * async ({ page, gotoOptions }) => {
56
57
  * await page.evaluate((attr) => { window.foo = attr; }, 'bar');
58
+ * gotoOptions.timeout = 60_000;
57
59
  * },
58
60
  * ]
59
61
  * ```
60
- *
61
- * Modyfing `pageOptions` is supported only in Playwright incognito.
62
- * See {@link PrePageCreateHook}
63
62
  */
64
- preNavigationHooks?: PlaywrightHook[];
63
+ preNavigationHooks?: BrowserHook<PlaywrightCrawlingContext<GetUserDataFromRequest<ExtendedContext['request']>>, ContextExtension>[];
65
64
  /**
66
65
  * Async functions that are sequentially evaluated after the navigation. Good for checking if the navigation was successful.
67
- * The function accepts `crawlingContext` as the only parameter.
66
+ * The function accepts `crawlingContext` as the only parameter. A hook may optionally return a partial object
67
+ * whose properties are merged into the crawling context (e.g. to override `response` after solving a challenge).
68
68
  * Example:
69
69
  * ```
70
70
  * postNavigationHooks: [
@@ -77,7 +77,7 @@ export interface PlaywrightCrawlerOptions<ContextExtension = {}, ExtendedContext
77
77
  * ]
78
78
  * ```
79
79
  */
80
- postNavigationHooks?: PlaywrightHook[];
80
+ postNavigationHooks?: BrowserHook<PlaywrightCrawlingContext<GetUserDataFromRequest<ExtendedContext['request']>>, ContextExtension>[];
81
81
  }
82
82
  /**
83
83
  * Provides a simple framework for parallel crawling of web pages
@@ -90,24 +90,26 @@ export interface PlaywrightCrawlerOptions<ContextExtension = {}, ExtendedContext
90
90
  * If the target website doesn't need JavaScript, consider using {@link CheerioCrawler},
91
91
  * which downloads the pages using raw HTTP requests and is about 10x faster.
92
92
  *
93
- * The source URLs are represented using {@link Request} objects that are fed from
94
- * {@link RequestList} or {@link RequestQueue} instances provided by the {@link PlaywrightCrawlerOptions.requestList}
95
- * or {@link PlaywrightCrawlerOptions.requestQueue} constructor options, respectively.
93
+ * The source URLs are represented using {@link Request} objects that are fed from the
94
+ * {@link IRequestManager|request manager} provided via the {@link PlaywrightCrawlerOptions.requestManager|`requestManager`}
95
+ * constructor option (a {@link RequestQueue} is itself a request manager). To read from a read-only source such
96
+ * as a {@link RequestList} while still being able to enqueue new requests, combine it with a queue into a
97
+ * {@link RequestManagerTandem} via {@link IRequestLoader.toTandem|`requestLoader.toTandem()`} and pass the
98
+ * result as `requestManager`.
96
99
  *
97
- * If both {@link PlaywrightCrawlerOptions.requestList} and {@link PlaywrightCrawlerOptions.requestQueue} are used,
98
- * the instance first processes URLs from the {@link RequestList} and automatically enqueues all of them
99
- * to {@link RequestQueue} before it starts their processing. This ensures that a single URL is not crawled multiple times.
100
+ * > The {@link PlaywrightCrawlerOptions.requestList|`requestList`} and {@link PlaywrightCrawlerOptions.requestQueue|`requestQueue`}
101
+ * > options are deprecated; they are still accepted and folded into a single `requestManager` for back-compat.
100
102
  *
101
103
  * The crawler finishes when there are no more {@link Request} objects to crawl.
102
104
  *
103
105
  * `PlaywrightCrawler` opens a new Chrome page (i.e. tab) for each {@link Request} object to crawl
104
106
  * and then calls the function provided by user as the {@link PlaywrightCrawlerOptions.requestHandler} option.
105
107
  *
106
- * New pages are only opened when there is enough free CPU and memory available,
107
- * using the functionality provided by the {@link AutoscaledPool} class.
108
- * All {@link AutoscaledPool} configuration options can be passed to the {@link PlaywrightCrawlerOptions.autoscaledPoolOptions}
109
- * parameter of the `PlaywrightCrawler` constructor. For user convenience, the `minConcurrency` and `maxConcurrency`
110
- * {@link AutoscaledPoolOptions} are available directly in the `PlaywrightCrawler` constructor.
108
+ * New pages are only opened when there is enough free CPU and memory available, as judged by the crawler's
109
+ * {@link ConcurrencySystem}.
110
+ * Concurrency is tuned via the `minConcurrency`, `maxConcurrency` and `maxRequestsPerMinute` options of the
111
+ * `PlaywrightCrawler` constructor, or, for finer control, by injecting a pre-configured
112
+ * {@link ConcurrencySystem|`concurrencySystem`}.
111
113
  *
112
114
  * Note that the pool of Playwright instances is internally managed by the [BrowserPool](https://github.com/apify/browser-pool) class.
113
115
  *
@@ -142,97 +144,164 @@ export interface PlaywrightCrawlerOptions<ContextExtension = {}, ExtendedContext
142
144
  * ```
143
145
  * @category Crawlers
144
146
  */
145
- export declare class PlaywrightCrawler<ContextExtension = {}, ExtendedContext extends PlaywrightCrawlingContext = PlaywrightCrawlingContext & ContextExtension> extends BrowserCrawler<Page, Response, PlaywrightController, {
146
- browserPlugins: [PlaywrightPlugin];
147
- }, LaunchOptions, PlaywrightCrawlingContext, ContextExtension, ExtendedContext> {
148
- readonly config: Configuration;
147
+ export declare class PlaywrightCrawler<ContextExtension = Dictionary<never>, ExtendedContext extends PlaywrightCrawlingContext = PlaywrightCrawlingContext & ContextExtension, Routes extends Record<keyof Routes, Dictionary> = Record<string, GetUserDataFromRequest<PlaywrightCrawlingContext['request']>>, StatisticStateExtension extends object = {}> extends BrowserCrawler<Page, Response, LaunchOptions, PlaywrightCrawlingContext, ContextExtension, ExtendedContext, Routes, StatisticStateExtension> {
149
148
  protected static optionsShape: {
150
- // @ts-ignore optional peer dependency or compatibility with es2022
151
- browserPoolOptions: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
152
- // @ts-ignore optional peer dependency or compatibility with es2022
153
- launcher: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
154
- // @ts-ignore optional peer dependency or compatibility with es2022
155
- ignoreIframes: import("ow").BooleanPredicate & import("ow").BasePredicate<boolean | undefined>;
156
- // @ts-ignore optional peer dependency or compatibility with es2022
157
- ignoreShadowRoots: import("ow").BooleanPredicate & import("ow").BasePredicate<boolean | undefined>;
158
- // @ts-ignore optional peer dependency or compatibility with es2022
159
- navigationTimeoutSecs: import("ow").NumberPredicate & import("ow").BasePredicate<number | undefined>;
160
- // @ts-ignore optional peer dependency or compatibility with es2022
161
- preNavigationHooks: import("ow").ArrayPredicate<unknown> & import("ow").BasePredicate<unknown[] | undefined>;
162
- // @ts-ignore optional peer dependency or compatibility with es2022
163
- postNavigationHooks: import("ow").ArrayPredicate<unknown> & import("ow").BasePredicate<unknown[] | undefined>;
164
- // @ts-ignore optional peer dependency or compatibility with es2022
165
- launchContext: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
166
- // @ts-ignore optional peer dependency or compatibility with es2022
167
- headless: import("ow").AnyPredicate<string | boolean>;
168
- // @ts-ignore optional peer dependency or compatibility with es2022
169
- sessionPoolOptions: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
170
- // @ts-ignore optional peer dependency or compatibility with es2022
171
- persistCookiesPerSession: import("ow").BooleanPredicate & import("ow").BasePredicate<boolean | undefined>;
172
- // @ts-ignore optional peer dependency or compatibility with es2022
173
- useSessionPool: import("ow").BooleanPredicate & import("ow").BasePredicate<boolean | undefined>;
174
- // @ts-ignore optional peer dependency or compatibility with es2022
175
- proxyConfiguration: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
176
- // @ts-ignore optional peer dependency or compatibility with es2022
177
- contextPipelineBuilder: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
178
- // @ts-ignore optional peer dependency or compatibility with es2022
179
- extendContext: import("ow").Predicate<Function> & import("ow").BasePredicate<Function | undefined>;
180
- // @ts-ignore optional peer dependency or compatibility with es2022
181
- requestList: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
182
- // @ts-ignore optional peer dependency or compatibility with es2022
183
- requestQueue: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
184
- // @ts-ignore optional peer dependency or compatibility with es2022
185
- requestHandler: import("ow").Predicate<Function> & import("ow").BasePredicate<Function | undefined>;
186
- // @ts-ignore optional peer dependency or compatibility with es2022
187
- requestHandlerTimeoutSecs: import("ow").NumberPredicate & import("ow").BasePredicate<number | undefined>;
188
- // @ts-ignore optional peer dependency or compatibility with es2022
189
- errorHandler: import("ow").Predicate<Function> & import("ow").BasePredicate<Function | undefined>;
190
- // @ts-ignore optional peer dependency or compatibility with es2022
191
- failedRequestHandler: import("ow").Predicate<Function> & import("ow").BasePredicate<Function | undefined>;
192
- // @ts-ignore optional peer dependency or compatibility with es2022
193
- maxRequestRetries: import("ow").NumberPredicate & import("ow").BasePredicate<number | undefined>;
194
- // @ts-ignore optional peer dependency or compatibility with es2022
195
- sameDomainDelaySecs: import("ow").NumberPredicate & import("ow").BasePredicate<number | undefined>;
196
- // @ts-ignore optional peer dependency or compatibility with es2022
197
- maxSessionRotations: import("ow").NumberPredicate & import("ow").BasePredicate<number | undefined>;
198
- // @ts-ignore optional peer dependency or compatibility with es2022
199
- maxRequestsPerCrawl: import("ow").NumberPredicate & import("ow").BasePredicate<number | undefined>;
200
- // @ts-ignore optional peer dependency or compatibility with es2022
201
- autoscaledPoolOptions: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
202
- // @ts-ignore optional peer dependency or compatibility with es2022
203
- statusMessageLoggingInterval: import("ow").NumberPredicate & import("ow").BasePredicate<number | undefined>;
204
- // @ts-ignore optional peer dependency or compatibility with es2022
205
- statusMessageCallback: import("ow").Predicate<Function> & import("ow").BasePredicate<Function | undefined>;
206
- // @ts-ignore optional peer dependency or compatibility with es2022
207
- retryOnBlocked: import("ow").BooleanPredicate & import("ow").BasePredicate<boolean | undefined>;
208
- // @ts-ignore optional peer dependency or compatibility with es2022
209
- respectRobotsTxtFile: import("ow").BooleanPredicate & import("ow").BasePredicate<boolean | undefined>;
210
- // @ts-ignore optional peer dependency or compatibility with es2022
211
- onSkippedRequest: import("ow").Predicate<Function> & import("ow").BasePredicate<Function | undefined>;
212
- // @ts-ignore optional peer dependency or compatibility with es2022
213
- httpClient: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
214
- // @ts-ignore optional peer dependency or compatibility with es2022
215
- minConcurrency: import("ow").NumberPredicate & import("ow").BasePredicate<number | undefined>;
216
- // @ts-ignore optional peer dependency or compatibility with es2022
217
- maxConcurrency: import("ow").NumberPredicate & import("ow").BasePredicate<number | undefined>;
218
- // @ts-ignore optional peer dependency or compatibility with es2022
219
- maxRequestsPerMinute: import("ow").NumberPredicate & import("ow").BasePredicate<number | undefined>;
220
- // @ts-ignore optional peer dependency or compatibility with es2022
221
- keepAlive: import("ow").BooleanPredicate & import("ow").BasePredicate<boolean | undefined>;
222
- // @ts-ignore optional peer dependency or compatibility with es2022
223
- log: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
224
- // @ts-ignore optional peer dependency or compatibility with es2022
225
- experiments: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
226
- // @ts-ignore optional peer dependency or compatibility with es2022
227
- statisticsOptions: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
149
+ headless: z.ZodOptional<z.ZodBoolean>;
150
+ launcher: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
151
+ navigationTimeoutSecs: z.ZodDefault<z.ZodCustom<number, number>>;
152
+ preNavigationHooks: z.ZodDefault<z.ZodCustom<unknown[], unknown[]>>;
153
+ postNavigationHooks: z.ZodDefault<z.ZodCustom<unknown[], unknown[]>>;
154
+ launchContext: z.ZodDefault<z.ZodCustom<Dictionary, Dictionary>>;
155
+ browserPool: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
156
+ browserPoolBuilder: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
157
+ remoteBrowser: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
158
+ saveResponseCookies: z.ZodDefault<z.ZodBoolean>;
159
+ proxyConfiguration: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
160
+ ignoreIframes: z.ZodDefault<z.ZodBoolean>;
161
+ ignoreShadowRoots: z.ZodDefault<z.ZodBoolean>;
162
+ contextPipelineBuilder: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
163
+ extendContext: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
164
+ requestList: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
165
+ requestQueue: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
166
+ requestManager: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
167
+ requestHandler: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
168
+ requestHandlerTimeoutSecs: z.ZodOptional<z.ZodCustom<number, number>>;
169
+ errorHandler: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
170
+ failedRequestHandler: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
171
+ maxRequestRetries: z.ZodDefault<z.ZodCustom<number, number>>;
172
+ sameDomainDelaySecs: z.ZodDefault<z.ZodCustom<number, number>>;
173
+ maxRequestsPerCrawl: z.ZodOptional<z.ZodCustom<number, number>>;
174
+ maxCrawlDepth: z.ZodOptional<z.ZodCustom<number, number>>;
175
+ taskLoopOptions: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
176
+ concurrencySystem: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
177
+ sessionPool: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
178
+ statusMessageLoggingInterval: z.ZodDefault<z.ZodCustom<number, number>>;
179
+ statusMessageCallback: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
180
+ additionalHttpErrorStatusCodes: z.ZodDefault<z.ZodArray<z.ZodCustom<number, number>>>;
181
+ ignoreHttpErrorStatusCodes: z.ZodDefault<z.ZodArray<z.ZodCustom<number, number>>>;
182
+ blockedStatusCodes: z.ZodOptional<z.ZodArray<z.ZodCustom<number, number>>>;
183
+ retryOnBlocked: z.ZodDefault<z.ZodBoolean>;
184
+ respectRobotsTxtFile: z.ZodDefault<z.ZodUnion<readonly [z.ZodBoolean, z.ZodCustom<Dictionary, Dictionary>]>>;
185
+ transactionalStorage: z.ZodOptional<z.ZodUnion<readonly [z.ZodBoolean, z.ZodObject<{
186
+ requestQueue: z.ZodOptional<z.ZodEnum<{
187
+ deferred: "deferred";
188
+ writeThrough: "writeThrough";
189
+ }>>;
190
+ }, z.core.$strict>]>>;
191
+ onSkippedRequest: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
192
+ // @ts-ignore optional peer dependency or compatibility with es2022
193
+ httpClient: z.ZodOptional<z.ZodCustom<import("@crawlee/http-client").BaseHttpClient, import("@crawlee/http-client").BaseHttpClient>>;
194
+ // @ts-ignore optional peer dependency or compatibility with es2022
195
+ configuration: z.ZodOptional<z.ZodCustom<import("@crawlee/browser").Configuration, import("@crawlee/browser").Configuration>>;
196
+ storageBackend: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
197
+ // @ts-ignore optional peer dependency or compatibility with es2022
198
+ eventManager: z.ZodOptional<z.ZodCustom<import("@crawlee/browser").EventManager, import("@crawlee/browser").EventManager>>;
199
+ logger: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
200
+ minConcurrency: z.ZodOptional<z.ZodCustom<number, number>>;
201
+ maxConcurrency: z.ZodOptional<z.ZodCustom<number, number>>;
202
+ maxRequestsPerMinute: z.ZodOptional<z.ZodCustom<number, number>>;
203
+ keepAlive: z.ZodOptional<z.ZodBoolean>;
204
+ statistics: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
205
+ id: z.ZodOptional<z.ZodString>;
228
206
  };
207
+ protected static optionsSchema: z.ZodObject<{
208
+ headless: z.ZodOptional<z.ZodBoolean>;
209
+ launcher: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
210
+ navigationTimeoutSecs: z.ZodDefault<z.ZodCustom<number, number>>;
211
+ preNavigationHooks: z.ZodDefault<z.ZodCustom<unknown[], unknown[]>>;
212
+ postNavigationHooks: z.ZodDefault<z.ZodCustom<unknown[], unknown[]>>;
213
+ launchContext: z.ZodDefault<z.ZodCustom<Dictionary, Dictionary>>;
214
+ browserPool: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
215
+ browserPoolBuilder: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
216
+ remoteBrowser: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
217
+ saveResponseCookies: z.ZodDefault<z.ZodBoolean>;
218
+ proxyConfiguration: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
219
+ ignoreIframes: z.ZodDefault<z.ZodBoolean>;
220
+ ignoreShadowRoots: z.ZodDefault<z.ZodBoolean>;
221
+ contextPipelineBuilder: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
222
+ extendContext: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
223
+ requestList: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
224
+ requestQueue: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
225
+ requestManager: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
226
+ requestHandler: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
227
+ requestHandlerTimeoutSecs: z.ZodOptional<z.ZodCustom<number, number>>;
228
+ errorHandler: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
229
+ failedRequestHandler: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
230
+ maxRequestRetries: z.ZodDefault<z.ZodCustom<number, number>>;
231
+ sameDomainDelaySecs: z.ZodDefault<z.ZodCustom<number, number>>;
232
+ maxRequestsPerCrawl: z.ZodOptional<z.ZodCustom<number, number>>;
233
+ maxCrawlDepth: z.ZodOptional<z.ZodCustom<number, number>>;
234
+ taskLoopOptions: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
235
+ concurrencySystem: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
236
+ sessionPool: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
237
+ statusMessageLoggingInterval: z.ZodDefault<z.ZodCustom<number, number>>;
238
+ statusMessageCallback: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
239
+ additionalHttpErrorStatusCodes: z.ZodDefault<z.ZodArray<z.ZodCustom<number, number>>>;
240
+ ignoreHttpErrorStatusCodes: z.ZodDefault<z.ZodArray<z.ZodCustom<number, number>>>;
241
+ blockedStatusCodes: z.ZodOptional<z.ZodArray<z.ZodCustom<number, number>>>;
242
+ retryOnBlocked: z.ZodDefault<z.ZodBoolean>;
243
+ respectRobotsTxtFile: z.ZodDefault<z.ZodUnion<readonly [z.ZodBoolean, z.ZodCustom<Dictionary, Dictionary>]>>;
244
+ transactionalStorage: z.ZodOptional<z.ZodUnion<readonly [z.ZodBoolean, z.ZodObject<{
245
+ requestQueue: z.ZodOptional<z.ZodEnum<{
246
+ deferred: "deferred";
247
+ writeThrough: "writeThrough";
248
+ }>>;
249
+ }, z.core.$strict>]>>;
250
+ onSkippedRequest: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
251
+ // @ts-ignore optional peer dependency or compatibility with es2022
252
+ httpClient: z.ZodOptional<z.ZodCustom<import("@crawlee/http-client").BaseHttpClient, import("@crawlee/http-client").BaseHttpClient>>;
253
+ // @ts-ignore optional peer dependency or compatibility with es2022
254
+ configuration: z.ZodOptional<z.ZodCustom<import("@crawlee/browser").Configuration, import("@crawlee/browser").Configuration>>;
255
+ storageBackend: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
256
+ // @ts-ignore optional peer dependency or compatibility with es2022
257
+ eventManager: z.ZodOptional<z.ZodCustom<import("@crawlee/browser").EventManager, import("@crawlee/browser").EventManager>>;
258
+ logger: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
259
+ minConcurrency: z.ZodOptional<z.ZodCustom<number, number>>;
260
+ maxConcurrency: z.ZodOptional<z.ZodCustom<number, number>>;
261
+ maxRequestsPerMinute: z.ZodOptional<z.ZodCustom<number, number>>;
262
+ keepAlive: z.ZodOptional<z.ZodBoolean>;
263
+ statistics: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
264
+ id: z.ZodOptional<z.ZodString>;
265
+ }, z.core.$strict>;
229
266
  /**
230
267
  * All `PlaywrightCrawler` parameters are passed via an options object.
231
268
  */
232
- constructor(options?: PlaywrightCrawlerOptions<ExtendedContext>, config?: Configuration);
233
- protected _navigationHandler(crawlingContext: PlaywrightCrawlingContext, gotoOptions: DirectNavigationOptions): Promise<Response | null>;
269
+ constructor(options?: PlaywrightCrawlerOptions<ContextExtension, ExtendedContext, Routes, StatisticStateExtension>);
270
+ // @ts-ignore optional peer dependency or compatibility with es2022
271
+ protected buildContextPipeline(): import("@crawlee/browser").ContextPipeline<import("@crawlee/browser").CrawlingContext<Dictionary>, BrowserCrawlingContext<Page, Response, Dictionary, Dictionary> & {
272
+ injectFile: (filePath: string, options?: InjectFileOptions) => Promise<unknown>;
273
+ injectJQuery: () => Promise<void>;
274
+ blockRequests: (options?: BlockRequestsOptions) => Promise<void>;
275
+ waitForSelector: (selector: string, timeoutMs?: number) => Promise<void>;
276
+ // @ts-ignore optional peer dependency or compatibility with es2022
277
+ parseWithCheerio: (selector?: string, timeoutMs?: number) => Promise<import("@crawlee/browser").CheerioAPI>;
278
+ infiniteScroll: (options?: InfiniteScrollOptions) => Promise<void>;
279
+ listDownloads: () => Promise<Download[]>;
280
+ saveSnapshot: (options?: SaveSnapshotOptions) => Promise<void>;
281
+ // @ts-ignore optional peer dependency or compatibility with es2022
282
+ enqueueLinksByClickingElements: (options: Omit<EnqueueLinksByClickingElementsOptions, "page" | "requestManager">) => Promise<import("@crawlee/types").BatchAddRequestsResult>;
283
+ // @ts-ignore optional peer dependency or compatibility with es2022
284
+ compileScript: (scriptString: string, ctx?: Dictionary) => import("./utils/playwright-utils.js").CompiledScriptFunction;
285
+ closeCookieModals: () => Promise<void>;
286
+ handleCloudflareChallenge: (options?: HandleCloudflareChallengeOptions) => Promise<Response | undefined>;
287
+ }>;
288
+ protected navigationHandler(crawlingContext: PlaywrightCrawlingContext, gotoOptions: DirectNavigationOptions): Promise<Response | null>;
234
289
  private enhanceContext;
235
290
  }
291
+ /**
292
+ * Returns a `postNavigationHooks`-ready hook that runs {@link PlaywrightContextUtils.handleCloudflareChallenge}
293
+ * and propagates the post-challenge {@link Response} back into the crawling context via its return value.
294
+ *
295
+ * **Example usage**
296
+ * ```ts
297
+ * import { PlaywrightCrawler, handleCloudflareChallengeHook } from 'crawlee';
298
+ *
299
+ * const crawler = new PlaywrightCrawler({
300
+ * postNavigationHooks: [handleCloudflareChallengeHook()],
301
+ * });
302
+ * ```
303
+ */
304
+ export declare function handleCloudflareChallengeHook(options?: HandleCloudflareChallengeOptions): PlaywrightHook;
236
305
  /**
237
306
  * Creates new {@link Router} instance that works based on request labels.
238
307
  * This instance can then serve as a `requestHandler` of your {@link PlaywrightCrawler}.
@@ -257,6 +326,6 @@ export declare class PlaywrightCrawler<ContextExtension = {}, ExtendedContext ex
257
326
  * await crawler.run();
258
327
  * ```
259
328
  */
260
- // @ts-ignore optional peer dependency or compatibility with es2022
261
- export declare function createPlaywrightRouter<Context extends PlaywrightCrawlingContext = PlaywrightCrawlingContext, UserData extends Dictionary = GetUserDataFromRequest<Context['request']>>(routes?: RouterRoutes<Context, UserData>): import("@crawlee/browser").RouterHandler<Context>;
262
- //# sourceMappingURL=playwright-crawler.d.ts.map
329
+ export declare function createPlaywrightRouter<Context extends PlaywrightCrawlingContext = PlaywrightCrawlingContext, Routes extends Record<keyof Routes, Dictionary> = Record<string, GetUserDataFromRequest<Context['request']>>>(routes?: RouterRoutes<Context, Routes>): RouterHandler<Context, Routes>;
330
+ export declare function createPlaywrightRouter<Context extends PlaywrightCrawlingContext = PlaywrightCrawlingContext, UserData extends Dictionary = GetUserDataFromRequest<Context['request']>>(routes?: RouterRoutes<Context, Record<string, UserData>>): RouterHandler<Context, Record<string, UserData>>;
331
+ export declare function createPlaywrightRouter<Context extends PlaywrightCrawlingContext = PlaywrightCrawlingContext, const Schemas extends RouteSchemas = RouteSchemas>(schemas: Schemas): RouterHandler<Context, RoutesFromSchemas<Schemas>>;
@@ -1,6 +1,6 @@
1
- import { BrowserCrawler, Configuration, RequestState, Router } from '@crawlee/browser';
2
- import ow from 'ow';
3
- import { PlaywrightLauncher } from './playwright-launcher.js';
1
+ import { assertBrowserPoolNotConfigured, BrowserCrawler, parseArgument, RequestState, Router, schemas, serviceLocator, } from '@crawlee/browser';
2
+ import { z } from 'zod';
3
+ import { playwrightBrowserPool, remotePlaywrightBrowserPool } from './playwright-browser-pool.js';
4
4
  import { gotoExtended, playwrightUtils } from './utils/playwright-utils.js';
5
5
  /**
6
6
  * Provides a simple framework for parallel crawling of web pages
@@ -13,24 +13,26 @@ import { gotoExtended, playwrightUtils } from './utils/playwright-utils.js';
13
13
  * If the target website doesn't need JavaScript, consider using {@link CheerioCrawler},
14
14
  * which downloads the pages using raw HTTP requests and is about 10x faster.
15
15
  *
16
- * The source URLs are represented using {@link Request} objects that are fed from
17
- * {@link RequestList} or {@link RequestQueue} instances provided by the {@link PlaywrightCrawlerOptions.requestList}
18
- * or {@link PlaywrightCrawlerOptions.requestQueue} constructor options, respectively.
16
+ * The source URLs are represented using {@link Request} objects that are fed from the
17
+ * {@link IRequestManager|request manager} provided via the {@link PlaywrightCrawlerOptions.requestManager|`requestManager`}
18
+ * constructor option (a {@link RequestQueue} is itself a request manager). To read from a read-only source such
19
+ * as a {@link RequestList} while still being able to enqueue new requests, combine it with a queue into a
20
+ * {@link RequestManagerTandem} via {@link IRequestLoader.toTandem|`requestLoader.toTandem()`} and pass the
21
+ * result as `requestManager`.
19
22
  *
20
- * If both {@link PlaywrightCrawlerOptions.requestList} and {@link PlaywrightCrawlerOptions.requestQueue} are used,
21
- * the instance first processes URLs from the {@link RequestList} and automatically enqueues all of them
22
- * to {@link RequestQueue} before it starts their processing. This ensures that a single URL is not crawled multiple times.
23
+ * > The {@link PlaywrightCrawlerOptions.requestList|`requestList`} and {@link PlaywrightCrawlerOptions.requestQueue|`requestQueue`}
24
+ * > options are deprecated; they are still accepted and folded into a single `requestManager` for back-compat.
23
25
  *
24
26
  * The crawler finishes when there are no more {@link Request} objects to crawl.
25
27
  *
26
28
  * `PlaywrightCrawler` opens a new Chrome page (i.e. tab) for each {@link Request} object to crawl
27
29
  * and then calls the function provided by user as the {@link PlaywrightCrawlerOptions.requestHandler} option.
28
30
  *
29
- * New pages are only opened when there is enough free CPU and memory available,
30
- * using the functionality provided by the {@link AutoscaledPool} class.
31
- * All {@link AutoscaledPool} configuration options can be passed to the {@link PlaywrightCrawlerOptions.autoscaledPoolOptions}
32
- * parameter of the `PlaywrightCrawler` constructor. For user convenience, the `minConcurrency` and `maxConcurrency`
33
- * {@link AutoscaledPoolOptions} are available directly in the `PlaywrightCrawler` constructor.
31
+ * New pages are only opened when there is enough free CPU and memory available, as judged by the crawler's
32
+ * {@link ConcurrencySystem}.
33
+ * Concurrency is tuned via the `minConcurrency`, `maxConcurrency` and `maxRequestsPerMinute` options of the
34
+ * `PlaywrightCrawler` constructor, or, for finer control, by injecting a pre-configured
35
+ * {@link ConcurrencySystem|`concurrencySystem`}.
34
36
  *
35
37
  * Note that the pool of Playwright instances is internally managed by the [BrowserPool](https://github.com/apify/browser-pool) class.
36
38
  *
@@ -66,47 +68,43 @@ import { gotoExtended, playwrightUtils } from './utils/playwright-utils.js';
66
68
  * @category Crawlers
67
69
  */
68
70
  export class PlaywrightCrawler extends BrowserCrawler {
69
- config;
70
71
  static optionsShape = {
71
72
  ...BrowserCrawler.optionsShape,
72
- browserPoolOptions: ow.optional.object,
73
- launcher: ow.optional.object,
74
- ignoreIframes: ow.optional.boolean,
75
- ignoreShadowRoots: ow.optional.boolean,
73
+ headless: z.boolean().optional(),
74
+ launcher: schemas.anyObject.optional(),
76
75
  };
76
+ static optionsSchema = z.strictObject(PlaywrightCrawler.optionsShape);
77
77
  /**
78
78
  * All `PlaywrightCrawler` parameters are passed via an options object.
79
79
  */
80
- constructor(options = {}, config = Configuration.getGlobalConfig()) {
81
- ow(options, 'PlaywrightCrawlerOptions', ow.object.exactShape(PlaywrightCrawler.optionsShape));
82
- const { launchContext = {}, headless, ...browserCrawlerOptions } = options;
83
- const browserPoolOptions = {
84
- ...options.browserPoolOptions,
85
- };
80
+ constructor(options = {}) {
81
+ const parsedOptions = parseArgument(options, PlaywrightCrawler.optionsSchema, 'PlaywrightCrawlerOptions');
82
+ const { launchContext, headless, configuration, contextPipelineBuilder, ...browserCrawlerOptions } = parsedOptions;
86
83
  if (launchContext.proxyUrl) {
87
84
  throw new Error('PlaywrightCrawlerOptions.launchContext.proxyUrl is not allowed in PlaywrightCrawler.' +
88
85
  'Use PlaywrightCrawlerOptions.proxyConfiguration');
89
86
  }
90
- // `browserPlugins` is working when it's not overridden by `launchContext`,
91
- // which for crawlers it is always overridden. Hence the error to use the other option.
92
- if (browserPoolOptions.browserPlugins) {
93
- throw new Error('browserPoolOptions.browserPlugins is disallowed. Use launchContext.launcher instead.');
94
- }
95
- if (headless != null) {
96
- launchContext.launchOptions ??= {};
97
- launchContext.launchOptions.headless = headless;
87
+ if (options.browserPool) {
88
+ // The raw options, not the parsed ones: `launchContext` has a default, so by now it is always set.
89
+ assertBrowserPoolNotConfigured(new.target.name, {
90
+ launchContext: options.launchContext,
91
+ headless: options.headless,
92
+ });
98
93
  }
99
- const playwrightLauncher = new PlaywrightLauncher(launchContext, config);
100
- browserPoolOptions.browserPlugins = [playwrightLauncher.createBrowserPlugin()];
101
94
  super({
102
95
  ...browserCrawlerOptions,
103
96
  launchContext,
104
- browserPoolOptions,
105
- contextPipelineBuilder: () => this.buildContextPipeline().compose({ action: this.enhanceContext.bind(this) }),
106
- }, config);
107
- this.config = config;
97
+ configuration,
98
+ browserPoolBuilder: (remoteBrowser) => remoteBrowser
99
+ ? remotePlaywrightBrowserPool({ ...remoteBrowser, launchContext, headless, configuration })
100
+ : playwrightBrowserPool({ launchContext, headless, configuration }),
101
+ contextPipelineBuilder: contextPipelineBuilder ?? (() => this.buildContextPipeline()),
102
+ });
103
+ }
104
+ buildContextPipeline() {
105
+ return super.buildContextPipeline().compose({ action: this.enhanceContext.bind(this) });
108
106
  }
109
- async _navigationHandler(crawlingContext, gotoOptions) {
107
+ async navigationHandler(crawlingContext, gotoOptions) {
110
108
  return gotoExtended(crawlingContext.page, crawlingContext.request, gotoOptions);
111
109
  }
112
110
  async enhanceContext(context) {
@@ -114,6 +112,8 @@ export class PlaywrightCrawler extends BrowserCrawler {
114
112
  const locator = context.page.locator(selector).first();
115
113
  await locator.waitFor({ timeout: timeoutMs, state: 'attached' });
116
114
  };
115
+ const downloads = [];
116
+ context.page.on('download', (download) => downloads.push(download));
117
117
  return {
118
118
  injectFile: async (filePath, options) => playwrightUtils.injectFile(context.page, filePath, options),
119
119
  injectJQuery: async () => {
@@ -133,45 +133,46 @@ export class PlaywrightCrawler extends BrowserCrawler {
133
133
  return playwrightUtils.parseWithCheerio(context.page, this.ignoreShadowRoots, this.ignoreIframes);
134
134
  },
135
135
  infiniteScroll: async (options) => playwrightUtils.infiniteScroll(context.page, options),
136
- saveSnapshot: async (options) => playwrightUtils.saveSnapshot(context.page, { ...options, config: this.config }),
136
+ listDownloads: async () => downloads,
137
+ saveSnapshot: async (options) => playwrightUtils.saveSnapshot(context.page, {
138
+ ...options,
139
+ configuration: serviceLocator.getConfiguration(),
140
+ }),
137
141
  enqueueLinksByClickingElements: async (options) => playwrightUtils.enqueueLinksByClickingElements({
138
142
  ...options,
139
143
  page: context.page,
140
- requestQueue: this.requestQueue,
144
+ requestManager: this.requestManager,
141
145
  }),
142
146
  compileScript: (scriptString, ctx) => playwrightUtils.compileScript(scriptString, ctx),
143
147
  closeCookieModals: async () => playwrightUtils.closeCookieModals(context.page),
144
148
  handleCloudflareChallenge: async (options) => {
145
- return playwrightUtils.handleCloudflareChallenge(context.page, context.request.url, context.session, options);
149
+ return playwrightUtils.handleCloudflareChallenge(context.page, context.request.url, options);
146
150
  },
147
151
  };
148
152
  }
149
153
  }
150
154
  /**
151
- * Creates new {@link Router} instance that works based on request labels.
152
- * This instance can then serve as a `requestHandler` of your {@link PlaywrightCrawler}.
153
- * Defaults to the {@link PlaywrightCrawlingContext}.
154
- *
155
- * > Serves as a shortcut for using `Router.create<PlaywrightCrawlingContext>()`.
155
+ * Returns a `postNavigationHooks`-ready hook that runs {@link PlaywrightContextUtils.handleCloudflareChallenge}
156
+ * and propagates the post-challenge {@link Response} back into the crawling context via its return value.
156
157
  *
158
+ * **Example usage**
157
159
  * ```ts
158
- * import { PlaywrightCrawler, createPlaywrightRouter } from 'crawlee';
159
- *
160
- * const router = createPlaywrightRouter();
161
- * router.addHandler('label-a', async (ctx) => {
162
- * ctx.log.info('...');
163
- * });
164
- * router.addDefaultHandler(async (ctx) => {
165
- * ctx.log.info('...');
166
- * });
160
+ * import { PlaywrightCrawler, handleCloudflareChallengeHook } from 'crawlee';
167
161
  *
168
162
  * const crawler = new PlaywrightCrawler({
169
- * requestHandler: router,
163
+ * postNavigationHooks: [handleCloudflareChallengeHook()],
170
164
  * });
171
- * await crawler.run();
172
165
  * ```
173
166
  */
174
- export function createPlaywrightRouter(routes) {
175
- return Router.create(routes);
167
+ export function handleCloudflareChallengeHook(options) {
168
+ return async (context) => {
169
+ const response = await context.handleCloudflareChallenge(options);
170
+ if (response !== undefined) {
171
+ return { response };
172
+ }
173
+ return undefined;
174
+ };
175
+ }
176
+ export function createPlaywrightRouter(routesOrSchemas) {
177
+ return Router.create(routesOrSchemas);
176
178
  }
177
- //# sourceMappingURL=playwright-crawler.js.map