@crawlee/playwright 4.0.0-beta.14 → 4.0.0-beta.141

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 (32) hide show
  1. package/README.md +14 -14
  2. package/index.d.ts +2 -2
  3. package/index.js +1 -1
  4. package/internals/adaptive-playwright-crawler.d.ts +116 -63
  5. package/internals/adaptive-playwright-crawler.js +312 -264
  6. package/internals/enqueue-links/click-elements.d.ts +36 -64
  7. package/internals/enqueue-links/click-elements.js +64 -67
  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 +178 -125
  11. package/internals/playwright-crawler.js +68 -62
  12. package/internals/playwright-launcher.d.ts +32 -18
  13. package/internals/playwright-launcher.js +23 -17
  14. package/internals/utils/playwright-utils.d.ts +54 -26
  15. package/internals/utils/playwright-utils.js +112 -93
  16. package/internals/utils/rendering-type-prediction.d.ts +25 -10
  17. package/internals/utils/rendering-type-prediction.js +77 -22
  18. package/package.json +15 -15
  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
@@ -3,6 +3,7 @@ import { BrowserLauncher, Configuration } from '@crawlee/browser';
3
3
  import { PlaywrightPlugin } from '@crawlee/browser-pool';
4
4
  // @ts-ignore optional peer dependency or compatibility with es2022
5
5
  import type { Browser, BrowserType, LaunchOptions } from 'playwright';
6
+ import { z } from 'zod';
6
7
  /**
7
8
  * Apify extends the launch options of Playwright.
8
9
  * You can use any of the Playwright compatible
@@ -70,31 +71,45 @@ export interface PlaywrightLaunchContext extends BrowserLaunchContext<LaunchOpti
70
71
  * @ignore
71
72
  */
72
73
  export declare class PlaywrightLauncher extends BrowserLauncher<PlaywrightPlugin> {
73
- readonly config: Configuration;
74
+ readonly configuration: Configuration;
75
+ /**
76
+ * @internal
77
+ */
74
78
  protected static optionsShape: {
75
79
  // @ts-ignore optional peer dependency or compatibility with es2022
76
- launcher: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
77
- // @ts-ignore optional peer dependency or compatibility with es2022
78
- launchContextOptions: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
79
- // @ts-ignore optional peer dependency or compatibility with es2022
80
- proxyUrl: import("ow").StringPredicate & import("ow").BasePredicate<string | undefined>;
80
+ launcher: z.ZodOptional<z.ZodCustom<import("@crawlee/types").Dictionary, import("@crawlee/types").Dictionary>>;
81
81
  // @ts-ignore optional peer dependency or compatibility with es2022
82
- useChrome: import("ow").BooleanPredicate & import("ow").BasePredicate<boolean | undefined>;
82
+ launchContextOptions: z.ZodOptional<z.ZodCustom<import("@crawlee/types").Dictionary, import("@crawlee/types").Dictionary>>;
83
+ proxyUrl: z.ZodOptional<z.ZodURL>;
84
+ useChrome: z.ZodOptional<z.ZodBoolean>;
85
+ useIncognitoPages: z.ZodOptional<z.ZodBoolean>;
86
+ browserPerProxy: z.ZodOptional<z.ZodBoolean>;
87
+ ignoreProxyCertificate: z.ZodOptional<z.ZodBoolean>;
88
+ userDataDir: z.ZodOptional<z.ZodString>;
83
89
  // @ts-ignore optional peer dependency or compatibility with es2022
84
- useIncognitoPages: import("ow").BooleanPredicate & import("ow").BasePredicate<boolean | undefined>;
85
- // @ts-ignore optional peer dependency or compatibility with es2022
86
- browserPerProxy: import("ow").BooleanPredicate & import("ow").BasePredicate<boolean | undefined>;
90
+ launchOptions: z.ZodOptional<z.ZodCustom<import("@crawlee/types").Dictionary, import("@crawlee/types").Dictionary>>;
91
+ userAgent: z.ZodOptional<z.ZodString>;
92
+ };
93
+ /** @internal */
94
+ protected static optionsSchema: z.ZodObject<{
87
95
  // @ts-ignore optional peer dependency or compatibility with es2022
88
- userDataDir: import("ow").StringPredicate & import("ow").BasePredicate<string | undefined>;
96
+ launcher: z.ZodOptional<z.ZodCustom<import("@crawlee/types").Dictionary, import("@crawlee/types").Dictionary>>;
89
97
  // @ts-ignore optional peer dependency or compatibility with es2022
90
- launchOptions: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
98
+ launchContextOptions: z.ZodOptional<z.ZodCustom<import("@crawlee/types").Dictionary, import("@crawlee/types").Dictionary>>;
99
+ proxyUrl: z.ZodOptional<z.ZodURL>;
100
+ useChrome: z.ZodOptional<z.ZodBoolean>;
101
+ useIncognitoPages: z.ZodOptional<z.ZodBoolean>;
102
+ browserPerProxy: z.ZodOptional<z.ZodBoolean>;
103
+ ignoreProxyCertificate: z.ZodOptional<z.ZodBoolean>;
104
+ userDataDir: z.ZodOptional<z.ZodString>;
91
105
  // @ts-ignore optional peer dependency or compatibility with es2022
92
- userAgent: import("ow").StringPredicate & import("ow").BasePredicate<string | undefined>;
93
- };
106
+ launchOptions: z.ZodOptional<z.ZodCustom<import("@crawlee/types").Dictionary, import("@crawlee/types").Dictionary>>;
107
+ userAgent: z.ZodOptional<z.ZodString>;
108
+ }, z.core.$strict>;
94
109
  /**
95
110
  * All `PlaywrightLauncher` parameters are passed via this launchContext object.
96
111
  */
97
- constructor(launchContext?: PlaywrightLaunchContext, config?: Configuration);
112
+ constructor(launchContext?: PlaywrightLaunchContext, configuration?: Configuration);
98
113
  }
99
114
  /**
100
115
  * Launches headless browsers using Playwright pre-configured to work within the Apify platform.
@@ -125,9 +140,8 @@ export declare class PlaywrightLauncher extends BrowserLauncher<PlaywrightPlugin
125
140
  * Optional settings passed to `browserType.launch()`. In addition to
126
141
  * [Playwright's options](https://playwright.dev/docs/api/class-browsertype?_highlight=launch#browsertypelaunchoptions)
127
142
  * the object may contain our own {@link PlaywrightLaunchContext} that enable additional features.
128
- * @param [config]
143
+ * @param [configuration]
129
144
  * @returns
130
145
  * Promise that resolves to Playwright's `Browser` instance.
131
146
  */
132
- export declare function launchPlaywright(launchContext?: PlaywrightLaunchContext, config?: Configuration): Promise<Browser>;
133
- //# sourceMappingURL=playwright-launcher.d.ts.map
147
+ export declare function launchPlaywright(launchContext?: PlaywrightLaunchContext, configuration?: Configuration): Promise<Browser>;
@@ -1,33 +1,40 @@
1
1
  import { BrowserLauncher, Configuration } from '@crawlee/browser';
2
2
  import { PlaywrightPlugin } from '@crawlee/browser-pool';
3
- import ow from 'ow';
3
+ import { parseArgument, schemas } from '@crawlee/utils/internal';
4
+ import { z } from 'zod';
4
5
  /**
5
6
  * `PlaywrightLauncher` is based on the `BrowserLauncher`. It launches `playwright` browser instance.
6
7
  * @ignore
7
8
  */
8
9
  export class PlaywrightLauncher extends BrowserLauncher {
9
- config;
10
+ configuration;
11
+ /**
12
+ * @internal
13
+ */
10
14
  static optionsShape = {
11
15
  ...BrowserLauncher.optionsShape,
12
- launcher: ow.optional.object,
13
- launchContextOptions: ow.optional.object,
16
+ // Passthrough schemas — the launcher module object must keep its prototype through parsing.
17
+ launcher: schemas.anyObject.optional(),
18
+ launchContextOptions: schemas.anyObject.optional(),
14
19
  };
20
+ /** @internal */
21
+ static optionsSchema = z.strictObject(PlaywrightLauncher.optionsShape);
15
22
  /**
16
23
  * All `PlaywrightLauncher` parameters are passed via this launchContext object.
17
24
  */
18
- constructor(launchContext = {}, config = Configuration.getGlobalConfig()) {
19
- ow(launchContext, 'PlaywrightLauncherOptions', ow.object.exactShape(PlaywrightLauncher.optionsShape));
20
- const { launcher = BrowserLauncher.requireLauncherOrThrow('playwright', 'apify/actor-node-playwright-*').chromium, } = launchContext;
21
- const { launchOptions = {}, ...rest } = launchContext;
25
+ constructor(launchContext = {}, configuration = Configuration.getGlobalConfiguration()) {
26
+ const parsedContext = parseArgument(launchContext, PlaywrightLauncher.optionsSchema, 'PlaywrightLaunchContext');
27
+ const { launcher = BrowserLauncher.requireLauncherOrThrow('playwright', 'apify/actor-node-playwright-*').chromium, } = parsedContext;
28
+ const { launchOptions = {}, ...rest } = parsedContext;
22
29
  super({
23
30
  ...rest,
24
31
  launchOptions: {
25
32
  ...launchOptions,
26
- executablePath: getDefaultExecutablePath(launchContext, config),
33
+ executablePath: getDefaultExecutablePath(parsedContext, configuration),
27
34
  },
28
35
  launcher,
29
- }, config);
30
- this.config = config;
36
+ }, configuration);
37
+ this.configuration = configuration;
31
38
  this.Plugin = PlaywrightPlugin;
32
39
  }
33
40
  }
@@ -36,8 +43,8 @@ export class PlaywrightLauncher extends BrowserLauncher {
36
43
  * @returns default path to browser.
37
44
  * @ignore
38
45
  */
39
- function getDefaultExecutablePath(launchContext, config) {
40
- const pathFromPlaywrightImage = config.get('defaultBrowserPath');
46
+ function getDefaultExecutablePath(launchContext, configuration) {
47
+ const pathFromPlaywrightImage = configuration.defaultBrowserPath;
41
48
  const { launchOptions = {} } = launchContext;
42
49
  if (launchOptions.executablePath) {
43
50
  return launchOptions.executablePath;
@@ -79,12 +86,11 @@ function getDefaultExecutablePath(launchContext, config) {
79
86
  * Optional settings passed to `browserType.launch()`. In addition to
80
87
  * [Playwright's options](https://playwright.dev/docs/api/class-browsertype?_highlight=launch#browsertypelaunchoptions)
81
88
  * the object may contain our own {@link PlaywrightLaunchContext} that enable additional features.
82
- * @param [config]
89
+ * @param [configuration]
83
90
  * @returns
84
91
  * Promise that resolves to Playwright's `Browser` instance.
85
92
  */
86
- export async function launchPlaywright(launchContext, config = Configuration.getGlobalConfig()) {
87
- const playwrightLauncher = new PlaywrightLauncher(launchContext, config);
93
+ export async function launchPlaywright(launchContext, configuration = Configuration.getGlobalConfiguration()) {
94
+ const playwrightLauncher = new PlaywrightLauncher(launchContext, configuration);
88
95
  return playwrightLauncher.launch();
89
96
  }
90
- //# sourceMappingURL=playwright-launcher.js.map
@@ -17,11 +17,11 @@
17
17
  * ```
18
18
  * @module playwrightUtils
19
19
  */
20
- import { Configuration, type Request, type Session } from '@crawlee/browser';
21
- import type { BatchAddRequestsResult } from '@crawlee/types';
22
- import { type CheerioRoot, type Dictionary } from '@crawlee/utils';
20
+ import { Configuration, type Request } from '@crawlee/browser';
21
+ import type { BatchAddRequestsResult, Dictionary } from '@crawlee/types';
22
+ import type { CheerioAPI } from 'cheerio';
23
23
  // @ts-ignore optional peer dependency or compatibility with es2022
24
- import type { Page, Response } from 'playwright';
24
+ import type { Download, Page, Response } from 'playwright';
25
25
  import type { EnqueueLinksByClickingElementsOptions } from '../enqueue-links/click-elements.js';
26
26
  import { enqueueLinksByClickingElements } from '../enqueue-links/click-elements.js';
27
27
  import { RenderingTypePredictor } from './rendering-type-prediction.js';
@@ -265,9 +265,9 @@ export interface SaveSnapshotOptions {
265
265
  keyValueStoreName?: string | null;
266
266
  /**
267
267
  * Configuration of the crawler that will be used to save the snapshot.
268
- * @default Configuration.getGlobalConfig()
268
+ * @default Configuration.getGlobalConfiguration()
269
269
  */
270
- config?: Configuration;
270
+ configuration?: Configuration;
271
271
  }
272
272
  /**
273
273
  * Saves a full screenshot and HTML of the current page into a Key-Value store.
@@ -287,7 +287,7 @@ export declare function saveSnapshot(page: Page, options?: SaveSnapshotOptions):
287
287
  * @param page Playwright [`Page`](https://playwright.dev/docs/api/class-page) object.
288
288
  * @param ignoreShadowRoots
289
289
  */
290
- export declare function parseWithCheerio(page: Page, ignoreShadowRoots?: boolean, ignoreIframes?: boolean): Promise<CheerioRoot>;
290
+ export declare function parseWithCheerio(page: Page, ignoreShadowRoots?: boolean, ignoreIframes?: boolean): Promise<CheerioAPI>;
291
291
  export declare function closeCookieModals(page: Page): Promise<void>;
292
292
  export interface HandleCloudflareChallengeOptions {
293
293
  /** Logging defaults to the `debug` level, use this flag to log to `info` level instead. */
@@ -303,6 +303,13 @@ export interface HandleCloudflareChallengeOptions {
303
303
  isChallengeCallback?: (page: Page) => Promise<boolean>;
304
304
  /** Allows overriding the detection of Cloudflare "blocked page". */
305
305
  isBlockedCallback?: (page: Page) => Promise<boolean>;
306
+ /** Allows overriding how the checkbox click position is calculated. */
307
+ clickPositionCallback?: (page: Page) => Promise<{
308
+ x: number;
309
+ y: number;
310
+ } | null>;
311
+ /** Optional delay (in seconds) before the first click attempt on the challenge checkbox. Defaults to 1s. */
312
+ preChallengeSleepSecs?: number;
306
313
  }
307
314
  /**
308
315
  * This helper tries to solve the Cloudflare challenge automatically by clicking on the checkbox.
@@ -311,24 +318,24 @@ export interface HandleCloudflareChallengeOptions {
311
318
  * result in a SessionError which will be automatically retried, so only successful requests will get
312
319
  * into the `requestHandler`.
313
320
  *
321
+ * On a successfully solved challenge the page is reloaded and the new {@link Response} is returned, so
322
+ * it can be propagated back to the crawling context via a hook return value (see
323
+ * {@link handleCloudflareChallengeHook}).
324
+ *
314
325
  * Works best with camoufox.
315
326
  *
316
327
  * **Example usage**
317
328
  * ```ts
318
329
  * postNavigationHooks: [
319
- * async ({ handleCloudflareChallenge }) => {
320
- * await handleCloudflareChallenge();
321
- * },
330
+ * async (context) => ({ response: await context.handleCloudflareChallenge() }),
322
331
  * ],
323
332
  * ```
324
333
  *
325
334
  * @param page Playwright [`Page`](https://playwright.dev/docs/api/class-page) object
326
335
  * @param url current URL for request identification, only used for logging
327
- * @param [session] current session object
328
336
  * @param [options]
329
337
  */
330
- declare function handleCloudflareChallenge(page: Page, url: string, session?: Session, options?: HandleCloudflareChallengeOptions): Promise<void>;
331
- /** @internal */
338
+ declare function handleCloudflareChallenge(page: Page, url: string, options?: HandleCloudflareChallengeOptions): Promise<Response | undefined>;
332
339
  export interface PlaywrightContextUtils {
333
340
  /**
334
341
  * Injects a JavaScript file into current `page`.
@@ -427,7 +434,7 @@ export interface PlaywrightContextUtils {
427
434
  * });
428
435
  * ```
429
436
  */
430
- parseWithCheerio(selector?: string, timeoutMs?: number): Promise<CheerioRoot>;
437
+ parseWithCheerio(selector?: string, timeoutMs?: number): Promise<CheerioAPI>;
431
438
  /**
432
439
  * Scrolls to the bottom of a page, or until it times out.
433
440
  * Loads dynamic content when it hits the bottom of a page, and then continues scrolling.
@@ -447,8 +454,7 @@ export interface PlaywrightContextUtils {
447
454
  * in `href` elements, but rather navigations are triggered in click handlers.
448
455
  * If you're looking to find URLs in `href` attributes of the page, see {@link enqueueLinks}.
449
456
  *
450
- * Optionally, the function allows you to filter the target links' URLs using an array of {@link PseudoUrl} objects
451
- * and override settings of the enqueued {@link Request} objects.
457
+ * Optionally, the function allows you to filter the target links' URLs using an array of glob or regexp patterns.
452
458
  *
453
459
  * **IMPORTANT**: To be able to do this, this function uses various mutations on the page,
454
460
  * such as changing the Z-index of elements being clicked and their visibility. Therefore,
@@ -469,9 +475,9 @@ export interface PlaywrightContextUtils {
469
475
  * async requestHandler({ enqueueLinksByClickingElements }) {
470
476
  * await enqueueLinksByClickingElements({
471
477
  * selector: 'a.product-detail',
472
- * globs: [
473
- * 'https://www.example.com/handbags/**'
474
- * 'https://www.example.com/purses/**'
478
+ * include: [
479
+ * 'https://www.example.com/handbags/**',
480
+ * 'https://www.example.com/purses/**',
475
481
  * ],
476
482
  * });
477
483
  * });
@@ -479,7 +485,7 @@ export interface PlaywrightContextUtils {
479
485
  *
480
486
  * @returns Promise that resolves to {@link BatchAddRequestsResult} object.
481
487
  */
482
- enqueueLinksByClickingElements(options: Omit<EnqueueLinksByClickingElementsOptions, 'page' | 'requestQueue'>): Promise<BatchAddRequestsResult>;
488
+ enqueueLinksByClickingElements(options: Omit<EnqueueLinksByClickingElementsOptions, 'page' | 'requestManager'>): Promise<BatchAddRequestsResult>;
483
489
  /**
484
490
  * Compiles a Playwright script into an async function that may be executed at any time
485
491
  * by providing it with the following object:
@@ -527,20 +533,43 @@ export interface PlaywrightContextUtils {
527
533
  * result in a SessionError which will be automatically retried, so only successful requests will get
528
534
  * into the `requestHandler`.
529
535
  *
530
- * Works best with camoufox.
536
+ * On a successfully solved challenge the page is reloaded and the new {@link Response} is returned,
537
+ * which can be returned from the hook to update the crawling context's `response`. For the common case,
538
+ * prefer the pre-wrapped {@link handleCloudflareChallengeHook} hook.
531
539
  *
532
540
  * **Example usage**
533
541
  * ```ts
534
542
  * postNavigationHooks: [
535
- * async ({ handleCloudflareChallenge }) => {
536
- * await handleCloudflareChallenge();
537
- * },
543
+ * async (context) => ({ response: await context.handleCloudflareChallenge() }),
538
544
  * ],
539
545
  * ```
540
546
  *
541
547
  * @param [options]
542
548
  */
543
- handleCloudflareChallenge(options?: HandleCloudflareChallengeOptions): Promise<void>;
549
+ handleCloudflareChallenge(options?: HandleCloudflareChallengeOptions): Promise<Response | undefined>;
550
+ /**
551
+ * Returns the list of {@link https://playwright.dev/docs/api/class-download | Download} objects
552
+ * collected during the current page navigation and request handler.
553
+ *
554
+ * Useful for accessing files that the page downloads automatically.
555
+ * For most use cases, prefer re-enqueueing the URL to {@link FileDownload}.
556
+ * Use this only when direct access to the Playwright `Download` object is required.
557
+ *
558
+ * **Example usage**
559
+ * ```ts
560
+ * requestHandler: async ({ listDownloads }) => {
561
+ * for (const download of await listDownloads()) {
562
+ * try {
563
+ * const stream = await download.createReadStream();
564
+ * // stream to storage...
565
+ * } catch {
566
+ * // download failed or was cancelled
567
+ * }
568
+ * }
569
+ * },
570
+ * ```
571
+ */
572
+ listDownloads(): Promise<Download[]>;
544
573
  }
545
574
  export { enqueueLinksByClickingElements };
546
575
  /** @internal */
@@ -558,4 +587,3 @@ export declare const playwrightUtils: {
558
587
  RenderingTypePredictor: typeof RenderingTypePredictor;
559
588
  handleCloudflareChallenge: typeof handleCloudflareChallenge;
560
589
  };
561
- //# sourceMappingURL=playwright-utils.d.ts.map