@crawlee/playwright 4.0.0-beta.33 → 4.0.0-beta.331

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 +15 -11
  2. package/index.d.ts +4 -3
  3. package/index.js +2 -2
  4. package/internals/adaptive-playwright-crawler.d.ts +156 -82
  5. package/internals/adaptive-playwright-crawler.js +561 -300
  6. package/internals/enqueue-links/click-elements.d.ts +21 -58
  7. package/internals/enqueue-links/click-elements.js +48 -61
  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 +179 -171
  11. package/internals/playwright-crawler.js +121 -77
  12. package/internals/playwright-launcher.d.ts +30 -22
  13. package/internals/playwright-launcher.js +24 -18
  14. package/internals/utils/playwright-utils.d.ts +66 -54
  15. package/internals/utils/playwright-utils.js +128 -137
  16. package/internals/utils/rendering-type-prediction.d.ts +42 -13
  17. package/internals/utils/rendering-type-prediction.js +83 -50
  18. package/package.json +20 -23
  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
@@ -1,47 +1,111 @@
1
+ import { setTimeout as delay } from 'node:timers/promises';
1
2
  import { isDeepStrictEqual } from 'node:util';
2
- import { BasicCrawler } from '@crawlee/basic';
3
- import { extractUrlsFromPage } from '@crawlee/browser';
3
+ import { BasicCrawler, ContextPipeline, ContextPipelineCleanupError, ContextPipelineInitializationError, ContextPipelineInterruptedError, navigationDeadlineKey, RequestHandlerError, resolveBaseUrlForEnqueueLinksFiltering, Router, Statistics, } from '@crawlee/basic';
4
+ import { CrawlingRequest, extractUrlsFromPage } from '@crawlee/browser';
4
5
  import { CheerioCrawler } from '@crawlee/cheerio';
5
- import { RequestHandlerError, RequestHandlerResult, resolveBaseUrlForEnqueueLinksFiltering, Router, serviceLocator, Statistics, withCheckedStorageAccess, } from '@crawlee/core';
6
- import { extractUrlsFromCheerio } from '@crawlee/utils';
6
+ import { ResponseWithUrl } from '@crawlee/http-client';
7
+ import { createStorageTransaction, EnqueueStrategy, OwnedOrInjected } from '@crawlee/core';
8
+ import { extractUrlsFromCheerio, MutationJournal, parseArgument } from '@crawlee/utils/internal';
9
+ import { z } from 'zod';
7
10
  import { addTimeoutToPromise } from '@apify/timeout';
8
11
  import { PlaywrightCrawler } from './playwright-crawler.js';
9
- import { RenderingTypePredictor } from './utils/rendering-type-prediction.js';
10
- class AdaptivePlaywrightCrawlerStatistics extends Statistics {
11
- state = null; // this needs to be assigned for a valid override, but the initialization is done by a reset() call from the parent constructor
12
- constructor(options = {}) {
13
- super(options);
14
- this.reset();
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(() => { });
15
29
  }
16
- reset() {
17
- super.reset();
18
- this.state.httpOnlyRequestHandlerRuns = 0;
19
- this.state.browserRequestHandlerRuns = 0;
20
- this.state.renderingTypeMispredictions = 0;
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]);
21
40
  }
22
- async _maybeLoadStatistics() {
23
- await super._maybeLoadStatistics();
24
- const savedState = await this.keyValueStore?.getValue(this.persistStateKey);
25
- if (!savedState) {
26
- return;
27
- }
28
- this.state.httpOnlyRequestHandlerRuns = savedState.httpOnlyRequestHandlerRuns;
29
- this.state.browserRequestHandlerRuns = savedState.browserRequestHandlerRuns;
30
- this.state.renderingTypeMispredictions = savedState.renderingTypeMispredictions;
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
+ };
31
54
  }
32
- trackHttpOnlyRequestHandlerRun() {
33
- this.state.httpOnlyRequestHandlerRuns ??= 0;
34
- this.state.httpOnlyRequestHandlerRuns += 1;
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
+ }
35
65
  }
36
- trackBrowserRequestHandlerRun() {
37
- this.state.browserRequestHandlerRuns ??= 0;
38
- this.state.browserRequestHandlerRuns += 1;
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);
39
79
  }
40
- trackRenderingTypeMisprediction() {
41
- this.state.renderingTypeMispredictions ??= 0;
42
- this.state.renderingTypeMispredictions += 1;
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
+ }
43
91
  }
44
92
  }
93
+ const adaptiveStatisticStateSchema = z.object({
94
+ /** How many requests were handled by the HTTP-only request handler. */
95
+ httpOnlyRequestHandlerRuns: z.number().default(0),
96
+ /** How many requests were handled in a browser. */
97
+ browserRequestHandlerRuns: z.number().default(0),
98
+ /** How many times the HTTP-only handler produced a result the `resultChecker` rejected. */
99
+ renderingTypeMispredictions: z.number().default(0),
100
+ });
101
+ /**
102
+ * The {@link AdaptivePlaywrightCrawlerStatisticState} fields as a {@link Statistics} state extension, defaults
103
+ * and all. A {@link Statistics} instance to be injected into an {@link AdaptivePlaywrightCrawler} has to carry
104
+ * them - `deserialize.extend()` your own fields onto this one and pass the result as `stateExtension`.
105
+ */
106
+ export const adaptivePlaywrightCrawlerStatisticState = {
107
+ deserialize: adaptiveStatisticStateSchema,
108
+ };
45
109
  const proxyLogMethods = [
46
110
  'error',
47
111
  'exception',
@@ -60,9 +124,9 @@ const proxyLogMethods = [
60
124
  * ```javascript
61
125
  * const crawler = new AdaptivePlaywrightCrawler({
62
126
  * renderingTypeDetectionRatio: 0.1,
63
- * async requestHandler({ querySelector, pushData, enqueueLinks, request, log }) {
127
+ * async requestHandler({ querySelectorAll, pushData, enqueueLinks, request, log }) {
64
128
  * // This function is called to extract data from a single web page
65
- * const $prices = await querySelector('span.price')
129
+ * const $prices = await querySelectorAll('span.price')
66
130
  *
67
131
  * await pushData({
68
132
  * url: request.url,
@@ -78,41 +142,93 @@ const proxyLogMethods = [
78
142
  * 'http://www.example.com/page-2',
79
143
  * ]);
80
144
  * ```
81
- *
82
- * @experimental
83
145
  */
84
146
  export class AdaptivePlaywrightCrawler extends BasicCrawler {
85
- renderingTypePredictor;
86
- resultChecker;
87
- resultComparator;
88
- preventDirectStorageAccess;
89
- staticContextPipeline;
90
- browserContextPipeline;
91
- individualRequestHandlerTimeoutMillis;
92
- resultObjects = new WeakMap();
93
- inFlightRenderingTypeDetections = 0;
94
- teardownHooks = [];
147
+ #renderingTypePredictor;
148
+ #resultChecker;
149
+ #shouldPropagateError;
150
+ #resultComparator;
151
+ #staticContextPipeline;
152
+ #browserContextPipeline;
153
+ #individualRequestHandlerTimeoutMillis;
154
+ /**
155
+ * The write policy of the per-attempt transactions. Defaults the request queue to `deferred`:
156
+ * a discarded attempt's enqueues must never reach the queue.
157
+ */
158
+ #attemptWritePolicy;
159
+ /** Owns the browser pool this crawler's runs use, so its per-run resources are released with ours. */
160
+ #browserCrawler;
161
+ /** Nothing of its state is per-run, but it owns a session pool that outlives one. */
162
+ #staticCrawler;
163
+ /**
164
+ * In-flight rendering type detections, plus the pending results of an asynchronous `storeResult`.
165
+ */
166
+ #activeDetections = new Set();
167
+ /**
168
+ * Set once `teardown()` starts, so that requests still in the pool stop opening new detections.
169
+ */
170
+ #shutDown = false;
95
171
  constructor(options = {}) {
96
- const { requestHandler, renderingTypeDetectionRatio = 0.1, renderingTypePredictor, resultChecker, resultComparator, statisticsOptions, preventDirectStorageAccess = true, requestHandlerTimeoutSecs = 60, errorHandler, failedRequestHandler, preNavigationHooks, postNavigationHooks, extendContext, contextPipelineBuilder, ...rest } = options;
172
+ const { requestHandler, renderingTypeDetectionRatio = 0.1, renderingTypePredictor, resultChecker, shouldPropagateError, resultComparator, statistics, requestHandlerTimeoutSecs = 60, errorHandler, failedRequestHandler, preNavigationHooks = [], postNavigationHooks = [], extendContext, transactionalStorage, navigationTimeoutSecs, launchContext, headless, browserPool, remoteBrowser, ...rest } = options;
173
+ // The user's value is replaced by `false` in the `super` call below — validate it separately,
174
+ // wrapped in an object so the error still names the field.
175
+ parseArgument({ transactionalStorage }, z.object({ transactionalStorage: BasicCrawler.optionsShape.transactionalStorage }), 'AdaptivePlaywrightCrawlerOptions');
176
+ // The extra fields are only tracked if the injected instance was built with them - the types enforce that,
177
+ // but plain JS callers would otherwise silently increment `undefined` into a sticky `NaN`. Extend
178
+ // `adaptivePlaywrightCrawlerStatisticState` to satisfy this.
179
+ if (statistics !== undefined) {
180
+ parseArgument(statistics.state, z.object({
181
+ httpOnlyRequestHandlerRuns: z.number(),
182
+ browserRequestHandlerRuns: z.number(),
183
+ renderingTypeMispredictions: z.number(),
184
+ }), 'statistics.state');
185
+ }
186
+ // Per-attempt buffering is load-bearing here: the handler runs up to twice per request and the
187
+ // losing attempt's writes must be discardable.
188
+ if (transactionalStorage === false) {
189
+ throw new Error('AdaptivePlaywrightCrawler requires transactional storage - it runs the request handler ' +
190
+ 'multiple times per request and must be able to discard the storage writes of losing ' +
191
+ 'attempts. `transactionalStorage: false` is therefore not supported; a write policy ' +
192
+ 'object is accepted and forwarded to the per-attempt transactions.');
193
+ }
97
194
  super({
98
195
  ...rest,
99
196
  errorHandler,
100
197
  failedRequestHandler,
101
198
  requestHandler,
102
- contextPipelineBuilder: contextPipelineBuilder ?? (() => this.buildContextPipeline()),
199
+ requestHandlerTimeoutSecs,
200
+ // The base would build a `Statistics` without the adaptive fields, so provide a default that has them.
201
+ // The cast covers a `StatisticStateExtension` that adds further fields - those can only come from an
202
+ // injected instance, in which case this default is never built.
203
+ statistics: statistics ??
204
+ new Statistics({
205
+ logMessage: `${AdaptivePlaywrightCrawler.name} request statistics:`,
206
+ stateExtension: adaptivePlaywrightCrawlerStatisticState,
207
+ }),
208
+ contextPipelineBuilder: () => this.#buildContextPipeline(),
209
+ // The base crawler must not wrap requests in a transaction of its own - this crawler opens
210
+ // one per request handler attempt in `crawlOne` instead, forwarding the write policy of the
211
+ // user-facing option (validated above) to those.
212
+ transactionalStorage: false,
103
213
  });
104
- this.individualRequestHandlerTimeoutMillis = requestHandlerTimeoutSecs * 1000;
105
- this.renderingTypePredictor =
106
- renderingTypePredictor ?? new RenderingTypePredictor({ detectionRatio: renderingTypeDetectionRatio });
107
- this.resultChecker = resultChecker ?? (() => true);
214
+ this.#individualRequestHandlerTimeoutMillis = requestHandlerTimeoutSecs * 1000;
215
+ // `renderingTypeDetectionRatio` only configures the default predictor - an injected one brings its own
216
+ // detection ratio (and its own state), so the option is ignored in that case.
217
+ this.#renderingTypePredictor = OwnedOrInjected.resolve(renderingTypePredictor, () => new RenderingTypePredictor({ detectionRatio: renderingTypeDetectionRatio, id: options.id }));
218
+ this.#attemptWritePolicy = {
219
+ requestQueue: 'deferred',
220
+ ...(typeof transactionalStorage === 'object' ? transactionalStorage : {}),
221
+ };
222
+ this.#resultChecker = resultChecker ?? (() => true);
223
+ this.#shouldPropagateError = shouldPropagateError ?? (() => false);
108
224
  if (resultComparator !== undefined) {
109
- this.resultComparator = resultComparator;
225
+ this.#resultComparator = resultComparator;
110
226
  }
111
227
  else if (resultChecker !== undefined) {
112
- this.resultComparator = (resultA, resultB) => this.resultChecker(resultA) && this.resultChecker(resultB);
228
+ this.#resultComparator = (resultA, resultB, context) => this.#resultChecker(resultA, context) && this.#resultChecker(resultB, context);
113
229
  }
114
230
  else {
115
- this.resultComparator = (resultA, resultB) => {
231
+ this.#resultComparator = (resultA, resultB) => {
116
232
  return (resultA.datasetItems.length === resultB.datasetItems.length &&
117
233
  resultA.datasetItems.every((itemA, i) => {
118
234
  const itemB = resultB.datasetItems[i];
@@ -120,340 +236,485 @@ export class AdaptivePlaywrightCrawler extends BasicCrawler {
120
236
  }));
121
237
  };
122
238
  }
239
+ // `extendContext` is forwarded to the inner crawlers, which run it *before* navigation (see
240
+ // `BasicCrawler`), keeping the behavior consistent with the non-adaptive crawlers: the
241
+ // extension is visible to the pre/post-navigation hooks and the request handler, but cannot
242
+ // access navigation-dependent members (`page`, `response`, `$`, ...).
243
+ //
244
+ // The adaptive hooks target a subset context (`AdaptiveHookContext`); the casts to the inner
245
+ // crawlers' `PlaywrightHook` type relax that nominal difference. The `ContextPipeline` merges
246
+ // each hook's overrides at runtime regardless of the static type.
123
247
  const staticCrawler = new CheerioCrawler({
124
248
  ...rest,
125
- useSessionPool: false,
126
- statisticsOptions: {
127
- persistenceOptions: { enable: false },
128
- },
129
- preNavigationHooks: [
130
- async (context) => {
131
- for (const hook of preNavigationHooks ?? []) {
132
- await hook(context, undefined);
133
- }
134
- },
135
- ],
136
- postNavigationHooks: [
137
- async (context) => {
138
- for (const hook of postNavigationHooks ?? []) {
139
- await hook(context, undefined);
140
- }
141
- },
142
- ],
249
+ statistics: new Statistics({ persistenceOptions: { enable: false } }),
250
+ preNavigationHooks,
251
+ postNavigationHooks,
252
+ extendContext,
253
+ navigationTimeoutSecs,
143
254
  });
144
255
  const browserCrawler = new PlaywrightCrawler({
145
256
  ...rest,
146
- useSessionPool: false,
147
- statisticsOptions: {
148
- persistenceOptions: { enable: false },
149
- },
150
- preNavigationHooks: [
151
- async (context, gotoOptions) => {
152
- for (const hook of preNavigationHooks ?? []) {
153
- await hook(context, gotoOptions);
257
+ statistics: new Statistics({ persistenceOptions: { enable: false } }),
258
+ preNavigationHooks: preNavigationHooks,
259
+ postNavigationHooks: postNavigationHooks,
260
+ extendContext,
261
+ navigationTimeoutSecs,
262
+ launchContext,
263
+ headless,
264
+ browserPool,
265
+ remoteBrowser,
266
+ });
267
+ this.#staticCrawler = staticCrawler;
268
+ this.#browserCrawler = browserCrawler;
269
+ // Each attempt needs its own deferred cleanups, and they must share the attempt's cleanup stack: resources the
270
+ // pipeline defers releasing (the page) have to outlive the user's cleanups, which may still use them.
271
+ const deferredCleanup = ContextPipeline.create().compose((_context, onCleanup) => ({
272
+ registerDeferredCleanup: (cleanup) => {
273
+ onCleanup(async () => {
274
+ try {
275
+ await cleanup();
154
276
  }
155
- },
156
- ],
157
- postNavigationHooks: [
158
- async (context, gotoOptions) => {
159
- for (const hook of postNavigationHooks ?? []) {
160
- await hook(context, gotoOptions);
277
+ catch (error) {
278
+ this.log.debug('Error in deferred cleanup', { error });
161
279
  }
162
- },
163
- ],
164
- });
165
- this.teardownHooks.push(browserCrawler.teardown.bind(browserCrawler));
166
- this.staticContextPipeline = staticCrawler.contextPipeline
167
- .compose({
168
- action: this.adaptCheerioContext.bind(this),
169
- })
170
- .compose({
171
- action: async (context) => extendContext ? await extendContext(context) : context,
172
- });
173
- this.browserContextPipeline = browserCrawler.contextPipeline
174
- .compose({
175
- action: this.adaptPlaywrightContext.bind(this),
176
- })
177
- .compose({
178
- action: async (context) => extendContext ? await extendContext(context) : context,
179
- });
180
- this.stats = new AdaptivePlaywrightCrawlerStatistics({
181
- logMessage: `${this.log.getOptions().prefix} request statistics:`,
182
- ...statisticsOptions,
183
- });
184
- this.preventDirectStorageAccess = preventDirectStorageAccess;
280
+ });
281
+ },
282
+ }));
283
+ this.#staticContextPipeline = deferredCleanup
284
+ .chain(staticCrawler.contextPipeline)
285
+ .compose(this.#adaptCheerioContext.bind(this));
286
+ this.#browserContextPipeline = deferredCleanup
287
+ .chain(browserCrawler.contextPipeline)
288
+ .compose(this.#adaptPlaywrightContext.bind(this));
185
289
  }
186
- async _init() {
187
- await this.renderingTypePredictor.initialize();
188
- return await super._init();
290
+ async init() {
291
+ // A crawler can be run again after a teardown.
292
+ this.#shutDown = false;
293
+ // Only the predictor we built ourselves is ours to initialize - an injected one is borrowed, so its
294
+ // lifecycle (including restoring persisted state) stays with whoever created it.
295
+ await this.#renderingTypePredictor.ifOwned((predictor) => predictor.initialize());
296
+ return await super.init();
189
297
  }
190
- buildContextPipeline() {
298
+ #buildContextPipeline() {
191
299
  const errorMessage = (prop) => `The \`${prop}\` property is not available on the outer context pipeline of AdaptivePlaywrightCrawler - it is provided by the inner (static/browser) pipelines`;
192
- return super.buildContextPipeline().compose({
193
- action: async ({ request }) => ({
194
- get request() {
195
- return request;
196
- },
197
- get response() {
198
- throw new Error(errorMessage('response'));
199
- },
200
- get page() {
201
- throw new Error(errorMessage('page'));
202
- },
203
- get querySelector() {
204
- throw new Error(errorMessage('querySelector'));
205
- },
206
- get waitForSelector() {
207
- throw new Error(errorMessage('waitForSelector'));
208
- },
209
- get parseWithCheerio() {
210
- throw new Error(errorMessage('parseWithCheerio'));
211
- },
212
- }),
213
- });
300
+ return ContextPipeline.create().compose(async ({ request }) => ({
301
+ get request() {
302
+ return request;
303
+ },
304
+ get response() {
305
+ throw new Error(errorMessage('response'));
306
+ },
307
+ get page() {
308
+ throw new Error(errorMessage('page'));
309
+ },
310
+ get querySelectorAll() {
311
+ throw new Error(errorMessage('querySelectorAll'));
312
+ },
313
+ get querySelectorOne() {
314
+ throw new Error(errorMessage('querySelectorOne'));
315
+ },
316
+ get waitForSelector() {
317
+ throw new Error(errorMessage('waitForSelector'));
318
+ },
319
+ get parseWithCheerio() {
320
+ throw new Error(errorMessage('parseWithCheerio'));
321
+ },
322
+ get extractLinks() {
323
+ throw new Error(errorMessage('extractLinks'));
324
+ },
325
+ get enqueueLinks() {
326
+ throw new Error(errorMessage('enqueueLinks'));
327
+ },
328
+ }));
214
329
  }
215
- async adaptCheerioContext(cheerioContext) {
216
- // Capture the original response to avoid infinite recursion when the getter is copied to the context
217
- const result = this.resultObjects.get(cheerioContext);
218
- if (result === undefined) {
219
- throw new Error('Logical error - `this.resultObjects` does not contain the result object');
220
- }
330
+ async #adaptCheerioContext(cheerioContext) {
331
+ const extractLinks = async (options = {}) => extractUrlsFromCheerio(cheerioContext.$, options.selector, options.baseUrl ?? cheerioContext.request.loadedUrl);
221
332
  return {
222
333
  get page() {
223
334
  throw new Error('Page object was used in HTTP-only request handler');
224
335
  },
225
- async querySelector(selector) {
226
- return cheerioContext.$(selector);
227
- },
228
- enqueueLinks: async (options = {}) => {
229
- const urls = options.urls ??
230
- extractUrlsFromCheerio(cheerioContext.$, options.selector, options.baseUrl ?? cheerioContext.request.loadedUrl);
231
- return (await this.enqueueLinks({ ...options, urls }, cheerioContext.request, result));
232
- },
233
- response: cheerioContext.response,
336
+ extractLinks,
337
+ enqueueLinks: async (options = {}) => this.#enqueueLinks(await extractLinks(options), options, cheerioContext.request),
338
+ // `skipNavigation` keeps the inner throwing getter. The body is already consumed (and decoded to UTF-8).
339
+ ...(cheerioContext.request.skipNavigation
340
+ ? {}
341
+ : { response: new ResponseWithUrl(cheerioContext.body, cheerioContext.response) }),
234
342
  };
235
343
  }
236
- async adaptPlaywrightContext(playwrightContext) {
237
- const originalResponse = playwrightContext.response;
238
- const result = this.resultObjects.get(playwrightContext);
239
- if (result === undefined) {
240
- throw new Error('Logical error - `this.resultObjects` does not contain the result object');
344
+ async #adaptPlaywrightContext(playwrightContext) {
345
+ // Capture the original response to avoid infinite recursion when the getter is copied to the context.
346
+ // The inner getter throws with `skipNavigation` or when navigation produced no response; it then stays.
347
+ let originalResponse;
348
+ try {
349
+ originalResponse = playwrightContext.response;
241
350
  }
242
- return {
243
- response: new Response(Uint8Array.from(await originalResponse.body()), {
244
- headers: originalResponse.headers(),
351
+ catch { }
352
+ let response;
353
+ if (originalResponse) {
354
+ // `headers()` can return repeated headers (e.g. `set-cookie`) joined with `\n`, which `Headers` rejects
355
+ const headers = new Headers();
356
+ for (const { name, value } of await originalResponse.headersArray()) {
357
+ headers.append(name, value);
358
+ }
359
+ // `body()` throws for redirects, `304` cache hits included, and for responses the page navigated away from
360
+ const body = await originalResponse
361
+ .body()
362
+ .catch(async () => Buffer.from(await playwrightContext.page.content()));
363
+ response = new ResponseWithUrl(Uint8Array.from(body), {
364
+ headers,
245
365
  status: originalResponse.status(),
246
366
  statusText: originalResponse.statusText(),
247
- }),
248
- async querySelector(selector, timeoutMs = 5000) {
249
- const locator = playwrightContext.page.locator(selector).first();
250
- await locator.waitFor({ timeout: timeoutMs, state: 'attached' });
251
- const $ = await playwrightContext.parseWithCheerio();
252
- return $(selector);
253
- },
254
- enqueueLinks: async (options = {}, timeoutMs = 5000) => {
255
- // TODO consider using `context.parseWithCheerio` to make this universal and avoid code duplication
256
- let urls;
257
- if (options.urls === undefined) {
258
- const selector = options.selector ?? 'a';
259
- const locator = playwrightContext.page.locator(selector).first();
260
- await locator.waitFor({ timeout: timeoutMs, state: 'attached' });
261
- urls =
262
- options.urls ??
263
- (await extractUrlsFromPage(playwrightContext.page, selector, options.baseUrl ?? playwrightContext.request.loadedUrl));
264
- }
265
- else {
266
- urls = options.urls;
267
- }
268
- return (await this.enqueueLinks({ ...options, urls }, playwrightContext.request, result));
269
- },
367
+ url: originalResponse.url(),
368
+ });
369
+ }
370
+ const extractLinks = async (options = {}, timeoutMs = 5000) => {
371
+ // TODO consider using `context.parseWithCheerio` to make this universal and avoid code duplication
372
+ const selector = options.selector ?? 'a';
373
+ const locator = playwrightContext.page.locator(selector).first();
374
+ // Wait for client-rendered links, but like the HTTP side, return nothing when there are none.
375
+ await locator.waitFor({ timeout: timeoutMs, state: 'attached' }).catch((error) => {
376
+ if (error.name !== 'TimeoutError')
377
+ throw error;
378
+ });
379
+ return extractUrlsFromPage(playwrightContext.page, selector, options.baseUrl ?? playwrightContext.request.loadedUrl);
380
+ };
381
+ return {
382
+ ...(response && { response }),
383
+ extractLinks,
384
+ enqueueLinks: async (options = {}, timeoutMs = 5000) => this.#enqueueLinks(await extractLinks(options, timeoutMs), options, playwrightContext.request),
270
385
  };
271
386
  }
272
- async crawlOne(renderingType, context, useStateFunction) {
273
- const result = new RequestHandlerResult(serviceLocator.getConfiguration(), AdaptivePlaywrightCrawler.CRAWLEE_STATE_KEY);
387
+ /**
388
+ * Runs one request handler attempt inside the attempt's {@link StorageTransaction}, wrapping the inner
389
+ * (static or browser) context pipeline. The caller owns the outcome and settles the attempt, including
390
+ * closing or reverting the {@link ContextModifications}.
391
+ *
392
+ * `request` defaults to the context's; a detection rerun passes a copy so it sees the request as it
393
+ * was before the browser attempt.
394
+ */
395
+ async #crawlOne(renderingType, context, useStateFunction, attempt, request = context.request) {
396
+ const { transaction } = attempt;
274
397
  const logs = [];
275
- const deferredCleanup = [];
276
- const resultBoundContextHelpers = {
277
- addRequests: result.addRequests,
278
- pushData: result.pushData,
279
- useState: this.allowStorageAccess(useStateFunction),
280
- getKeyValueStore: this.allowStorageAccess(result.getKeyValueStore),
281
- log: this.createLogProxy(context.log, logs),
282
- registerDeferredCleanup: (cleanup) => deferredCleanup.push(cleanup),
398
+ const contextModifications = {
399
+ request: new MutationJournal(),
400
+ state: new MutationJournal(),
283
401
  };
284
402
  const subCrawlerContext = Object.defineProperties({}, Object.getOwnPropertyDescriptors(context));
285
- // Mark result-bound helpers as non-configurable so they survive the sub-crawler context pipeline
286
- // (which would otherwise override them with the sub-crawler's own versions, losing the result binding).
287
- for (const [key, descriptor] of Object.entries(Object.getOwnPropertyDescriptors(resultBoundContextHelpers))) {
403
+ const attemptBoundContextHelpers = {
404
+ request: contextModifications.request.track(request),
405
+ useState: async (defaultValue) => contextModifications.state.track(await useStateFunction(defaultValue)),
406
+ log: this.#createLogProxy(context.log, logs),
407
+ // The sub-crawler pipeline keeps this attempt's navigation deadline on `subCrawlerContext`, but the
408
+ // outer `extendTimeout` only pushes the deadline it finds on `context`, so push this one as well.
409
+ extendTimeout: (secs) => {
410
+ context.extendTimeout(secs);
411
+ if (subCrawlerContext[navigationDeadlineKey] !== undefined) {
412
+ subCrawlerContext[navigationDeadlineKey] += secs * 1000;
413
+ }
414
+ },
415
+ };
416
+ // Mark attempt-bound helpers as non-configurable so they survive the sub-crawler context pipeline
417
+ // (which would otherwise override them with the sub-crawler's own versions, losing the binding).
418
+ for (const [key, descriptor] of Object.entries(Object.getOwnPropertyDescriptors(attemptBoundContextHelpers))) {
288
419
  Object.defineProperty(subCrawlerContext, key, { ...descriptor, configurable: false });
289
420
  }
290
- this.resultObjects.set(subCrawlerContext, result);
291
421
  try {
292
422
  const callAdaptiveRequestHandler = async () => {
293
423
  if (renderingType === 'static') {
294
- await this.staticContextPipeline.call(subCrawlerContext, this.requestHandler.bind(this));
424
+ await attempt.run(this.#staticContextPipeline, subCrawlerContext, this.requestHandler.bind(this));
295
425
  }
296
426
  else if (renderingType === 'clientOnly') {
297
- await this.browserContextPipeline.call(subCrawlerContext, this.requestHandler.bind(this));
427
+ await attempt.run(this.#browserContextPipeline, subCrawlerContext, attempt.abandonable(this.requestHandler.bind(this)));
298
428
  }
299
429
  };
300
- await addTimeoutToPromise(async () => withCheckedStorageAccess(() => {
301
- if (this.preventDirectStorageAccess) {
302
- throw new Error('Directly accessing storage in a request handler is not allowed in AdaptivePlaywrightCrawler');
303
- }
304
- }, callAdaptiveRequestHandler), this.individualRequestHandlerTimeoutMillis, 'Request handler timed out');
305
- return { result, ok: true, logs };
430
+ // this crawler overrides `runRequestHandler` and times each rendering-type run itself, so it has
431
+ // to resolve any per-route override too - otherwise routes would be silently ignored here
432
+ const routeTimeoutSecs = this.requestHandler.getTimeoutSecs?.(context.request.label);
433
+ const timeoutMillis = routeTimeoutSecs === undefined ? this.#individualRequestHandlerTimeoutMillis : routeTimeoutSecs * 1000;
434
+ await addTimeoutToPromise(async () => transaction.run(callAdaptiveRequestHandler), timeoutMillis, 'Request handler timed out');
435
+ return { ok: true, transaction, contextModifications, logs };
306
436
  }
307
437
  catch (error) {
308
- return { error, ok: false, logs };
309
- }
310
- finally {
311
- await Promise.all(deferredCleanup.map((cleanup) => cleanup()));
438
+ attempt.fail(error);
439
+ return { ok: false, error, transaction, contextModifications, logs };
312
440
  }
313
441
  }
314
442
  async runRequestHandler(crawlingContext) {
315
- const renderingTypePrediction = this.renderingTypePredictor.predict(crawlingContext.request);
316
- const shouldDetectRenderingType = Math.random() < renderingTypePrediction.detectionProbabilityRecommendation;
443
+ const renderingTypePrediction = await this.#renderingTypePredictor.value.predict(crawlingContext.request);
444
+ const shouldDetectRenderingType = !this.#shutDown && Math.random() < renderingTypePrediction.detectionProbabilityRecommendation;
317
445
  if (!shouldDetectRenderingType) {
318
446
  crawlingContext.log.debug(`Predicted rendering type ${renderingTypePrediction.renderingType} for ${crawlingContext.request.url}`);
319
447
  }
320
- if (shouldDetectRenderingType) {
321
- this.inFlightRenderingTypeDetections += 1;
322
- }
448
+ // Settled only in the `finally` below - the comparators read the journals after `crawlOne` returns.
449
+ const attempts = [];
450
+ const startAttempt = () => {
451
+ const attempt = new Attempt(createStorageTransaction({
452
+ policy: this.#attemptWritePolicy,
453
+ commitTimeoutMillis: this.internalTimeoutMillis,
454
+ }));
455
+ attempts.push(attempt);
456
+ return attempt;
457
+ };
323
458
  try {
459
+ // A result the `resultChecker` rejected is as good as a detection saying the page needs a browser - but
460
+ // only once the browser run has succeeded. A thrown error says nothing about rendering.
461
+ let resultCheckerRejectedHttpResult = false;
324
462
  if (renderingTypePrediction.renderingType === 'static' && !shouldDetectRenderingType) {
325
463
  crawlingContext.log.debug(`Running HTTP-only request handler for ${crawlingContext.request.url}`);
326
- this.stats.trackHttpOnlyRequestHandlerRun();
327
- const plainHTTPRun = await this.crawlOne('static', crawlingContext, crawlingContext.useState);
328
- if (plainHTTPRun.ok && this.resultChecker(plainHTTPRun.result)) {
464
+ this.statistics.state.httpOnlyRequestHandlerRuns++;
465
+ const httpAttempt = startAttempt();
466
+ const plainHTTPRun = await this.#crawlOne('static', crawlingContext, crawlingContext.useState, httpAttempt);
467
+ if (plainHTTPRun.ok &&
468
+ this.#resultChecker(plainHTTPRun.transaction, { request: crawlingContext.request })) {
329
469
  crawlingContext.log.debug(`HTTP-only request handler succeeded for ${crawlingContext.request.url}`);
330
- plainHTTPRun.logs?.forEach(([log, method, ...args]) => log[method](...args));
331
- await this.commitResult(crawlingContext, plainHTTPRun.result);
470
+ plainHTTPRun.logs.forEach(([log, method, ...args]) => log[method](...args));
471
+ this.#keepContextModifications(plainHTTPRun.contextModifications);
472
+ await plainHTTPRun.transaction.commit();
332
473
  return;
333
474
  }
334
475
  // Execution will "fall through" and try running the request handler in a browser
335
476
  if (!plainHTTPRun.ok) {
336
- const actualError = plainHTTPRun.error instanceof RequestHandlerError
477
+ const actualError = plainHTTPRun.error instanceof RequestHandlerError ||
478
+ plainHTTPRun.error instanceof ContextPipelineInitializationError
337
479
  ? plainHTTPRun.error.cause
338
480
  : plainHTTPRun.error;
481
+ if (actualError instanceof ContextPipelineInterruptedError ||
482
+ (await this.#shouldPropagateError(actualError, crawlingContext))) {
483
+ this.#keepContextModifications(plainHTTPRun.contextModifications);
484
+ httpAttempt.exposeToErrorHandlers(crawlingContext);
485
+ throw actualError;
486
+ }
339
487
  crawlingContext.log.exception(actualError, `HTTP-only request handler failed for ${crawlingContext.request.url}`);
488
+ await httpAttempt.release();
340
489
  }
341
490
  else {
342
491
  crawlingContext.log.warning(`HTTP-only request handler returned a suspicious result for ${crawlingContext.request.url}`);
343
- this.stats.trackRenderingTypeMisprediction();
492
+ this.statistics.state.renderingTypeMispredictions++;
493
+ resultCheckerRejectedHttpResult = true;
344
494
  }
495
+ // The browser attempt starts from the request and state as they were before the rejected one.
496
+ this.#discardContextModifications(plainHTTPRun.contextModifications, crawlingContext);
345
497
  }
346
498
  crawlingContext.log.debug(`Running browser request handler for ${crawlingContext.request.url}`);
347
- this.stats.trackBrowserRequestHandlerRun();
348
- // Run the request handler in a browser. The copy of the crawler state is kept so that we can perform
349
- // a rendering type detection if necessary. Without this measure, the HTTP request handler would run
350
- // under different conditions, which could change its behavior. Changes done to the crawler state by
351
- // the HTTP request handler will not be committed to the actual storage.
352
- const stateTracker = {
353
- stateCopy: null,
354
- async getLiveState(defaultValue = {}) {
355
- const state = await crawlingContext.useState(defaultValue);
356
- if (this.stateCopy === null) {
357
- this.stateCopy = JSON.parse(JSON.stringify(state));
358
- }
359
- return state;
360
- },
361
- async getStateCopy(defaultValue = {}) {
362
- if (this.stateCopy === null) {
363
- return defaultValue;
364
- }
365
- return this.stateCopy;
366
- },
367
- };
368
- const browserRun = await this.crawlOne('clientOnly', crawlingContext, stateTracker.getLiveState.bind(stateTracker));
499
+ this.statistics.state.browserRequestHandlerRuns++;
500
+ const browserAttempt = startAttempt();
501
+ const browserRun = await this.#crawlOne('clientOnly', crawlingContext, crawlingContext.useState, browserAttempt);
369
502
  if (!browserRun.ok) {
503
+ // A failed browser attempt is handed to the retry logic with its writes - `userData` stashed for the
504
+ // next attempt must survive.
505
+ this.#keepContextModifications(browserRun.contextModifications);
506
+ browserAttempt.exposeToErrorHandlers(crawlingContext);
370
507
  throw browserRun.error;
371
508
  }
372
- await this.commitResult(crawlingContext, browserRun.result);
509
+ try {
510
+ browserRun.logs.forEach(([log, method, ...args]) => log[method](...args));
511
+ // The `afterStorageCommit` callbacks belong to this attempt, so the detection rerun undoes their
512
+ // writes too - the journals stay open until they have run.
513
+ await browserRun.transaction.commit();
514
+ }
515
+ finally {
516
+ this.#keepContextModifications(browserRun.contextModifications);
517
+ }
518
+ // Past the shutdown fence, `teardown()` has already drained - and possibly torn down the predictor.
519
+ if (resultCheckerRejectedHttpResult && !this.#shutDown) {
520
+ this.#storeRenderingType(crawlingContext.request, 'clientOnly');
521
+ }
373
522
  if (shouldDetectRenderingType) {
374
- crawlingContext.log.debug(`Detecting rendering type for ${crawlingContext.request.url}`);
375
- const plainHTTPRun = await this.crawlOne('static', crawlingContext, stateTracker.getStateCopy.bind(stateTracker));
376
- const detectionResult = (() => {
377
- if (!plainHTTPRun.ok) {
378
- return 'clientOnly';
379
- }
380
- const comparisonResult = this.resultComparator(plainHTTPRun.result, browserRun.result);
381
- if (comparisonResult === true || comparisonResult === 'equal') {
382
- return 'static';
523
+ const detectionPromise = (async () => {
524
+ crawlingContext.log.debug(`Detecting rendering type for ${crawlingContext.request.url}`);
525
+ // The detection attempt's transaction is never committed - its writes exist only for the
526
+ // result comparison. It runs on copies of the request and the crawler state with the browser
527
+ // attempt's writes undone, so both attempts start from the same conditions, and the copies go
528
+ // away with it.
529
+ const { request: requestJournal, state: stateJournal } = browserRun.contextModifications;
530
+ let stateCopy;
531
+ 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)))));
532
+ const detectionResult = (() => {
533
+ if (!plainHTTPRun.ok) {
534
+ return 'clientOnly';
535
+ }
536
+ const comparisonResult = this.#resultComparator(plainHTTPRun.transaction, browserRun.transaction, {
537
+ request: crawlingContext.request,
538
+ });
539
+ if (comparisonResult === true || comparisonResult === 'equal') {
540
+ return 'static';
541
+ }
542
+ if (comparisonResult === false || comparisonResult === 'different') {
543
+ return 'clientOnly';
544
+ }
545
+ return undefined;
546
+ })();
547
+ crawlingContext.log.debug(`Detected rendering type ${detectionResult} for ${crawlingContext.request.url}`);
548
+ if (detectionResult !== undefined) {
549
+ this.#storeRenderingType(crawlingContext.request, detectionResult);
383
550
  }
384
- if (comparisonResult === false || comparisonResult === 'different') {
385
- return 'clientOnly';
386
- }
387
- return undefined;
388
551
  })();
389
- crawlingContext.log.debug(`Detected rendering type ${detectionResult} for ${crawlingContext.request.url}`);
390
- if (detectionResult !== undefined) {
391
- this.renderingTypePredictor.storeResult(crawlingContext.request, detectionResult);
392
- }
552
+ await this.#trackDetection(detectionPromise);
393
553
  }
394
554
  }
395
555
  finally {
396
- if (shouldDetectRenderingType) {
397
- this.inFlightRenderingTypeDetections -= 1;
398
- }
556
+ await Promise.all(attempts.map(async (attempt) => attempt.settle()));
399
557
  }
400
558
  }
401
- async commitResult(crawlingContext, { calls, keyValueStoreChanges }) {
402
- await Promise.all([
403
- ...calls.pushData.map(async (params) => crawlingContext.pushData(...params)),
404
- ...calls.addRequests.map(async (params) => crawlingContext.addRequests(...params)),
405
- ...Object.entries(keyValueStoreChanges).map(async ([storeIdOrName, changes]) => {
406
- const store = await crawlingContext.getKeyValueStore(storeIdOrName);
407
- await Promise.all(Object.entries(changes).map(async ([key, { changedValue, options }]) => store.setValue(key, changedValue, options)));
408
- }),
409
- ]);
559
+ #keepContextModifications(modifications) {
560
+ modifications.request.close();
561
+ modifications.state.close();
410
562
  }
411
- allowStorageAccess(func) {
412
- return async (...args) => withCheckedStorageAccess(() => { }, async () => func(...args));
563
+ #discardContextModifications(modifications, { request, log }) {
564
+ // Nothing else writes to a request while its handler runs, so a conflict means a write that bypassed
565
+ // the context (e.g. through a stashed reference) - it stays, but it is not what the retry logic expects.
566
+ modifications.request.revert({
567
+ onConflict: (key) => log.warning(`Request ${request.url}: '${String(key)}' was modified outside the request handler`),
568
+ });
569
+ // The state is shared with concurrent handlers; a conflict is one of them having written the same
570
+ // property meanwhile. Their value wins, and this attempt's write stays with it.
571
+ modifications.state.revert({
572
+ onConflict: (key) => log.debug(`Crawler state '${String(key)}' was changed concurrently; keeping the newer value`),
573
+ });
413
574
  }
414
- async enqueueLinks(options, request, result) {
575
+ #storeRenderingType(request, renderingType) {
576
+ // Deliberately not awaited: a predictor that persists asynchronously gets to keep batching its writes,
577
+ // and `drainRenderingDetections()` catches whatever is still pending.
578
+ const stored = this.#renderingTypePredictor.value.storeResult(request, renderingType);
579
+ if (stored !== undefined) {
580
+ // Nothing downstream awaits this, so a failed write would otherwise be silent.
581
+ void this.#trackDetection(Promise.resolve(stored).catch((error) => this.log.exception(error, `Failed to store the rendering type detection result for ${request.url}`)));
582
+ }
583
+ }
584
+ async #enqueueLinks(urls, options, request) {
415
585
  const baseUrl = resolveBaseUrlForEnqueueLinksFiltering({
416
586
  enqueueStrategy: options?.strategy,
417
587
  finalRequestUrl: request.loadedUrl,
418
588
  originalRequestUrl: request.url,
419
589
  userProvidedBaseUrl: options?.baseUrl,
420
590
  });
421
- const addRequestsBatched = async (requests) => {
422
- await result.addRequests(requests);
423
- return {
424
- addedRequests: requests.map(({ uniqueKey, id }) => ({
425
- uniqueKey,
426
- requestId: id ?? '',
427
- wasAlreadyPresent: false,
428
- wasAlreadyHandled: false,
429
- })),
430
- waitForAllRequestsToBeAdded: Promise.resolve([]),
431
- };
432
- };
433
- // We need to use a mock request queue implementation, in order to add the requests into our result object
434
- const mockRequestQueue = { addRequestsBatched };
435
- return await this.enqueueLinksWithCrawlDepth({ ...options, baseUrl }, request, mockRequestQueue);
591
+ const requestsWithDepth = this.addCrawlDepthRequestGenerator(urls, request.crawlDepth + 1);
592
+ // The per-attempt transaction buffers these (the queue policy defaults to `deferred` here),
593
+ // so a discarded attempt's enqueues never reach the queue.
594
+ return await this.addRequests(requestsWithDepth, {
595
+ ...options,
596
+ baseUrl,
597
+ strategy: options.strategy ?? EnqueueStrategy.SameHostname,
598
+ });
436
599
  }
437
- createLogProxy(log, logs) {
600
+ #createLogProxy(log, logs) {
438
601
  return new Proxy(log, {
439
- get(target, propertyName, receiver) {
602
+ get(target, propertyName) {
440
603
  if (proxyLogMethods.includes(propertyName)) {
441
604
  return (...args) => {
442
605
  logs.push([target, propertyName, ...args]);
443
606
  };
444
607
  }
445
- return Reflect.get(target, propertyName, receiver);
608
+ const value = Reflect.get(target, propertyName, target);
609
+ // Bind non-intercepted methods to the target instance so private #-fields
610
+ // (e.g. BaseCrawleeLogger.#options, #warningsLogged) do not throw TypeError at runtime.
611
+ if (typeof value === 'function') {
612
+ return value.bind(target);
613
+ }
614
+ return value;
446
615
  },
447
616
  });
448
617
  }
618
+ #trackDetection(promise) {
619
+ this.#activeDetections.add(promise);
620
+ // Not `finally()`: the promise it derives would reject on its own and go unhandled. A rejection here
621
+ // belongs to whoever awaits the original, or to `allSettled` in the drain.
622
+ void promise.catch(() => { }).then(() => this.#activeDetections.delete(promise));
623
+ return promise;
624
+ }
625
+ /**
626
+ * Number of rendering type detections that have not settled yet, including results the predictor is
627
+ * still persisting.
628
+ */
629
+ get inFlightRenderingTypeDetectionCount() {
630
+ return this.#activeDetections.size;
631
+ }
632
+ /**
633
+ * Waits for in-flight rendering type detections to settle, bounded by `timeoutMillis` (defaults to the
634
+ * internal timeout).
635
+ */
636
+ async drainRenderingDetections({ timeoutMillis } = {}) {
637
+ if (this.#activeDetections.size === 0) {
638
+ return;
639
+ }
640
+ const drained = (async () => {
641
+ while (this.#activeDetections.size > 0) {
642
+ await Promise.allSettled(Array.from(this.#activeDetections));
643
+ }
644
+ })();
645
+ const millis = timeoutMillis ?? this.internalTimeoutMillis;
646
+ // A caller opting out of the bound would otherwise get an immediate spurious timeout - `setTimeout`
647
+ // clamps a non-finite delay to 1ms.
648
+ if (!Number.isFinite(millis)) {
649
+ await drained;
650
+ return;
651
+ }
652
+ const abortTimer = new AbortController();
653
+ try {
654
+ const outcome = await Promise.race([
655
+ drained.then(() => 'drained'),
656
+ delay(millis, 'timedOut', { signal: abortTimer.signal }).catch(() => 'aborted'),
657
+ ]);
658
+ if (outcome === 'timedOut') {
659
+ this.log.warning(`Timed out after ${millis / 1e3} seconds waiting for ${this.#activeDetections.size} rendering type detection(s) to settle - their results may be lost.`);
660
+ }
661
+ }
662
+ finally {
663
+ abortTimer.abort();
664
+ }
665
+ }
666
+ /**
667
+ * Stops the crawler immediately, but not before rendering type detections already under way (and results
668
+ * the predictor is still persisting) have settled - see
669
+ * {@link AdaptivePlaywrightCrawler.drainRenderingDetections|`drainRenderingDetections()`}. Requests
670
+ * that are still running are not waited for, unlike {@link BasicCrawler.stop|`stop()`}.
671
+ */
449
672
  async teardown() {
673
+ // Called from outside `run()` - under `keepAlive`, say - the pool keeps dispatching until
674
+ // `super.teardown()` aborts it, and a request starting during the drain would open a detection the
675
+ // drain has already passed. Closing that first makes the drain a fence.
676
+ this.#shutDown = true;
677
+ await this.drainRenderingDetections();
450
678
  await super.teardown();
451
- for (const hook of this.teardownHooks) {
452
- await hook();
453
- }
679
+ // Mirrors the owned-only `initialize()` in `init()` - without this, the predictor we built keeps its
680
+ // PERSIST_STATE listener registered after the crawl and never gets a final write.
681
+ await this.#renderingTypePredictor.ifOwned((predictor) => predictor.teardown());
682
+ await this.#browserCrawler.teardown();
454
683
  }
684
+ async destroy() {
685
+ await super.destroy();
686
+ await this.#staticCrawler.destroy();
687
+ await this.#browserCrawler.destroy();
688
+ }
689
+ }
690
+ export function createAdaptivePlaywrightRouter(routesOrSchemas) {
691
+ return Router.create(routesOrSchemas);
455
692
  }
456
- export function createAdaptivePlaywrightRouter(routes) {
457
- return Router.create(routes);
693
+ /**
694
+ * An opt-in {@link AdaptivePlaywrightCrawlerOptions.resultComparator|`resultComparator`} that considers two
695
+ * request handler results equal only if *all* of their observable effects match - the pushed dataset items, the
696
+ * enqueued requests, and the key-value store changes. This is stricter than the default comparator, which only
697
+ * compares dataset items.
698
+ *
699
+ * **Beware:** enqueued URLs are compared exactly. The same page rendered in a browser and via plain HTTP often
700
+ * yields links that differ only in tracking query parameters, for example:
701
+ * - `https://sdk.apify.com/docs/guides/getting-started`
702
+ * - `https://sdk.apify.com/docs/guides/getting-started?__hsfp=1136113150&__hssc=7591405.1.173549427712`
703
+ *
704
+ * Such links are treated as *different*, which will make the crawler favor browser rendering for those pages.
705
+ *
706
+ * **Example usage:**
707
+ * ```ts
708
+ * const crawler = new AdaptivePlaywrightCrawler({
709
+ * resultComparator: fullResultComparator,
710
+ * async requestHandler({ pushData, enqueueLinks }) {
711
+ * // ...
712
+ * },
713
+ * });
714
+ * ```
715
+ */
716
+ export function fullResultComparator(resultA, resultB) {
717
+ return (isDeepStrictEqual(resultA.datasetItems, resultB.datasetItems) &&
718
+ isDeepStrictEqual(resultA.enqueuedUrls, resultB.enqueuedUrls) &&
719
+ isDeepStrictEqual(resultA.keyValueStoreChanges, resultB.keyValueStoreChanges));
458
720
  }
459
- //# sourceMappingURL=adaptive-playwright-crawler.js.map