@crawlee/basic 4.0.0-beta.8 → 4.0.0-beta.81

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,38 +1,21 @@
1
- import type { AddRequestsBatchedOptions, AddRequestsBatchedResult, AutoscaledPoolOptions, BaseHttpClient, CrawlingContext, DatasetExportOptions, EnqueueLinksOptions, EventManager, FinalStatistics, GetUserDataFromRequest, IRequestList, LoadedContext, ProxyInfo, Request, RequestOptions, RestrictedCrawlingContext, RouterHandler, RouterRoutes, Session, SessionPoolOptions, SkippedRequestCallback, Source, StatisticsOptions, StatisticState } from '@crawlee/core';
2
- import { AutoscaledPool, Configuration, Dataset, RequestProvider, SessionPool, Statistics } from '@crawlee/core';
3
- import type { Awaitable, BatchAddRequestsResult, Dictionary, SetStatusMessageOptions } from '@crawlee/types';
1
+ import type { AddRequestsBatchedOptions, AddRequestsBatchedResult, AutoscaledPoolOptions, Configuration, CrawleeLogger, CrawlingContext, DatasetExportOptions, EnqueueLinksOptions, EventManager, FinalStatistics, GetUserDataFromRequest, IProxyConfiguration, IRequestLoader, IRequestManager, Request, RequestsLike, RouterHandler, RouterRoutes, SkippedRequestCallback, Source, StatisticsOptions, StatisticState, StorageIdentifier } from '@crawlee/core';
2
+ import { AutoscaledPool, ContextPipeline, Dataset, RequestQueue, Statistics } from '@crawlee/core';
3
+ import type { Awaitable, BaseHttpClient, BatchAddRequestsResult, Dictionary, ISession, ISessionPool, ProxyInfo, SetStatusMessageOptions, StorageBackend } from '@crawlee/types';
4
4
  import { RobotsTxtFile } from '@crawlee/utils';
5
- import type { SetRequired } from 'type-fest';
6
- import type { Log } from '@apify/log';
5
+ import type { ReadonlyDeep, SetRequired } from 'type-fest';
7
6
  import { TimeoutError } from '@apify/timeout';
8
- export interface BasicCrawlingContext<UserData extends Dictionary = Dictionary> extends CrawlingContext<BasicCrawler, UserData> {
9
- /**
10
- * This function automatically finds and enqueues links from the current page, adding them to the {@link RequestQueue}
11
- * currently used by the crawler.
12
- *
13
- * Optionally, the function allows you to filter the target links' URLs using an array of globs or regular expressions
14
- * and override settings of the enqueued {@link Request} objects.
15
- *
16
- * Check out the [Crawl a website with relative links](https://crawlee.dev/js/docs/examples/crawl-relative-links) example
17
- * for more details regarding its usage.
18
- *
19
- * **Example usage**
20
- *
21
- * ```ts
22
- * async requestHandler({ enqueueLinks }) {
23
- * await enqueueLinks({
24
- * urls: [...],
25
- * });
26
- * },
27
- * ```
28
- *
29
- * @param [options] All `enqueueLinks()` parameters are passed via an options object.
30
- * @returns Promise that resolves to {@link BatchAddRequestsResult} object.
31
- */
32
- enqueueLinks(options?: SetRequired<EnqueueLinksOptions, 'urls'>): Promise<BatchAddRequestsResult>;
7
+ export interface BasicCrawlingContext<UserData extends Dictionary = Dictionary> extends CrawlingContext<UserData> {
33
8
  }
34
- export type RequestHandler<Context extends CrawlingContext = LoadedContext<BasicCrawlingContext & RestrictedCrawlingContext>> = (inputs: LoadedContext<Context>) => Awaitable<void>;
35
- export type ErrorHandler<Context extends CrawlingContext = LoadedContext<BasicCrawlingContext & RestrictedCrawlingContext>> = (inputs: LoadedContext<Context>, error: Error) => Awaitable<void>;
9
+ export type RequestHandler<Context extends CrawlingContext = CrawlingContext> = (inputs: Context) => Awaitable<void>;
10
+ /**
11
+ * An error handler receives the crawling context and the error that was thrown while processing the request.
12
+ *
13
+ * Unlike the {@link RequestHandler}, an error handler may run before the context pipeline has finished
14
+ * building the full context (e.g. when navigation or session setup fails). Therefore only `BaseContext` is
15
+ * guaranteed to be present, while the extra properties added by the pipeline and `extendContext` (the
16
+ * difference between `BaseContext` and `ExtendedContext`) are only available as a `Partial`.
17
+ */
18
+ export type ErrorHandler<BaseContext extends CrawlingContext = CrawlingContext, ExtendedContext extends BaseContext = BaseContext> = (inputs: BaseContext & Partial<ExtendedContext>, error: Error) => Awaitable<void>;
36
19
  export interface StatusMessageCallbackParams<Context extends CrawlingContext = BasicCrawlingContext, Crawler extends BasicCrawler<any> = BasicCrawler<Context>> {
37
20
  state: StatisticState;
38
21
  crawler: Crawler;
@@ -40,7 +23,10 @@ export interface StatusMessageCallbackParams<Context extends CrawlingContext = B
40
23
  message: string;
41
24
  }
42
25
  export type StatusMessageCallback<Context extends CrawlingContext = BasicCrawlingContext, Crawler extends BasicCrawler<any> = BasicCrawler<Context>> = (params: StatusMessageCallbackParams<Context, Crawler>) => Awaitable<void>;
43
- export interface BasicCrawlerOptions<Context extends CrawlingContext = BasicCrawlingContext> {
26
+ export type RequireContextPipeline<DefaultContextType extends CrawlingContext, FinalContextType extends DefaultContextType> = DefaultContextType extends FinalContextType ? {} : {
27
+ contextPipelineBuilder: () => ContextPipeline<CrawlingContext, FinalContextType>;
28
+ };
29
+ export interface BasicCrawlerOptions<Context extends CrawlingContext = CrawlingContext, ContextExtension = Dictionary<never>, ExtendedContext extends Context = Context & ContextExtension> {
44
30
  /**
45
31
  * User-provided function that performs the logic of the crawler. It is called for each URL to crawl.
46
32
  *
@@ -58,21 +44,58 @@ export interface BasicCrawlerOptions<Context extends CrawlingContext = BasicCraw
58
44
  * The exceptions are logged to the request using the
59
45
  * {@link Request.pushErrorMessage|`Request.pushErrorMessage()`} function.
60
46
  */
61
- requestHandler?: RequestHandler<Context>;
47
+ requestHandler?: RequestHandler<ExtendedContext>;
48
+ /**
49
+ * Allows the user to extend the crawling context passed to the request handler with custom functionality.
50
+ *
51
+ * **Example usage:**
52
+ *
53
+ * ```javascript
54
+ * import { BasicCrawler } from 'crawlee';
55
+ *
56
+ * // Create a crawler instance
57
+ * const crawler = new BasicCrawler({
58
+ * extendContext(context) => ({
59
+ * async customHelper() {
60
+ * await context.pushData({ url: context.request.url })
61
+ * }
62
+ * }),
63
+ * async requestHandler(context) {
64
+ * await context.customHelper();
65
+ * },
66
+ * });
67
+ * ```
68
+ */
69
+ extendContext?: (context: Context) => Awaitable<ContextExtension>;
70
+ /**
71
+ * *Intended for BasicCrawler subclasses*. Prepares a context pipeline that transforms the initial crawling context into the shape given by the `Context` type parameter.
72
+ *
73
+ * The option is not required if your crawler subclass does not extend the crawling context with custom information or helpers.
74
+ */
75
+ contextPipelineBuilder?: () => ContextPipeline<CrawlingContext, Context>;
62
76
  /**
63
77
  * Static list of URLs to be processed.
64
- * If not provided, the crawler will open the default request queue when the {@link BasicCrawler.addRequests|`crawler.addRequests()`} function is called.
65
- * > Alternatively, `requests` parameter of {@link BasicCrawler.run|`crawler.run()`} could be used to enqueue the initial requests -
66
- * it is a shortcut for running `crawler.addRequests()` before the `crawler.run()`.
78
+ *
79
+ * @deprecated Use the `requestManager` option instead. To combine a read-only loader (such as a `RequestList`)
80
+ * with a writable queue, build a tandem with {@link IRequestLoader.toTandem|`requestList.toTandem(requestQueue)`}
81
+ * and pass the result as `requestManager`. When both `requestList` and `requestQueue` are provided, they are
82
+ * combined into a tandem automatically.
67
83
  */
68
- requestList?: IRequestList;
84
+ requestList?: IRequestLoader;
69
85
  /**
70
86
  * Dynamic queue of URLs to be processed. This is useful for recursive crawling of websites.
71
- * If not provided, the crawler will open the default request queue when the {@link BasicCrawler.addRequests|`crawler.addRequests()`} function is called.
72
- * > Alternatively, `requests` parameter of {@link BasicCrawler.run|`crawler.run()`} could be used to enqueue the initial requests -
73
- * it is a shortcut for running `crawler.addRequests()` before the `crawler.run()`.
87
+ *
88
+ * @deprecated Use the `requestManager` option instead. A `RequestQueue` is itself a request manager, so you can
89
+ * pass it directly as `requestManager`.
74
90
  */
75
- requestQueue?: RequestProvider;
91
+ requestQueue?: RequestQueue;
92
+ /**
93
+ * Manager of requests that should be processed by the crawler. Mutually exclusive with the deprecated
94
+ * `requestQueue` and `requestList` options.
95
+ *
96
+ * If not provided, the crawler will open the default {@link RequestQueue} when it is first needed.
97
+ */
98
+ requestManager?: IRequestManager;
76
99
  /**
77
100
  * Timeout in which the function passed as {@link BasicCrawlerOptions.requestHandler|`requestHandler`} needs to finish, in seconds.
78
101
  * @default 60
@@ -87,7 +110,7 @@ export interface BasicCrawlerOptions<Context extends CrawlingContext = BasicCraw
87
110
  * Second argument is the `Error` instance that
88
111
  * represents the last error thrown during processing of the request.
89
112
  */
90
- errorHandler?: ErrorHandler<Context>;
113
+ errorHandler?: ErrorHandler<CrawlingContext, ExtendedContext>;
91
114
  /**
92
115
  * A function to handle requests that failed more than {@link BasicCrawlerOptions.maxRequestRetries|`maxRequestRetries`} times.
93
116
  *
@@ -96,14 +119,11 @@ export interface BasicCrawlerOptions<Context extends CrawlingContext = BasicCraw
96
119
  * Second argument is the `Error` instance that
97
120
  * represents the last error thrown during processing of the request.
98
121
  */
99
- failedRequestHandler?: ErrorHandler<Context>;
122
+ failedRequestHandler?: ErrorHandler<CrawlingContext, ExtendedContext>;
100
123
  /**
101
124
  * Specifies the maximum number of retries allowed for a request if its processing fails.
102
- * This includes retries due to navigation errors or errors thrown from user-supplied functions
103
- * (`requestHandler`, `preNavigationHooks`, `postNavigationHooks`).
104
- *
105
- * This limit does not apply to retries triggered by session rotation
106
- * (see {@link BasicCrawlerOptions.maxSessionRotations|`maxSessionRotations`}).
125
+ * This includes retries due to navigation errors, session/proxy errors, or errors thrown from user-supplied
126
+ * functions (`requestHandler`, `preNavigationHooks`, `postNavigationHooks`).
107
127
  * @default 3
108
128
  */
109
129
  maxRequestRetries?: number;
@@ -112,26 +132,24 @@ export interface BasicCrawlerOptions<Context extends CrawlingContext = BasicCraw
112
132
  * @default 0
113
133
  */
114
134
  sameDomainDelaySecs?: number;
115
- /**
116
- * Maximum number of session rotations per request.
117
- * The crawler will automatically rotate the session in case of a proxy error or if it gets blocked by the website.
118
- *
119
- * The session rotations are not counted towards the {@link BasicCrawlerOptions.maxRequestRetries|`maxRequestRetries`} limit.
120
- * @default 10
121
- */
122
- maxSessionRotations?: number;
123
135
  /**
124
136
  * Maximum number of pages that the crawler will open. The crawl will stop when this limit is reached.
125
137
  * This value should always be set in order to prevent infinite loops in misconfigured crawlers.
126
138
  * > *NOTE:* In cases of parallel crawling, the actual number of pages visited might be slightly higher than this value.
127
139
  */
128
140
  maxRequestsPerCrawl?: number;
141
+ /**
142
+ * Maximum depth of the crawl. If not set, the crawl will continue until all requests are processed.
143
+ * Setting this to `0` will only process the initial requests, skipping all links enqueued by `crawlingContext.enqueueLinks` and `crawlingContext.addRequests`.
144
+ * Passing `1` will process the initial requests and all links enqueued by `crawlingContext.enqueueLinks` and `crawlingContext.addRequests` in the handler for initial requests.
145
+ */
146
+ maxCrawlDepth?: number;
129
147
  /**
130
148
  * Custom options passed to the underlying {@link AutoscaledPool} constructor.
131
149
  * > *NOTE:* The {@link AutoscaledPoolOptions.runTaskFunction|`runTaskFunction`}
132
- * and {@link AutoscaledPoolOptions.isTaskReadyFunction|`isTaskReadyFunction`} options
133
- * are provided by the crawler and cannot be overridden.
134
- * However, we can provide a custom implementation of {@link AutoscaledPoolOptions.isFinishedFunction|`isFinishedFunction`}.
150
+ * option is provided by the crawler and cannot be overridden.
151
+ * However, we can provide custom implementations of {@link AutoscaledPoolOptions.isFinishedFunction|`isFinishedFunction`}
152
+ * and {@link AutoscaledPoolOptions.isTaskReadyFunction|`isTaskReadyFunction`}.
135
153
  */
136
154
  autoscaledPoolOptions?: AutoscaledPoolOptions;
137
155
  /**
@@ -159,14 +177,14 @@ export interface BasicCrawlerOptions<Context extends CrawlingContext = BasicCraw
159
177
  */
160
178
  keepAlive?: boolean;
161
179
  /**
162
- * Basic crawler will initialize the {@link SessionPool} with the corresponding {@link SessionPoolOptions|`sessionPoolOptions`}.
163
- * The session instance will be than available in the {@link BasicCrawlerOptions.requestHandler|`requestHandler`}.
164
- */
165
- useSessionPool?: boolean;
166
- /**
167
- * The configuration options for {@link SessionPool} to use.
180
+ * An existing session pool instance to use. When provided, the crawler will use this pool directly instead of
181
+ * creating a new one, enabling session sharing across multiple crawlers. The crawler will not tear down a shared
182
+ * pool — the caller is responsible for its lifecycle.
183
+ *
184
+ * Accepts the built-in {@link SessionPool} or any object implementing the {@link ISessionPool} interface,
185
+ * so custom session-management strategies can be plugged in.
168
186
  */
169
- sessionPoolOptions?: SessionPoolOptions;
187
+ sessionPool?: ISessionPool;
170
188
  /**
171
189
  * Defines the length of the interval for calling the `setStatusMessage` in seconds.
172
190
  */
@@ -188,6 +206,11 @@ export interface BasicCrawlerOptions<Context extends CrawlingContext = BasicCraw
188
206
  * ```
189
207
  */
190
208
  statusMessageCallback?: StatusMessageCallback;
209
+ /**
210
+ * HTTP status codes that indicate the session should be retired.
211
+ * @default [401, 403, 429]
212
+ */
213
+ blockedStatusCodes?: number[];
191
214
  /**
192
215
  * If set to `true`, the crawler will automatically try to bypass any detected bot protection.
193
216
  *
@@ -199,20 +222,22 @@ export interface BasicCrawlerOptions<Context extends CrawlingContext = BasicCraw
199
222
  /**
200
223
  * If set to `true`, the crawler will automatically try to fetch the robots.txt file for each domain,
201
224
  * and skip those that are not allowed. This also prevents disallowed URLs to be added via `enqueueLinks`.
225
+ *
226
+ * If an object is provided, it may contain a `userAgent` property to specify which user-agent
227
+ * should be used when checking the robots.txt file. If not provided, the default user-agent `*` will be used.
202
228
  */
203
- respectRobotsTxtFile?: boolean;
229
+ respectRobotsTxtFile?: boolean | {
230
+ userAgent?: string;
231
+ };
204
232
  /**
205
233
  * When a request is skipped for some reason, you can use this callback to act on it.
206
- * This is currently fired only for requests skipped based on robots.txt file.
234
+ * This is currently fired for requests skipped
235
+ * 1. based on robots.txt file,
236
+ * 2. because they don't match enqueueLinks filters,
237
+ * 3. because they are redirected to a URL that doesn't match the enqueueLinks strategy,
238
+ * 4. or because the {@link BasicCrawlerOptions.maxRequestsPerCrawl|`maxRequestsPerCrawl`} limit has been reached
207
239
  */
208
240
  onSkippedRequest?: SkippedRequestCallback;
209
- /** @internal */
210
- log?: Log;
211
- /**
212
- * Enables experimental features of Crawlee, which can alter the behavior of the crawler.
213
- * WARNING: these options are not guaranteed to be stable and may change or be removed at any time.
214
- */
215
- experiments?: CrawlerExperiments;
216
241
  /**
217
242
  * Customize the way statistics collecting works, such as logging interval or
218
243
  * whether to output them to the Key-Value store.
@@ -220,24 +245,56 @@ export interface BasicCrawlerOptions<Context extends CrawlingContext = BasicCraw
220
245
  statisticsOptions?: StatisticsOptions;
221
246
  /**
222
247
  * HTTP client implementation for the `sendRequest` context helper and for plain HTTP crawling.
223
- * Defaults to a new instance of {@link GotScrapingHttpClient}
248
+ * Defaults to {@link ImpitHttpClient} when `@crawlee/impit-client` is installed, otherwise {@link FetchHttpClient}.
224
249
  */
225
250
  httpClient?: BaseHttpClient;
226
- }
227
- /**
228
- * A set of options that you can toggle to enable experimental features in Crawlee.
229
- *
230
- * NOTE: These options will not respect semantic versioning and may be removed or changed at any time. Use at your own risk.
231
- * If you do use these and encounter issues, please report them to us.
232
- */
233
- export interface CrawlerExperiments {
234
251
  /**
235
- * @deprecated This experiment is now enabled by default, and this flag will be removed in a future release.
236
- * If you encounter issues due to this change, please:
237
- * - report it to us: https://github.com/apify/crawlee
238
- * - set `requestLocking` to `false` in the `experiments` option of the crawler
252
+ * If set, the crawler will be configured for all connections to use
253
+ * the Proxy URLs provided and rotated according to the configuration.
254
+ */
255
+ proxyConfiguration?: IProxyConfiguration;
256
+ /**
257
+ * Custom configuration to use for this crawler.
258
+ * If provided, the crawler will use its own ServiceLocator instance instead of the global one.
259
+ */
260
+ configuration?: Configuration;
261
+ /**
262
+ * Custom storage backend to use for this crawler.
263
+ * If provided, the crawler will use its own ServiceLocator instance instead of the global one.
264
+ */
265
+ storageBackend?: StorageBackend;
266
+ /**
267
+ * Custom event manager to use for this crawler.
268
+ * If provided, the crawler will use its own ServiceLocator instance instead of the global one.
269
+ */
270
+ eventManager?: EventManager;
271
+ /**
272
+ * Custom logger to use for this crawler.
273
+ * If provided, the crawler will use its own ServiceLocator instance instead of the global one.
239
274
  */
240
- requestLocking?: boolean;
275
+ logger?: CrawleeLogger;
276
+ /**
277
+ * A unique identifier for the crawler instance. This ID is used to isolate the state returned by
278
+ * {@link BasicCrawler.useState|`crawler.useState()`} from other crawler instances.
279
+ *
280
+ * When multiple crawler instances use `useState()` without an explicit `id`, they will share the same
281
+ * state object for backward compatibility. A warning will be logged in this case.
282
+ *
283
+ * To ensure each crawler has its own isolated state that also persists across script restarts
284
+ * (e.g., during Apify migrations), provide a stable, unique ID for each crawler instance.
285
+ *
286
+ */
287
+ id?: string;
288
+ /**
289
+ * An array of HTTP response [Status Codes](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status) to be excluded from error consideration.
290
+ * By default, status codes >= 500 trigger errors.
291
+ */
292
+ ignoreHttpErrorStatusCodes?: number[];
293
+ /**
294
+ * An array of additional HTTP response [Status Codes](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status) to be treated as errors.
295
+ * By default, status codes >= 500 trigger errors.
296
+ */
297
+ additionalHttpErrorStatusCodes?: number[];
241
298
  }
242
299
  /**
243
300
  * Provides a simple framework for parallel crawling of web pages.
@@ -251,15 +308,22 @@ export interface CrawlerExperiments {
251
308
  *
252
309
  * `BasicCrawler` invokes the user-provided {@link BasicCrawlerOptions.requestHandler|`requestHandler`}
253
310
  * for each {@link Request} object, which represents a single URL to crawl.
254
- * The {@link Request} objects are fed from the {@link RequestList} or {@link RequestQueue}
255
- * instances provided by the {@link BasicCrawlerOptions.requestList|`requestList`} or {@link BasicCrawlerOptions.requestQueue|`requestQueue`}
256
- * constructor options, respectively. If neither `requestList` nor `requestQueue` options are provided,
257
- * the crawler will open the default request queue either when the {@link BasicCrawler.addRequests|`crawler.addRequests()`} function is called,
258
- * or if `requests` parameter (representing the initial requests) of the {@link BasicCrawler.run|`crawler.run()`} function is provided.
311
+ * The {@link Request} objects are fed from the {@link IRequestManager|request manager} provided via the
312
+ * {@link BasicCrawlerOptions.requestManager|`requestManager`} constructor option (a {@link RequestQueue} is
313
+ * itself a request manager). If no `requestManager` is provided, the crawler opens the default {@link RequestQueue}
314
+ * either when the {@link BasicCrawler.addRequests|`crawler.addRequests()`} function is called, or if the `requests`
315
+ * parameter (representing the initial requests) of the {@link BasicCrawler.run|`crawler.run()`} function is provided.
316
+ *
317
+ * To read requests from a read-only source such as a {@link RequestList} or {@link SitemapRequestLoader} while
318
+ * still being able to enqueue new ones, combine the loader with a queue into a {@link RequestManagerTandem} using
319
+ * {@link IRequestLoader.toTandem|`requestLoader.toTandem()`} and pass the result as `requestManager`. The tandem
320
+ * first processes URLs from the loader and automatically enqueues them into the queue, ensuring a single URL is not
321
+ * crawled multiple times.
259
322
  *
260
- * If both {@link BasicCrawlerOptions.requestList|`requestList`} and {@link BasicCrawlerOptions.requestQueue|`requestQueue`} options are used,
261
- * the instance first processes URLs from the {@link RequestList} and automatically enqueues all of them
262
- * to the {@link RequestQueue} before it starts their processing. This ensures that a single URL is not crawled multiple times.
323
+ * > The legacy {@link BasicCrawlerOptions.requestList|`requestList`} and
324
+ * > {@link BasicCrawlerOptions.requestQueue|`requestQueue`} options are deprecated. They are still accepted and
325
+ * > folded into a single `requestManager` (combined into a tandem when both are given), but new code should use
326
+ * > `requestManager` directly.
263
327
  *
264
328
  * The crawler finishes if there are no more {@link Request} objects to crawl.
265
329
  *
@@ -303,29 +367,68 @@ export interface CrawlerExperiments {
303
367
  * ```
304
368
  * @category Crawlers
305
369
  */
306
- export declare class BasicCrawler<Context extends CrawlingContext = BasicCrawlingContext> {
307
- readonly config: Configuration;
370
+ /**
371
+ * Identifies a crawler instance for storage aliasing, `useState()` and status-message events.
372
+ */
373
+ interface CrawlerIdentity {
374
+ /**
375
+ * 0-based instantiation order across all crawlers in the process.
376
+ * Note that the value can be subject to race conditions between different script invocations.
377
+ */
378
+ readonly instanceIndex: number;
379
+ /** The user-supplied `id` option, or a fallback derived from `instanceIndex`. */
380
+ readonly id: string;
381
+ /** Whether `id` came from the user (as opposed to being derived from `instanceIndex`). */
382
+ readonly hasExplicitId: boolean;
383
+ }
384
+ export declare class BasicCrawler<Context extends CrawlingContext = CrawlingContext, ContextExtension = Dictionary<never>, ExtendedContext extends Context = Context & ContextExtension> {
385
+ #private;
308
386
  protected static readonly CRAWLEE_STATE_KEY = "CRAWLEE_STATE";
387
+ /**
388
+ * Tracks the number of crawler instances created. The first crawler uses the default
389
+ * request queue; subsequent ones get their own queue via a unique alias so they don't
390
+ * collide.
391
+ */
392
+ private static instanceCount;
393
+ /**
394
+ * Tracks crawler instances that accessed shared state without having an explicit id.
395
+ * Used to detect and warn about multiple crawlers sharing the same state.
396
+ */
397
+ private static useStateAnonymousIndices;
309
398
  /**
310
399
  * A reference to the underlying {@link Statistics} class that collects and logs run statistics for requests.
311
400
  */
312
401
  readonly stats: Statistics;
313
402
  /**
314
- * A reference to the underlying {@link RequestList} class that manages the crawler's {@link Request|requests}.
315
- * Only available if used by the crawler.
403
+ * The main request-handling component of the crawler. It manages the requests that the crawler processes,
404
+ * combining any provided request loader and/or queue. It's initialized during the crawler startup or lazily
405
+ * via {@link BasicCrawler.getRequestManager|`getRequestManager()`}.
316
406
  */
317
- requestList?: IRequestList;
407
+ protected requestManager?: IRequestManager;
318
408
  /**
319
- * Dynamic queue of URLs to be processed. This is useful for recursive crawling of websites.
320
- * A reference to the underlying {@link RequestQueue} class that manages the crawler's {@link Request|requests}.
321
- * Only available if used by the crawler.
409
+ * A reference to the underlying session pool that manages the crawler's {@link Session|sessions}. Typed as
410
+ * {@link ISessionPool} so custom implementations can be plugged in via the `sessionPool` constructor option.
322
411
  */
323
- requestQueue?: RequestProvider;
412
+ readonly sessionPool: ISessionPool;
324
413
  /**
325
- * A reference to the underlying {@link SessionPool} class that manages the crawler's {@link Session|sessions}.
326
- * Only available if used by the crawler.
414
+ * Set when the crawler constructed its own {@link SessionPool} (no `sessionPool` option was provided).
415
+ * Holds the same instance as `sessionPool`, but typed as the concrete class so the crawler can call
416
+ * lifecycle methods (`resetStore`, `teardown`) that aren't part of {@link ISessionPool}. A user-supplied
417
+ * pool is never owned and never torn down by the crawler.
327
418
  */
328
- sessionPool?: SessionPool;
419
+ private ownedSessionPool?;
420
+ /**
421
+ * Set when the crawler constructed its own request manager (no `requestManager`, `requestQueue`, or `requestList`
422
+ * option was provided). The owned manager is purged (not dropped) between repeated `run()` calls.
423
+ * A user-supplied manager is never purged by the crawler.
424
+ */
425
+ private ownedRequestManager?;
426
+ /**
427
+ * Whether the request-processing-time hint has already been forwarded to the request manager. The hint
428
+ * derives only from `requestHandlerTimeoutMillis` (constant for the crawler's lifetime) and is raise-only,
429
+ * so it only needs to be applied once, at the first async access of the manager.
430
+ */
431
+ private requestManagerTimeoutsApplied;
329
432
  /**
330
433
  * A reference to the underlying {@link AutoscaledPool} class that manages the concurrency of the crawler.
331
434
  * > *NOTE:* This property is only initialized after calling the {@link BasicCrawler.run|`crawler.run()`} function.
@@ -334,40 +437,65 @@ export declare class BasicCrawler<Context extends CrawlingContext = BasicCrawlin
334
437
  * or to abort it by calling {@link AutoscaledPool.abort|`autoscaledPool.abort()`}.
335
438
  */
336
439
  autoscaledPool?: AutoscaledPool;
440
+ /**
441
+ * A reference to the underlying {@link IProxyConfiguration} instance that manages the crawler's proxies.
442
+ * Only available if used by the crawler.
443
+ */
444
+ readonly proxyConfiguration?: IProxyConfiguration;
337
445
  /**
338
446
  * Default {@link Router} instance that will be used if we don't specify any {@link BasicCrawlerOptions.requestHandler|`requestHandler`}.
339
447
  * See {@link Router.addHandler|`router.addHandler()`} and {@link Router.addDefaultHandler|`router.addDefaultHandler()`}.
340
448
  */
341
- readonly router: RouterHandler<LoadedContext<Context>>;
449
+ readonly router: RouterHandler<Context>;
450
+ private _basicContextPipeline?;
451
+ /**
452
+ * The basic part of the context pipeline. Unlike the subclass pipeline, this
453
+ * part has no major side effects (e.g. launching a browser). It also makes typing more explicit, as subclass
454
+ * pipelines expect the basic crawler fields to already be present in the context at runtime.
455
+ *
456
+ * Context built with this pipeline can be passed into multiple crawler pipelines at once.
457
+ * This is used e.g. in the {@link AdaptivePlaywrightCrawler|`AdaptivePlaywrightCrawler`}.
458
+ */
459
+ get basicContextPipeline(): ContextPipeline<{
460
+ request: Request;
461
+ }, CrawlingContext>;
462
+ private _contextPipeline?;
463
+ get contextPipeline(): ContextPipeline<CrawlingContext, ExtendedContext>;
342
464
  running: boolean;
343
465
  hasFinishedBefore: boolean;
344
- readonly log: Log;
345
- protected requestHandler: RequestHandler<Context>;
346
- protected errorHandler?: ErrorHandler<Context>;
347
- protected failedRequestHandler?: ErrorHandler<Context>;
348
- protected requestHandlerTimeoutMillis: number;
349
- protected internalTimeoutMillis: number;
350
- protected maxRequestRetries: number;
351
- protected sameDomainDelayMillis: number;
352
- protected domainAccessedTime: Map<string, number>;
353
- protected maxSessionRotations: number;
354
- protected handledRequestsCount: number;
355
- protected statusMessageLoggingInterval: number;
356
- protected statusMessageCallback?: StatusMessageCallback;
357
- protected sessionPoolOptions: SessionPoolOptions;
358
- protected useSessionPool: boolean;
359
- protected crawlingContexts: Map<string, Context>;
360
- protected autoscaledPoolOptions: AutoscaledPoolOptions;
361
- protected events: EventManager;
362
- protected httpClient: BaseHttpClient;
363
- protected retryOnBlocked: boolean;
364
- protected respectRobotsTxtFile: boolean;
365
- protected onSkippedRequest?: SkippedRequestCallback;
466
+ private unexpectedStop;
467
+ get log(): CrawleeLogger;
468
+ protected readonly requestHandler: RequestHandler<ExtendedContext>;
469
+ protected readonly errorHandler?: ErrorHandler<CrawlingContext, ExtendedContext>;
470
+ protected readonly failedRequestHandler?: ErrorHandler<CrawlingContext, ExtendedContext>;
471
+ private requestHandlerTimeoutMillis;
472
+ protected readonly internalTimeoutMillis: number;
473
+ protected readonly maxRequestRetries: number;
474
+ protected readonly maxCrawlDepth?: number;
475
+ private sameDomainDelayMillis;
476
+ private domainAccessedTime;
477
+ protected readonly maxRequestsPerCrawl?: number;
478
+ private get handledRequestsCount();
479
+ private statusMessageLoggingInterval;
480
+ private statusMessageCallback?;
481
+ protected blockedStatusCodes: Set<number>;
482
+ protected readonly additionalHttpErrorStatusCodes: Set<number>;
483
+ private ignoreHttpErrorStatusCodes;
484
+ private autoscaledPoolOptions;
485
+ protected readonly httpClient: BaseHttpClient;
486
+ protected readonly retryOnBlocked: boolean;
487
+ private respectRobotsTxtFile;
488
+ protected readonly onSkippedRequest?: SkippedRequestCallback;
366
489
  private _closeEvents?;
367
- private experiments;
490
+ private loggedPerRun;
368
491
  private readonly robotsTxtFileCache;
369
- private _experimentWarnings;
492
+ protected readonly identity: CrawlerIdentity;
493
+ private readonly contextPipelineOptions;
370
494
  protected static optionsShape: {
495
+ // @ts-ignore optional peer dependency or compatibility with es2022
496
+ contextPipelineBuilder: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
497
+ // @ts-ignore optional peer dependency or compatibility with es2022
498
+ extendContext: import("ow").Predicate<Function> & import("ow").BasePredicate<Function | undefined>;
371
499
  // @ts-ignore optional peer dependency or compatibility with es2022
372
500
  requestList: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
373
501
  // @ts-ignore optional peer dependency or compatibility with es2022
@@ -384,28 +512,42 @@ export declare class BasicCrawler<Context extends CrawlingContext = BasicCrawlin
384
512
  maxRequestRetries: import("ow").NumberPredicate & import("ow").BasePredicate<number | undefined>;
385
513
  // @ts-ignore optional peer dependency or compatibility with es2022
386
514
  sameDomainDelaySecs: import("ow").NumberPredicate & import("ow").BasePredicate<number | undefined>;
387
- // @ts-ignore optional peer dependency or compatibility with es2022
388
- maxSessionRotations: import("ow").NumberPredicate & import("ow").BasePredicate<number | undefined>;
389
515
  // @ts-ignore optional peer dependency or compatibility with es2022
390
516
  maxRequestsPerCrawl: import("ow").NumberPredicate & import("ow").BasePredicate<number | undefined>;
517
+ // @ts-ignore optional peer dependency or compatibility with es2022
518
+ maxCrawlDepth: import("ow").NumberPredicate & import("ow").BasePredicate<number | undefined>;
391
519
  // @ts-ignore optional peer dependency or compatibility with es2022
392
520
  autoscaledPoolOptions: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
393
521
  // @ts-ignore optional peer dependency or compatibility with es2022
394
- sessionPoolOptions: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
522
+ sessionPool: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
395
523
  // @ts-ignore optional peer dependency or compatibility with es2022
396
- useSessionPool: import("ow").BooleanPredicate & import("ow").BasePredicate<boolean | undefined>;
524
+ proxyConfiguration: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
397
525
  // @ts-ignore optional peer dependency or compatibility with es2022
398
526
  statusMessageLoggingInterval: import("ow").NumberPredicate & import("ow").BasePredicate<number | undefined>;
399
527
  // @ts-ignore optional peer dependency or compatibility with es2022
400
528
  statusMessageCallback: import("ow").Predicate<Function> & import("ow").BasePredicate<Function | undefined>;
529
+ // @ts-ignore optional peer dependency or compatibility with es2022
530
+ additionalHttpErrorStatusCodes: import("ow").ArrayPredicate<number>;
531
+ // @ts-ignore optional peer dependency or compatibility with es2022
532
+ ignoreHttpErrorStatusCodes: import("ow").ArrayPredicate<number>;
533
+ // @ts-ignore optional peer dependency or compatibility with es2022
534
+ blockedStatusCodes: import("ow").ArrayPredicate<number>;
401
535
  // @ts-ignore optional peer dependency or compatibility with es2022
402
536
  retryOnBlocked: import("ow").BooleanPredicate & import("ow").BasePredicate<boolean | undefined>;
403
537
  // @ts-ignore optional peer dependency or compatibility with es2022
404
- respectRobotsTxtFile: import("ow").BooleanPredicate & import("ow").BasePredicate<boolean | undefined>;
538
+ respectRobotsTxtFile: import("ow").AnyPredicate<boolean | object>;
405
539
  // @ts-ignore optional peer dependency or compatibility with es2022
406
540
  onSkippedRequest: import("ow").Predicate<Function> & import("ow").BasePredicate<Function | undefined>;
407
541
  // @ts-ignore optional peer dependency or compatibility with es2022
408
542
  httpClient: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
543
+ // @ts-ignore optional peer dependency or compatibility with es2022
544
+ configuration: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
545
+ // @ts-ignore optional peer dependency or compatibility with es2022
546
+ storageBackend: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
547
+ // @ts-ignore optional peer dependency or compatibility with es2022
548
+ eventManager: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
549
+ // @ts-ignore optional peer dependency or compatibility with es2022
550
+ logger: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
409
551
  // @ts-ignore optional peer dependency or compatibility with es2022
410
552
  minConcurrency: import("ow").NumberPredicate & import("ow").BasePredicate<number | undefined>;
411
553
  // @ts-ignore optional peer dependency or compatibility with es2022
@@ -414,17 +556,38 @@ export declare class BasicCrawler<Context extends CrawlingContext = BasicCrawlin
414
556
  maxRequestsPerMinute: import("ow").NumberPredicate & import("ow").BasePredicate<number | undefined>;
415
557
  // @ts-ignore optional peer dependency or compatibility with es2022
416
558
  keepAlive: import("ow").BooleanPredicate & import("ow").BasePredicate<boolean | undefined>;
417
- // @ts-ignore optional peer dependency or compatibility with es2022
418
- log: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
419
- // @ts-ignore optional peer dependency or compatibility with es2022
420
- experiments: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
421
559
  // @ts-ignore optional peer dependency or compatibility with es2022
422
560
  statisticsOptions: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
561
+ // @ts-ignore optional peer dependency or compatibility with es2022
562
+ id: import("ow").StringPredicate & import("ow").BasePredicate<string | undefined>;
423
563
  };
424
564
  /**
425
565
  * All `BasicCrawler` parameters are passed via an options object.
426
566
  */
427
- constructor(options?: BasicCrawlerOptions<Context>, config?: Configuration);
567
+ constructor(options?: BasicCrawlerOptions<Context, ContextExtension, ExtendedContext> & RequireContextPipeline<CrawlingContext, Context>);
568
+ /**
569
+ * Determines if the given HTTP status code is an error status code given
570
+ * the default behaviour and user-set preferences.
571
+ * @param status
572
+ * @returns `true` if the status code is considered an error, `false` otherwise
573
+ */
574
+ protected isErrorStatusCode(status: number): boolean;
575
+ /**
576
+ * Builds the basic context pipeline that transforms `{ request }` into a full `CrawlingContext`.
577
+ * This handles base context creation, session resolution, and context helpers.
578
+ */
579
+ private buildBasicContextPipeline;
580
+ private checkRobotsTxt;
581
+ /**
582
+ * Builds the subclass-specific context pipeline that transforms a `CrawlingContext` into the crawler's target context type.
583
+ * Subclasses should override this to add their own pipeline stages.
584
+ */
585
+ protected buildContextPipeline(): ContextPipeline<CrawlingContext, CrawlingContext>;
586
+ private createBaseContext;
587
+ private resolveRequest;
588
+ private resolveSession;
589
+ private createContextHelpers;
590
+ private buildFinalContextPipeline;
428
591
  /**
429
592
  * Checks if the given error is a proxy error by comparing its message to a list of known proxy error messages.
430
593
  * Used for retrying requests that failed due to proxy errors.
@@ -433,15 +596,15 @@ export declare class BasicCrawler<Context extends CrawlingContext = BasicCrawlin
433
596
  */
434
597
  protected isProxyError(error: Error): boolean;
435
598
  /**
436
- * Checks whether the given crawling context is getting blocked by anti-bot protection using several heuristics.
437
- * Returns `false` if the request is not blocked, otherwise returns a string with a description of the block reason.
438
- * @param _crawlingContext The crawling context to check.
439
- */
440
- protected isRequestBlocked(_crawlingContext: Context): Promise<string | false>;
441
- /**
599
+ * Sets the status message for the current crawler run.
600
+ *
442
601
  * This method is periodically called by the crawler, every `statusMessageLoggingInterval` seconds.
602
+ *
603
+ * The message is logged and broadcast via the {@link EventType.STATUS_MESSAGE|`statusMessage`}
604
+ * event. Integrations such as the Apify SDK subscribe to that event and forward the message to
605
+ * their status-reporting backend (e.g. the Apify platform).
443
606
  */
444
- setStatusMessage(message: string, options?: SetStatusMessageOptions): Promise<void>;
607
+ setStatusMessage(message: string, options?: SetStatusMessageOptions): void;
445
608
  private getPeriodicLogger;
446
609
  /**
447
610
  * Runs the crawler. Returns a promise that resolves once all the requests are processed
@@ -453,15 +616,52 @@ export declare class BasicCrawler<Context extends CrawlingContext = BasicCrawlin
453
616
  * @param [requests] The requests to add.
454
617
  * @param [options] Options for the request queue.
455
618
  */
456
- run(requests?: (string | Request | RequestOptions)[], options?: CrawlerRunOptions): Promise<FinalStatistics>;
619
+ run(requests?: RequestsLike, options?: CrawlerRunOptions): Promise<FinalStatistics>;
457
620
  /**
458
621
  * Gracefully stops the current run of the crawler.
459
622
  *
460
623
  * All the tasks active at the time of calling this method will be allowed to finish.
624
+ *
625
+ * To stop the crawler immediately, use {@link BasicCrawler.teardown|`crawler.teardown()`} instead.
626
+ */
627
+ stop(reason?: string): void;
628
+ /**
629
+ * Returns the crawler's {@link IRequestManager|request manager}, opening the default {@link RequestQueue}
630
+ * if none has been configured or opened yet.
631
+ */
632
+ getRequestManager(): Promise<IRequestManager>;
633
+ /**
634
+ * @deprecated Use {@link BasicCrawler.getRequestManager|`getRequestManager()`} instead. This returns the
635
+ * crawler's request manager, which is no longer guaranteed to be a {@link RequestQueue}.
636
+ */
637
+ getRequestQueue(): Promise<IRequestManager>;
638
+ /**
639
+ * Opens the default {@link RequestQueue}, applies the crawler's timeouts to it and records it as the
640
+ * crawler-owned manager (so it gets purged between repeated `run()` calls).
641
+ * @private
642
+ */
643
+ private openOwnedRequestQueue;
644
+ /**
645
+ * Tells a request manager how long we expect to hold a fetched request, so that one backed by a
646
+ * locking storage backend keeps it reserved for slightly longer than the request handler timeout
647
+ * (with some padding for overhead), but never for less than a minute. This prevents a long-running
648
+ * request from being handed out a second time while it is still being processed — and it works
649
+ * regardless of whether the manager is a plain {@link RequestQueue} or a `RequestManagerTandem`.
461
650
  */
462
- stop(message?: string): void;
463
- getRequestQueue(): Promise<RequestProvider>;
651
+ private applyRequestManagerTimeouts;
652
+ /**
653
+ * Validates a request source's `userData` against the {@link RouteSchemas|Standard Schema} registered
654
+ * for its label on the crawler's schema-router (if any), throwing a {@link RequestValidationError} on
655
+ * mismatch. A no-op when the user's request handler is not a schema-router, or no schema is registered for
656
+ * the request's label. Applied by the crawler on the add paths it owns — `crawler.addRequests`,
657
+ * `crawler.run`, `context.addRequests` and `context.enqueueLinks`.
658
+ */
659
+ private validateRequestUserData;
464
660
  useState<State extends Dictionary = Dictionary>(defaultValue?: State): Promise<State>;
661
+ protected getPendingRequestCountApproximation(): Promise<number>;
662
+ protected calculateEnqueuedRequestLimit(explicitLimit?: number): Promise<number | undefined>;
663
+ protected handleSkippedRequest(options: Parameters<SkippedRequestCallback>[0]): Promise<void>;
664
+ private logOncePerRun;
465
665
  /**
466
666
  * Adds requests to the queue in batches. By default, it will resolve after the initial batch is added, and continue
467
667
  * adding the rest in background. You can configure the batch size via `batchSize` option and the sleep time in between
@@ -473,15 +673,15 @@ export declare class BasicCrawler<Context extends CrawlingContext = BasicCrawlin
473
673
  * @param requests The requests to add
474
674
  * @param options Options for the request queue
475
675
  */
476
- addRequests(requests: (string | Source)[], options?: CrawlerAddRequestsOptions): Promise<CrawlerAddRequestsResult>;
676
+ addRequests(requests: ReadonlyDeep<RequestsLike>, options?: CrawlerAddRequestsOptions): Promise<CrawlerAddRequestsResult>;
477
677
  /**
478
678
  * Pushes data to the specified {@link Dataset}, or the default crawler {@link Dataset} by calling {@link Dataset.pushData}.
479
679
  */
480
- pushData(data: Parameters<Dataset['pushData']>[0], datasetIdOrName?: string): Promise<void>;
680
+ pushData(data: Parameters<Dataset['pushData']>[0], datasetIdentifier?: string | StorageIdentifier): Promise<void>;
481
681
  /**
482
682
  * Retrieves the specified {@link Dataset}, or the default crawler {@link Dataset}.
483
683
  */
484
- getDataset(idOrName?: string): Promise<Dataset>;
684
+ getDataset(identifier?: string | StorageIdentifier): Promise<Dataset>;
485
685
  /**
486
686
  * Retrieves data from the default crawler {@link Dataset} by calling {@link Dataset.getData}.
487
687
  */
@@ -491,85 +691,89 @@ export declare class BasicCrawler<Context extends CrawlingContext = BasicCrawlin
491
691
  * Supported formats are currently 'json' and 'csv', and will be inferred from the `path` automatically.
492
692
  */
493
693
  exportData<Data>(path: string, format?: 'json' | 'csv', options?: DatasetExportOptions): Promise<Data[]>;
694
+ /**
695
+ * Initializes the crawler.
696
+ */
494
697
  protected _init(): Promise<void>;
495
- protected _runRequestHandler(crawlingContext: Context): Promise<void>;
698
+ protected runRequestHandler(crawlingContext: ExtendedContext): Promise<void>;
496
699
  /**
497
700
  * Handles blocked request
498
701
  */
499
- protected _throwOnBlockedRequest(session: Session, statusCode: number): void;
702
+ protected _throwOnBlockedRequest(statusCode: number): void;
500
703
  private isAllowedBasedOnRobotsTxtFile;
501
704
  protected getRobotsTxtFileForUrl(url: string): Promise<RobotsTxtFile | undefined>;
502
- protected _pauseOnMigration(): Promise<void>;
705
+ private pauseOnMigration;
503
706
  /**
504
- * Fetches request from either RequestList or RequestQueue. If request comes from a RequestList
505
- * and RequestQueue is present then enqueues it to the queue first.
707
+ * Fetches the next request to process from the underlying request provider.
506
708
  */
507
- protected _fetchNextRequest(): Promise<Request<Dictionary> | null | undefined>;
508
- /**
509
- * Executed when `errorHandler` finishes or the request is successful.
510
- * Can be used to clean up orphaned browser pages.
511
- */
512
- protected _cleanupContext(_crawlingContext: Context): Promise<void>;
709
+ private fetchNextRequest;
513
710
  /**
514
711
  * Delays processing of the request based on the `sameDomainDelaySecs` option,
515
712
  * adding it back to the queue after the timeout passes. Returns `true` if the request
516
713
  * should be ignored and will be reclaimed to the queue once ready.
517
714
  */
518
- protected delayRequest(request: Request, source: IRequestList | RequestProvider): boolean;
715
+ private delayRequest;
716
+ /** Handles a single request - runs the request handler with retries, error handling, and lifecycle management. */
717
+ private handleRequest;
718
+ /**
719
+ * Wrapper around the crawling context's `enqueueLinks` method:
720
+ * - Injects `crawlDepth` to each request being added based on the crawling context request.
721
+ * - Provides defaults for the `enqueueLinks` options based on the crawler configuration.
722
+ * - These options can be overridden by the user.
723
+ * @internal
724
+ */
725
+ protected enqueueLinksWithCrawlDepth(options: SetRequired<EnqueueLinksOptions, 'urls'>, request: Request<Dictionary>, requestManager: IRequestManager): Promise<BatchAddRequestsResult>;
519
726
  /**
520
- * Wrapper around requestHandler that fetches requests from RequestList/RequestQueue
521
- * then retries them in a case of an error, etc.
727
+ * Generator function that yields requests injected with the given crawl depth.
728
+ * @internal
522
729
  */
523
- protected _runTaskFunction(): Promise<void>;
730
+ protected addCrawlDepthRequestGenerator(requests: RequestsLike, newRequestDepth: number): AsyncGenerator<Source, void, undefined>;
524
731
  /**
525
- * Run async callback with given timeout and retry.
732
+ * Run async callback with given timeout and retry. Returns the result of the callback.
526
733
  * @ignore
527
734
  */
528
- protected _timeoutAndRetry(handler: () => Promise<unknown>, timeout: number, error: Error | string, maxRetries?: number, retried?: number): Promise<void>;
735
+ private timeoutAndRetry;
529
736
  /**
530
737
  * Returns true if either RequestList or RequestQueue have a request ready for processing.
531
738
  */
532
- protected _isTaskReadyFunction(): Promise<boolean>;
739
+ private isTaskReadyFunction;
533
740
  /**
534
741
  * Returns true if both RequestList and RequestQueue have all requests finished.
535
742
  */
536
- protected _defaultIsFinishedFunction(): Promise<boolean>;
537
- private _rotateSession;
743
+ private defaultIsFinishedFunction;
744
+ /**
745
+ * Unwraps errors thrown by the context pipeline to get the actual user error.
746
+ * RequestHandlerError and ContextPipelineInitializationError wrap the actual error.
747
+ */
748
+ private unwrapError;
538
749
  /**
539
750
  * Handles errors thrown by user provided requestHandler()
751
+ *
752
+ * @param request The request object, passed separately to circumvent potential dynamic logic in crawlingContext.request
540
753
  */
541
- protected _requestFunctionErrorHandler(error: Error, crawlingContext: Context, source: IRequestList | RequestProvider): Promise<void>;
542
- protected _tagUserHandlerError<T>(cb: () => unknown): Promise<T>;
543
- protected _handleFailedRequestHandler(crawlingContext: Context, error: Error): Promise<void>;
754
+ private requestFunctionErrorHandler;
755
+ private handleFailedRequestHandler;
544
756
  /**
545
757
  * Resolves the most verbose error message from a thrown error
546
758
  * @param error The error received
547
759
  * @returns The message to be logged
548
760
  */
549
761
  protected _getMessageFromError(error: Error, forceStack?: boolean): string | TimeoutError | undefined;
550
- protected _canRequestBeRetried(request: Request, error: Error): boolean;
551
- /**
552
- * Updates handledRequestsCount from possibly stored counts,
553
- * usually after worker migration. Since one of the stores
554
- * needs to have priority when both are present,
555
- * it is the request queue, because generally, the request
556
- * list will first be dumped into the queue and then left
557
- * empty.
558
- */
559
- protected _loadHandledRequestCount(): Promise<void>;
560
- protected _executeHooks<HookLike extends (...args: any[]) => Awaitable<void>>(hooks: HookLike[], ...args: Parameters<HookLike>): Promise<void>;
762
+ private canRequestBeRetried;
561
763
  /**
562
- * Function for cleaning up after all request are processed.
563
- * @ignore
764
+ * Stops the crawler immediately.
765
+ *
766
+ * This method doesn't wait for currently active requests to finish.
767
+ *
768
+ * To stop the crawler gracefully (waiting for all running requests to finish), use {@link BasicCrawler.stop|`crawler.stop()`} instead.
564
769
  */
565
770
  teardown(): Promise<void>;
566
771
  protected _getCookieHeaderFromRequest(request: Request): string;
567
- private _getRequestQueue;
568
- protected requestMatchesEnqueueStrategy(request: Request): boolean;
772
+ private requestMatchesEnqueueStrategy;
569
773
  }
570
774
  export interface CreateContextOptions {
571
775
  request: Request;
572
- session?: Session;
776
+ session: ISession;
573
777
  proxyInfo?: ProxyInfo;
574
778
  }
575
779
  export interface CrawlerAddRequestsOptions extends AddRequestsBatchedOptions {
@@ -578,9 +782,14 @@ export interface CrawlerAddRequestsResult extends AddRequestsBatchedResult {
578
782
  }
579
783
  export interface CrawlerRunOptions extends CrawlerAddRequestsOptions {
580
784
  /**
581
- * Whether to purge the RequestQueue before running the crawler again. Defaults to true, so it is possible to reprocess failed requests.
582
- * When disabled, only new requests will be considered. Note that even a failed request is considered as handled.
583
- * @default true
785
+ * Controls whether the request queue is purged between repeated `run()` calls on the same crawler instance.
786
+ * Purging clears all requests and resets internal counters, allowing the same URLs to be processed again.
787
+ *
788
+ * - **`undefined`** (default) — only the crawler's own (auto-created) queue is purged.
789
+ * A user-supplied `requestQueue` is left untouched.
790
+ * - **`true`** — the queue is always purged, even if it was supplied by the user.
791
+ * - **`false`** — nothing is purged. Only genuinely new requests will be processed;
792
+ * note that even a failed request is considered handled.
584
793
  */
585
794
  purgeRequestQueue?: boolean;
586
795
  }
@@ -608,5 +817,6 @@ export interface CrawlerRunOptions extends CrawlerAddRequestsOptions {
608
817
  * await crawler.run();
609
818
  * ```
610
819
  */
611
- export declare function createBasicRouter<Context extends BasicCrawlingContext = BasicCrawlingContext, UserData extends Dictionary = GetUserDataFromRequest<Context['request']>>(routes?: RouterRoutes<Context, UserData>): RouterHandler<Context>;
612
- //# sourceMappingURL=basic-crawler.d.ts.map
820
+ export declare function createBasicRouter<Context extends BasicCrawlingContext = BasicCrawlingContext, Routes extends Record<keyof Routes, Dictionary> = Record<string, GetUserDataFromRequest<Context['request']>>>(routes?: RouterRoutes<Context, Routes>): RouterHandler<Context, Routes>;
821
+ export declare function createBasicRouter<Context extends BasicCrawlingContext = BasicCrawlingContext, UserData extends Dictionary = GetUserDataFromRequest<Context['request']>>(routes?: RouterRoutes<Context, Record<string, UserData>>): RouterHandler<Context, Record<string, UserData>>;
822
+ export {};