@crawlee/playwright 4.0.0-beta.323 → 4.0.0-beta.325

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.
@@ -1,6 +1,6 @@
1
1
  import { setTimeout as delay } from 'node:timers/promises';
2
2
  import { isDeepStrictEqual } from 'node:util';
3
- import { BasicCrawler, ContextPipeline, ContextPipelineInitializationError, ContextPipelineInterruptedError, navigationDeadlineKey, RequestHandlerError, resolveBaseUrlForEnqueueLinksFiltering, Router, Statistics, } from '@crawlee/basic';
3
+ import { BasicCrawler, ContextPipeline, ContextPipelineCleanupError, ContextPipelineInitializationError, ContextPipelineInterruptedError, navigationDeadlineKey, RequestHandlerError, resolveBaseUrlForEnqueueLinksFiltering, Router, Statistics, } from '@crawlee/basic';
4
4
  import { CrawlingRequest, extractUrlsFromPage } from '@crawlee/browser';
5
5
  import { CheerioCrawler } from '@crawlee/cheerio';
6
6
  import { ResponseWithUrl } from '@crawlee/http-client';
@@ -10,6 +10,86 @@ import { z } from 'zod';
10
10
  import { addTimeoutToPromise } from '@apify/timeout';
11
11
  import { PlaywrightCrawler } from './playwright-crawler.js';
12
12
  import { RenderingTypePredictor, } from './utils/rendering-type-prediction.js';
13
+ /**
14
+ * A failed attempt stops before its cleanups (closing the page) until released, so the error handlers still get an
15
+ * open page, as in `BasicCrawler`.
16
+ */
17
+ class Attempt {
18
+ transaction;
19
+ #failure = Promise.withResolvers();
20
+ #failed = false;
21
+ #cleanupsReleased = Promise.withResolvers();
22
+ #call;
23
+ #context;
24
+ #heldBeforeCleanups = false;
25
+ #releaseDeferred = false;
26
+ constructor(transaction) {
27
+ this.transaction = transaction;
28
+ this.#failure.promise.catch(() => { });
29
+ }
30
+ /** Settles without waiting for a failed run's cleanups. */
31
+ async run(pipeline, context, consumer) {
32
+ this.#context = context;
33
+ this.#call = pipeline.call(context, consumer, async (error) => {
34
+ this.#heldBeforeCleanups = true;
35
+ this.fail(error);
36
+ await this.#cleanupsReleased.promise;
37
+ throw error;
38
+ });
39
+ await Promise.race([this.#call, this.#failure.promise]);
40
+ }
41
+ fail(reason) {
42
+ this.#failed = true;
43
+ this.#failure.reject(reason);
44
+ }
45
+ /** Stops waiting for `handler` once the run fails - a timeout does not stop it. */
46
+ abandonable(handler) {
47
+ return async (context) => {
48
+ // The run may have failed before the handler starts - then it never starts.
49
+ if (this.#failed) {
50
+ return this.#failure.promise;
51
+ }
52
+ return Promise.race([handler(context), this.#failure.promise]);
53
+ };
54
+ }
55
+ /** Idempotent. */
56
+ async release() {
57
+ this.#cleanupsReleased.resolve();
58
+ // Not waited for if still in a middleware or a non-abandonable handler.
59
+ if (this.#heldBeforeCleanups) {
60
+ await this.#call?.catch((error) => {
61
+ if (error instanceof ContextPipelineCleanupError)
62
+ throw error;
63
+ });
64
+ }
65
+ }
66
+ /** Lets the error handlers, which get the outer `context`, use this attempt's page and helpers. */
67
+ exposeToErrorHandlers(context) {
68
+ this.#releaseDeferred = true;
69
+ // Before the attempt's own `registerDeferredCleanup` replaces the outer one below.
70
+ context.registerDeferredCleanup(async () => this.release());
71
+ const descriptors = Object.getOwnPropertyDescriptors(this.#context ?? {});
72
+ for (const key of Reflect.ownKeys(descriptors)) {
73
+ // The attempt-bound helpers (non-configurable, see `#crawlOne`) and the navigation deadline stay here.
74
+ if (descriptors[key].configurable === false || key === navigationDeadlineKey) {
75
+ delete descriptors[key];
76
+ }
77
+ }
78
+ Object.defineProperties(context, descriptors);
79
+ }
80
+ async settle() {
81
+ try {
82
+ if (!this.#releaseDeferred) {
83
+ await this.release();
84
+ }
85
+ }
86
+ finally {
87
+ // Closed even when a cleanup threw - the writes it still holds must never reach storage.
88
+ this.transaction.rollback();
89
+ this.transaction.dispose();
90
+ }
91
+ }
92
+ }
13
93
  const adaptiveStatisticStateSchema = z.object({
14
94
  /** How many requests were handled by the HTTP-only request handler. */
15
95
  httpOnlyRequestHandlerRuns: z.number().default(0),
@@ -253,26 +333,40 @@ export class AdaptivePlaywrightCrawler extends BasicCrawler {
253
333
  const urls = extractUrlsFromCheerio(cheerioContext.$, options.selector, options.baseUrl ?? cheerioContext.request.loadedUrl);
254
334
  return (await this.#enqueueLinks(urls, options, cheerioContext.request));
255
335
  },
256
- // The HTTP crawler has already consumed the body; hand out a fresh copy, like the browser side does.
257
- // HTML bodies are already decoded to UTF-8, so `arrayBuffer()` may disagree with the original headers.
258
- response: new ResponseWithUrl(cheerioContext.body, cheerioContext.response),
336
+ // `skipNavigation` keeps the inner throwing getter. The body is already consumed (and decoded to UTF-8).
337
+ ...(cheerioContext.request.skipNavigation
338
+ ? {}
339
+ : { response: new ResponseWithUrl(cheerioContext.body, cheerioContext.response) }),
259
340
  };
260
341
  }
261
342
  async #adaptPlaywrightContext(playwrightContext) {
262
- // Capture the original response to avoid infinite recursion when the getter is copied to the context
263
- const originalResponse = playwrightContext.response;
264
- // `headers()` can return repeated headers (e.g. `set-cookie`) joined with `\n`, which `Headers` rejects
265
- const headers = new Headers();
266
- for (const { name, value } of await originalResponse.headersArray()) {
267
- headers.append(name, value);
343
+ // Capture the original response to avoid infinite recursion when the getter is copied to the context.
344
+ // The inner getter throws with `skipNavigation` or when navigation produced no response; it then stays.
345
+ let originalResponse;
346
+ try {
347
+ originalResponse = playwrightContext.response;
268
348
  }
269
- return {
270
- response: new ResponseWithUrl(Uint8Array.from(await originalResponse.body()), {
349
+ catch { }
350
+ let response;
351
+ if (originalResponse) {
352
+ // `headers()` can return repeated headers (e.g. `set-cookie`) joined with `\n`, which `Headers` rejects
353
+ const headers = new Headers();
354
+ for (const { name, value } of await originalResponse.headersArray()) {
355
+ headers.append(name, value);
356
+ }
357
+ // `body()` throws for redirects, `304` cache hits included, and for responses the page navigated away from
358
+ const body = await originalResponse
359
+ .body()
360
+ .catch(async () => Buffer.from(await playwrightContext.page.content()));
361
+ response = new ResponseWithUrl(Uint8Array.from(body), {
271
362
  headers,
272
363
  status: originalResponse.status(),
273
364
  statusText: originalResponse.statusText(),
274
365
  url: originalResponse.url(),
275
- }),
366
+ });
367
+ }
368
+ return {
369
+ ...(response && { response }),
276
370
  enqueueLinks: async (options = {}, timeoutMs = 5000) => {
277
371
  // TODO consider using `context.parseWithCheerio` to make this universal and avoid code duplication
278
372
  const selector = options.selector ?? 'a';
@@ -288,20 +382,15 @@ export class AdaptivePlaywrightCrawler extends BasicCrawler {
288
382
  };
289
383
  }
290
384
  /**
291
- * Runs one request handler attempt inside its own {@link StorageTransaction}, wrapping the inner
292
- * (static or browser) context pipeline. The transaction is pushed to `transactions` *at creation
293
- * time, before the `try`*, as failed attempts are routine here. The caller owns the outcome and
294
- * disposal, including closing or reverting the {@link ContextModifications}.
385
+ * Runs one request handler attempt inside the attempt's {@link StorageTransaction}, wrapping the inner
386
+ * (static or browser) context pipeline. The caller owns the outcome and settles the attempt, including
387
+ * closing or reverting the {@link ContextModifications}.
295
388
  *
296
389
  * `request` defaults to the context's; a detection rerun passes a copy so it sees the request as it
297
390
  * was before the browser attempt.
298
391
  */
299
- async #crawlOne(renderingType, context, useStateFunction, transactions, request = context.request) {
300
- const transaction = createStorageTransaction({
301
- policy: this.#attemptWritePolicy,
302
- commitTimeoutMillis: this.internalTimeoutMillis,
303
- });
304
- transactions.push(transaction);
392
+ async #crawlOne(renderingType, context, useStateFunction, attempt, request = context.request) {
393
+ const { transaction } = attempt;
305
394
  const logs = [];
306
395
  const contextModifications = {
307
396
  request: new MutationJournal(),
@@ -326,32 +415,13 @@ export class AdaptivePlaywrightCrawler extends BasicCrawler {
326
415
  for (const [key, descriptor] of Object.entries(Object.getOwnPropertyDescriptors(attemptBoundContextHelpers))) {
327
416
  Object.defineProperty(subCrawlerContext, key, { ...descriptor, configurable: false });
328
417
  }
329
- // The timeout below does not stop the request handler, and the pipeline closes the page only after the handler
330
- // settles. Racing the handler against this lets a timed-out attempt release its page right away.
331
- const attemptFailed = new AbortController();
332
418
  try {
333
- // Any failure - middleware or handler - ends up in the `ok: false` branch below.
334
- const rethrow = (error) => {
335
- throw error;
336
- };
337
- const abandonableRequestHandler = async (crawlingContext) => {
338
- // The attempt may have failed before the handler starts, and a late abort listener would never fire.
339
- attemptFailed.signal.throwIfAborted();
340
- return Promise.race([
341
- this.requestHandler(crawlingContext),
342
- new Promise((_resolve, reject) => {
343
- attemptFailed.signal.addEventListener('abort', () => reject(attemptFailed.signal.reason), {
344
- once: true,
345
- });
346
- }),
347
- ]);
348
- };
349
419
  const callAdaptiveRequestHandler = async () => {
350
420
  if (renderingType === 'static') {
351
- await this.#staticContextPipeline.call(subCrawlerContext, this.requestHandler.bind(this), rethrow);
421
+ await attempt.run(this.#staticContextPipeline, subCrawlerContext, this.requestHandler.bind(this));
352
422
  }
353
423
  else if (renderingType === 'clientOnly') {
354
- await this.#browserContextPipeline.call(subCrawlerContext, abandonableRequestHandler, rethrow);
424
+ await attempt.run(this.#browserContextPipeline, subCrawlerContext, attempt.abandonable(this.requestHandler.bind(this)));
355
425
  }
356
426
  };
357
427
  // this crawler overrides `runRequestHandler` and times each rendering-type run itself, so it has
@@ -362,7 +432,7 @@ export class AdaptivePlaywrightCrawler extends BasicCrawler {
362
432
  return { ok: true, transaction, contextModifications, logs };
363
433
  }
364
434
  catch (error) {
365
- attemptFailed.abort(error);
435
+ attempt.fail(error);
366
436
  return { ok: false, error, transaction, contextModifications, logs };
367
437
  }
368
438
  }
@@ -372,18 +442,25 @@ export class AdaptivePlaywrightCrawler extends BasicCrawler {
372
442
  if (!shouldDetectRenderingType) {
373
443
  crawlingContext.log.debug(`Predicted rendering type ${renderingTypePrediction.renderingType} for ${crawlingContext.request.url}`);
374
444
  }
375
- // Every transaction created for this request - up to two, since the static-then-browser
376
- // fall-through and the browser-then-detection pair are mutually exclusive. Disposed in the
377
- // `finally` below, not earlier: the comparators read the journals after `crawlOne` returns.
378
- const transactions = [];
445
+ // Settled only in the `finally` below - the comparators read the journals after `crawlOne` returns.
446
+ const attempts = [];
447
+ const startAttempt = () => {
448
+ const attempt = new Attempt(createStorageTransaction({
449
+ policy: this.#attemptWritePolicy,
450
+ commitTimeoutMillis: this.internalTimeoutMillis,
451
+ }));
452
+ attempts.push(attempt);
453
+ return attempt;
454
+ };
379
455
  try {
380
456
  // A result the `resultChecker` rejected is as good as a detection saying the page needs a browser - but
381
457
  // only once the browser run has succeeded. A thrown error says nothing about rendering.
382
- let httpResultRejected = false;
458
+ let resultCheckerRejectedHttpResult = false;
383
459
  if (renderingTypePrediction.renderingType === 'static' && !shouldDetectRenderingType) {
384
460
  crawlingContext.log.debug(`Running HTTP-only request handler for ${crawlingContext.request.url}`);
385
461
  this.statistics.state.httpOnlyRequestHandlerRuns++;
386
- const plainHTTPRun = await this.#crawlOne('static', crawlingContext, crawlingContext.useState, transactions);
462
+ const httpAttempt = startAttempt();
463
+ const plainHTTPRun = await this.#crawlOne('static', crawlingContext, crawlingContext.useState, httpAttempt);
387
464
  if (plainHTTPRun.ok &&
388
465
  this.#resultChecker(plainHTTPRun.transaction, { request: crawlingContext.request })) {
389
466
  crawlingContext.log.debug(`HTTP-only request handler succeeded for ${crawlingContext.request.url}`);
@@ -401,25 +478,29 @@ export class AdaptivePlaywrightCrawler extends BasicCrawler {
401
478
  if (actualError instanceof ContextPipelineInterruptedError ||
402
479
  (await this.#shouldPropagateError(actualError, crawlingContext))) {
403
480
  this.#keepContextModifications(plainHTTPRun.contextModifications);
481
+ httpAttempt.exposeToErrorHandlers(crawlingContext);
404
482
  throw actualError;
405
483
  }
406
484
  crawlingContext.log.exception(actualError, `HTTP-only request handler failed for ${crawlingContext.request.url}`);
485
+ await httpAttempt.release();
407
486
  }
408
487
  else {
409
488
  crawlingContext.log.warning(`HTTP-only request handler returned a suspicious result for ${crawlingContext.request.url}`);
410
489
  this.statistics.state.renderingTypeMispredictions++;
411
- httpResultRejected = true;
490
+ resultCheckerRejectedHttpResult = true;
412
491
  }
413
492
  // The browser attempt starts from the request and state as they were before the rejected one.
414
493
  this.#discardContextModifications(plainHTTPRun.contextModifications, crawlingContext);
415
494
  }
416
495
  crawlingContext.log.debug(`Running browser request handler for ${crawlingContext.request.url}`);
417
496
  this.statistics.state.browserRequestHandlerRuns++;
418
- const browserRun = await this.#crawlOne('clientOnly', crawlingContext, crawlingContext.useState, transactions);
497
+ const browserAttempt = startAttempt();
498
+ const browserRun = await this.#crawlOne('clientOnly', crawlingContext, crawlingContext.useState, browserAttempt);
419
499
  if (!browserRun.ok) {
420
500
  // A failed browser attempt is handed to the retry logic with its writes - `userData` stashed for the
421
501
  // next attempt must survive.
422
502
  this.#keepContextModifications(browserRun.contextModifications);
503
+ browserAttempt.exposeToErrorHandlers(crawlingContext);
423
504
  throw browserRun.error;
424
505
  }
425
506
  try {
@@ -432,7 +513,7 @@ export class AdaptivePlaywrightCrawler extends BasicCrawler {
432
513
  this.#keepContextModifications(browserRun.contextModifications);
433
514
  }
434
515
  // Past the shutdown fence, `teardown()` has already drained - and possibly torn down the predictor.
435
- if (httpResultRejected && !this.#shutDown) {
516
+ if (resultCheckerRejectedHttpResult && !this.#shutDown) {
436
517
  this.#storeRenderingType(crawlingContext.request, 'clientOnly');
437
518
  }
438
519
  if (shouldDetectRenderingType) {
@@ -444,7 +525,7 @@ export class AdaptivePlaywrightCrawler extends BasicCrawler {
444
525
  // away with it.
445
526
  const { request: requestJournal, state: stateJournal } = browserRun.contextModifications;
446
527
  let stateCopy;
447
- const plainHTTPRun = await this.#crawlOne('static', crawlingContext, async (defaultValue) => (stateCopy ??= stateJournal.undoOnto(JSON.parse(JSON.stringify(await crawlingContext.useState(defaultValue))))), transactions, requestJournal.undoOnto(CrawlingRequest.fromSchema(JSON.parse(JSON.stringify(crawlingContext.request)))));
528
+ const plainHTTPRun = await this.#crawlOne('static', crawlingContext, async (defaultValue) => (stateCopy ??= stateJournal.undoOnto(JSON.parse(JSON.stringify(await crawlingContext.useState(defaultValue))))), startAttempt(), requestJournal.undoOnto(CrawlingRequest.fromSchema(JSON.parse(JSON.stringify(crawlingContext.request)))));
448
529
  const detectionResult = (() => {
449
530
  if (!plainHTTPRun.ok) {
450
531
  return 'clientOnly';
@@ -469,11 +550,7 @@ export class AdaptivePlaywrightCrawler extends BasicCrawler {
469
550
  }
470
551
  }
471
552
  finally {
472
- // A still-open transaction here belongs to a discarded attempt - roll it back, then release.
473
- for (const transaction of transactions) {
474
- transaction.rollback();
475
- transaction.dispose();
476
- }
553
+ await Promise.all(attempts.map(async (attempt) => attempt.settle()));
477
554
  }
478
555
  }
479
556
  #keepContextModifications(modifications) {
@@ -164,8 +164,6 @@ export declare class PlaywrightCrawler<ContextExtension = Dictionary<never>, Ext
164
164
  // @ts-ignore optional peer dependency or compatibility with es2022
165
165
  configuration: z.ZodOptional<z.ZodInstanceOf<import("@crawlee/browser").Configuration>>;
166
166
  storageBackend: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
167
- // @ts-ignore optional peer dependency or compatibility with es2022
168
- eventManager: z.ZodOptional<z.ZodInstanceOf<import("@crawlee/browser").EventManager>>;
169
167
  logger: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
170
168
  minConcurrency: z.ZodOptional<z.ZodCustom<number, number>>;
171
169
  maxConcurrency: z.ZodOptional<z.ZodCustom<number, number>>;
@@ -224,8 +222,6 @@ export declare class PlaywrightCrawler<ContextExtension = Dictionary<never>, Ext
224
222
  // @ts-ignore optional peer dependency or compatibility with es2022
225
223
  configuration: z.ZodOptional<z.ZodInstanceOf<import("@crawlee/browser").Configuration>>;
226
224
  storageBackend: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
227
- // @ts-ignore optional peer dependency or compatibility with es2022
228
- eventManager: z.ZodOptional<z.ZodInstanceOf<import("@crawlee/browser").EventManager>>;
229
225
  logger: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
230
226
  minConcurrency: z.ZodOptional<z.ZodCustom<number, number>>;
231
227
  maxConcurrency: z.ZodOptional<z.ZodCustom<number, number>>;
@@ -183,8 +183,7 @@ export class PlaywrightCrawler extends BrowserCrawler {
183
183
  response = context.response;
184
184
  }
185
185
  catch {
186
- // the getter throws before navigation and with `skipNavigation`; a navigation
187
- // without a response replaces it with plain `undefined` instead
186
+ // the getter throws before navigation, with `skipNavigation`, and when navigation produced no response
188
187
  }
189
188
  return handleCloudflareChallenge(context.page, context.request.url, options, response);
190
189
  },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@crawlee/playwright",
3
- "version": "4.0.0-beta.323",
3
+ "version": "4.0.0-beta.325",
4
4
  "description": "The scalable web crawling and scraping library for JavaScript/Node.js. Enables development of data extraction and web automation jobs (not only) with headless Chrome and Puppeteer.",
5
5
  "engines": {
6
6
  "node": ">=22.13.0"
@@ -49,14 +49,14 @@
49
49
  "dependencies": {
50
50
  "@apify/datastructures": "^3.0.1",
51
51
  "@apify/timeout": "^1.1.0",
52
- "@crawlee/basic": "4.0.0-beta.323",
53
- "@crawlee/browser": "4.0.0-beta.323",
54
- "@crawlee/browser-pool": "4.0.0-beta.323",
55
- "@crawlee/cheerio": "4.0.0-beta.323",
56
- "@crawlee/core": "4.0.0-beta.323",
57
- "@crawlee/http-client": "4.0.0-beta.323",
58
- "@crawlee/types": "4.0.0-beta.323",
59
- "@crawlee/utils": "4.0.0-beta.323",
52
+ "@crawlee/basic": "4.0.0-beta.325",
53
+ "@crawlee/browser": "4.0.0-beta.325",
54
+ "@crawlee/browser-pool": "4.0.0-beta.325",
55
+ "@crawlee/cheerio": "4.0.0-beta.325",
56
+ "@crawlee/core": "4.0.0-beta.325",
57
+ "@crawlee/http-client": "4.0.0-beta.325",
58
+ "@crawlee/types": "4.0.0-beta.325",
59
+ "@crawlee/utils": "4.0.0-beta.325",
60
60
  "cheerio": "^1.2.0",
61
61
  "domhandler": "^6.0.1",
62
62
  "jquery": "^3.8.0",
@@ -81,5 +81,5 @@
81
81
  }
82
82
  }
83
83
  },
84
- "gitHead": "f08b3c8d5e61f1dfe7c55308d64db92390c3352c"
84
+ "gitHead": "72ed70d29fe1a4122d4b7384c14ee4828229345f"
85
85
  }