@crawlee/basic 3.0.0-beta.6 → 3.0.0-beta.62

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,65 +1,48 @@
1
- import { Log } from '@apify/log';
2
- import { AutoscaledPool, AutoscaledPoolOptions, EnqueueLinksOptions, CrawlerHandleFailedRequestInput, ProxyInfo, QueueOperationInfo, Request, RequestList, RequestQueue, Session, SessionPool, SessionPoolOptions, Statistics, type CrawlingContext, RequestOptions, RequestQueueOperationOptions, Configuration, EventManager, FinalStatistics } from '@crawlee/core';
3
- import { Response as GotResponse } from 'got-scraping';
4
- import { ProcessedRequest } from '@crawlee/types';
5
- import { Awaitable } from '@crawlee/utils';
6
- export interface BasicCrawlerCrawlingContext extends CrawlingContext {
1
+ import type { Log } from '@apify/log';
2
+ import type { AutoscaledPoolOptions, EnqueueLinksOptions, EventManager, FinalStatistics, ProxyInfo, QueueOperationInfo, Request, RequestList, RequestOptions, RequestQueueOperationOptions, RouterHandler, Session, SessionPoolOptions } from '@crawlee/core';
3
+ import { AutoscaledPool, Configuration, type CrawlingContext, RequestQueue, SessionPool, Statistics } from '@crawlee/core';
4
+ import type { GotOptionsInit, Response as GotResponse } from 'got-scraping';
5
+ import type { ProcessedRequest, Dictionary, Awaitable } from '@crawlee/types';
6
+ export interface BasicCrawlingContext<UserData extends Dictionary = Dictionary> extends CrawlingContext<UserData> {
7
7
  crawler: BasicCrawler;
8
8
  enqueueLinks: (options: BasicCrawlerEnqueueLinksOptions) => Promise<QueueOperationInfo[]>;
9
- sendRequest: (request?: Request) => Promise<GotResponse<string>>;
10
- }
11
- export interface BasicCrawlerHandleFailedRequestInput extends CrawlerHandleFailedRequestInput {
12
- crawler: BasicCrawler;
9
+ sendRequest: (overrideOptions?: Partial<GotOptionsInit>) => Promise<GotResponse<string>>;
13
10
  }
14
11
  /** @internal */
15
12
  export declare type BasicCrawlerEnqueueLinksOptions = Omit<EnqueueLinksOptions, 'requestQueue'>;
16
- export declare type RequestHandler<Context extends CrawlingContext = BasicCrawlerCrawlingContext> = (inputs: Context) => Awaitable<void>;
17
- export declare type FailedRequestHandler<Inputs extends CrawlerHandleFailedRequestInput = BasicCrawlerHandleFailedRequestInput> = (inputs: Inputs) => Awaitable<void>;
18
- export interface BasicCrawlerOptions<Context extends CrawlingContext = BasicCrawlerCrawlingContext, ErrorContext extends CrawlerHandleFailedRequestInput = BasicCrawlerHandleFailedRequestInput> {
13
+ export declare type RequestHandler<Context extends CrawlingContext = BasicCrawlingContext> = (inputs: Context) => Awaitable<void>;
14
+ export declare type FailedRequestHandler<Context extends CrawlingContext = BasicCrawlingContext> = (inputs: Context, error: Error) => Awaitable<void>;
15
+ export interface BasicCrawlerOptions<Context extends CrawlingContext = BasicCrawlingContext> {
19
16
  /**
20
17
  * User-provided function that performs the logic of the crawler. It is called for each URL to crawl.
21
18
  *
22
- * The function receives the following object as an argument:
23
- * ```
24
- * {
25
- * request: Request,
26
- * session: Session,
27
- * crawler: BasicCrawler,
28
- * }
29
- * ```
30
- * where the {@link Request} instance represents the URL to crawl.
19
+ * The function receives the {@link BasicCrawlingContext} as an argument,
20
+ * where the {@link BasicCrawlingContext.request} represents the URL to crawl.
31
21
  *
32
22
  * The function must return a promise, which is then awaited by the crawler.
33
23
  *
34
24
  * If the function throws an exception, the crawler will try to re-crawl the
35
25
  * request later, up to `option.maxRequestRetries` times.
36
26
  * If all the retries fail, the crawler calls the function
37
- * provided to the `handleFailedRequestFunction` parameter.
27
+ * provided to the `failedRequestHandler` parameter.
38
28
  * To make this work, you should **always**
39
29
  * let your function throw exceptions rather than catch them.
40
30
  * The exceptions are logged to the request using the
41
31
  * {@link Request.pushErrorMessage} function.
42
32
  */
43
- requestHandler: RequestHandler<Context>;
33
+ requestHandler?: RequestHandler<Context>;
44
34
  /**
45
35
  * User-provided function that performs the logic of the crawler. It is called for each URL to crawl.
46
36
  *
47
- * The function receives the following object as an argument:
48
- * ```
49
- * {
50
- * request: Request,
51
- * session: Session,
52
- * crawler: BasicCrawler,
53
- * }
54
- * ```
55
- * where the {@link Request} instance represents the URL to crawl.
37
+ * The function receives the {@link BasicCrawlingContext} as an argument,
38
+ * where the {@link BasicCrawlingContext.request} represents the URL to crawl.
56
39
  *
57
40
  * The function must return a promise, which is then awaited by the crawler.
58
41
  *
59
42
  * If the function throws an exception, the crawler will try to re-crawl the
60
43
  * request later, up to `option.maxRequestRetries` times.
61
44
  * If all the retries fail, the crawler calls the function
62
- * provided to the `handleFailedRequestFunction` parameter.
45
+ * provided to the `failedRequestHandler` parameter.
63
46
  * To make this work, you should **always**
64
47
  * let your function throw exceptions rather than catch them.
65
48
  * The exceptions are logged to the request using the
@@ -90,49 +73,37 @@ export interface BasicCrawlerOptions<Context extends CrawlingContext = BasicCraw
90
73
  */
91
74
  handleRequestTimeoutSecs?: number;
92
75
  /**
93
- * A function to handle requests that failed more than `option.maxRequestRetries` times.
76
+ * User-provided function that allows modifying the request object before it gets retried by the crawler.
77
+ * It's executed before each retry for the requests that failed less than `option.maxRequestRetries` times.
94
78
  *
95
- * The function receives the following object as an argument:
96
- * ```
97
- * {
98
- * request: Request,
99
- * error: Error,
100
- * session: Session,
101
- * crawler: BasicCrawler,
102
- * }
103
- * ```
104
- * where the {@link Request} instance corresponds to the failed request, and the `Error` instance
79
+ * The function receives the {@link BasicCrawlingContext} as the first argument,
80
+ * where the {@link BasicCrawlingContext.request} corresponds to the request to be retried.
81
+ * Second argument is the `Error` instance that
105
82
  * represents the last error thrown during processing of the request.
106
- *
107
- * See
108
- * [source code](https://github.com/apify/apify-js/blob/master/src/crawlers/basic_crawler.js#L11)
109
- * for the default implementation of this function.
110
83
  */
111
- failedRequestHandler?: FailedRequestHandler<ErrorContext>;
84
+ errorHandler?: FailedRequestHandler<Context>;
112
85
  /**
113
86
  * A function to handle requests that failed more than `option.maxRequestRetries` times.
114
87
  *
115
- * The function receives the following object as an argument:
116
- * ```
117
- * {
118
- * request: Request,
119
- * error: Error,
120
- * session: Session,
121
- * crawler: BasicCrawler,
122
- * }
123
- * ```
124
- * where the {@link Request} instance corresponds to the failed request, and the `Error` instance
88
+ * The function receives the {@link BasicCrawlingContext} as the first argument,
89
+ * where the {@link BasicCrawlingContext.request} corresponds to the failed request.
90
+ * Second argument is the `Error` instance that
125
91
  * represents the last error thrown during processing of the request.
92
+ */
93
+ failedRequestHandler?: FailedRequestHandler<Context>;
94
+ /**
95
+ * A function to handle requests that failed more than `option.maxRequestRetries` times.
126
96
  *
127
- * See
128
- * [source code](https://github.com/apify/apify-js/blob/master/src/crawlers/basic_crawler.js#L11)
129
- * for the default implementation of this function.
97
+ * The function receives the {@link BasicCrawlingContext} as the first argument,
98
+ * where the {@link BasicCrawlingContext.request} corresponds to the failed request.
99
+ * Second argument is the `Error` instance that
100
+ * represents the last error thrown during processing of the request.
130
101
  *
131
102
  * @deprecated `handleFailedRequestFunction` has been renamed to `failedRequestHandler` and will be removed in a future version.
132
103
  */
133
- handleFailedRequestFunction?: FailedRequestHandler<ErrorContext>;
104
+ handleFailedRequestFunction?: FailedRequestHandler<Context>;
134
105
  /**
135
- * Indicates how many times the request is retried if {@link requestHandler} or {@link handlePageFunction} fails.
106
+ * Indicates how many times the request is retried if {@link requestHandler} fails.
136
107
  * @default 3
137
108
  */
138
109
  maxRequestRetries?: number;
@@ -203,16 +174,13 @@ export interface BasicCrawlerOptions<Context extends CrawlingContext = BasicCraw
203
174
  * **Example usage:**
204
175
  *
205
176
  * ```javascript
206
- * const { gotScraping } = require('got-scraping');
177
+ * import { gotScraping } from 'got-scraping';
207
178
  *
208
179
  * // Prepare a list of URLs to crawl
209
- * const requestList = new RequestList({
210
- * sources: [
211
- * { url: 'http://www.example.com/page-1' },
212
- * { url: 'http://www.example.com/page-2' },
213
- * ],
214
- * });
215
- * await requestList.initialize();
180
+ * const requestList = await RequestList.open(null, [
181
+ * { url: 'http://www.example.com/page-1' },
182
+ * { url: 'http://www.example.com/page-2' },
183
+ * ]);
216
184
  *
217
185
  * // Crawl the URLs
218
186
  * const crawler = new BasicCrawler({
@@ -227,7 +195,7 @@ export interface BasicCrawlerOptions<Context extends CrawlingContext = BasicCraw
227
195
  * headers: request.headers,
228
196
  * });
229
197
  *
230
- * await Actor.pushData({
198
+ * await Dataset.pushData({
231
199
  * url: request.url,
232
200
  * html: body,
233
201
  * })
@@ -238,8 +206,9 @@ export interface BasicCrawlerOptions<Context extends CrawlingContext = BasicCraw
238
206
  * ```
239
207
  * @category Crawlers
240
208
  */
241
- export declare class BasicCrawler<Context extends CrawlingContext = BasicCrawlerCrawlingContext, ErrorContext extends CrawlerHandleFailedRequestInput = BasicCrawlerHandleFailedRequestInput> {
209
+ export declare class BasicCrawler<Context extends CrawlingContext = BasicCrawlingContext> {
242
210
  readonly config: Configuration;
211
+ private static readonly CRAWLEE_STATE_KEY;
243
212
  /**
244
213
  * Static list of URLs to be processed.
245
214
  */
@@ -270,9 +239,15 @@ export declare class BasicCrawler<Context extends CrawlingContext = BasicCrawler
270
239
  * or to abort it by calling {@link AutoscaledPool.abort}.
271
240
  */
272
241
  autoscaledPool?: AutoscaledPool;
242
+ /**
243
+ * Default router instance that will be used if we don't specify any {@link requestHandler}.
244
+ * See {@link Router.addHandler} and {@link Router.addDefaultHandler.}
245
+ */
246
+ readonly router: RouterHandler<Context>;
273
247
  protected log: Log;
274
248
  protected requestHandler: RequestHandler<Context>;
275
- protected failedRequestHandler?: FailedRequestHandler<ErrorContext>;
249
+ protected errorHandler?: FailedRequestHandler<Context>;
250
+ protected failedRequestHandler?: FailedRequestHandler<Context>;
276
251
  protected requestHandlerTimeoutMillis: number;
277
252
  protected internalTimeoutMillis: number;
278
253
  protected maxRequestRetries: number;
@@ -282,6 +257,7 @@ export declare class BasicCrawler<Context extends CrawlingContext = BasicCrawler
282
257
  protected crawlingContexts: Map<string, Context>;
283
258
  protected autoscaledPoolOptions: AutoscaledPoolOptions;
284
259
  protected events: EventManager;
260
+ private _closeEvents?;
285
261
  protected static optionsShape: {
286
262
  requestList: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
287
263
  requestQueue: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
@@ -289,6 +265,7 @@ export declare class BasicCrawler<Context extends CrawlingContext = BasicCrawler
289
265
  handleRequestFunction: import("ow").Predicate<Function> & import("ow").BasePredicate<Function | undefined>;
290
266
  requestHandlerTimeoutSecs: import("ow").NumberPredicate & import("ow").BasePredicate<number | undefined>;
291
267
  handleRequestTimeoutSecs: import("ow").NumberPredicate & import("ow").BasePredicate<number | undefined>;
268
+ errorHandler: import("ow").Predicate<Function> & import("ow").BasePredicate<Function | undefined>;
292
269
  failedRequestHandler: import("ow").Predicate<Function> & import("ow").BasePredicate<Function | undefined>;
293
270
  handleFailedRequestFunction: import("ow").Predicate<Function> & import("ow").BasePredicate<Function | undefined>;
294
271
  maxRequestRetries: import("ow").NumberPredicate & import("ow").BasePredicate<number | undefined>;
@@ -303,12 +280,13 @@ export declare class BasicCrawler<Context extends CrawlingContext = BasicCrawler
303
280
  /**
304
281
  * All `BasicCrawler` parameters are passed via an options object.
305
282
  */
306
- constructor(options: BasicCrawlerOptions<Context, ErrorContext>, config?: Configuration);
283
+ constructor(options?: BasicCrawlerOptions<Context>, config?: Configuration);
307
284
  /**
308
285
  * Runs the crawler. Returns a promise that gets resolved once all the requests are processed.
309
286
  */
310
287
  run(): Promise<FinalStatistics>;
311
288
  getRequestQueue(): Promise<RequestQueue>;
289
+ useState<State extends Dictionary = Dictionary>(defaultValue?: State): Promise<State>;
312
290
  /**
313
291
  * Adds requests to be processed by the crawler
314
292
  * @param requests The requests to add
@@ -326,7 +304,7 @@ export declare class BasicCrawler<Context extends CrawlingContext = BasicCrawler
326
304
  * Fetches request from either RequestList or RequestQueue. If request comes from a RequestList
327
305
  * and RequestQueue is present then enqueues it to the queue first.
328
306
  */
329
- protected _fetchNextRequest(): Promise<Request | null>;
307
+ protected _fetchNextRequest(): Promise<Request<Dictionary<any>> | null>;
330
308
  /**
331
309
  * Wrapper around requestHandler that fetches requests from RequestList/RequestQueue
332
310
  * then retries them in a case of an error, etc.
@@ -349,7 +327,7 @@ export declare class BasicCrawler<Context extends CrawlingContext = BasicCrawler
349
327
  * Handles errors thrown by user provided requestHandler()
350
328
  */
351
329
  protected _requestFunctionErrorHandler(error: Error, crawlingContext: Context, source: RequestList | RequestQueue): Promise<void>;
352
- protected _handleFailedRequestHandler(crawlingContext: ErrorContext): Promise<void>;
330
+ protected _handleFailedRequestHandler(crawlingContext: Context, error: Error): Promise<void>;
353
331
  /**
354
332
  * Updates handledRequestsCount from possibly stored counts,
355
333
  * usually after worker migration. Since one of the stores
@@ -406,5 +384,30 @@ interface HandlePropertyNameChangeData<New, Old> {
406
384
  propertyKey: string;
407
385
  allowUndefined?: boolean;
408
386
  }
387
+ /**
388
+ * Creates new {@link Router} instance that works based on request labels.
389
+ * This instance can then serve as a `requestHandler` of your {@link BasicCrawler}.
390
+ * Defaults to the {@link BasicCrawlingContext}.
391
+ *
392
+ * > Serves as a shortcut for using `Router.create<BasicCrawlingContext>()`.
393
+ *
394
+ * ```ts
395
+ * import { BasicCrawler, createBasicRouter } from 'crawlee';
396
+ *
397
+ * const router = createBasicRouter();
398
+ * router.addHandler('label-a', async (ctx) => {
399
+ * ctx.log.info('...');
400
+ * });
401
+ * router.addDefaultHandler(async (ctx) => {
402
+ * ctx.log.info('...');
403
+ * });
404
+ *
405
+ * const crawler = new BasicCrawler({
406
+ * requestHandler: router,
407
+ * });
408
+ * await crawler.run();
409
+ * ```
410
+ */
411
+ export declare function createBasicRouter<Context extends BasicCrawlingContext = BasicCrawlingContext>(): RouterHandler<Context>;
409
412
  export {};
410
413
  //# sourceMappingURL=basic-crawler.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"basic-crawler.d.ts","sourceRoot":"","sources":["../../src/internals/basic-crawler.ts"],"names":[],"mappings":"AAAA,OAAmB,EAAE,GAAG,EAAE,MAAM,YAAY,CAAC;AAG7C,OAAO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E,OAAO,CAAC;IACjB,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,SAAS,CAAC,EAAE,SAAS,CAAC;CACzB;AAED,MAAM,WAAW,yBAA0B,SAAQ,4BAA4B;IAC3E;;;;OAIG;IACH,2BAA2B,CAAC,EAAE,OAAO,CAAC;CACzC;AAED,MAAM,WAAW,wBAAwB;IACrC,aAAa,EAAE,gBAAgB,EAAE,CAAC;IAClC;;;;;;;;;;;;OAYG;IACH,2BAA2B,EAAE,OAAO,CAAC,gBAAgB,EAAE,CAAC,CAAC;CAC5D;AAED,UAAU,4BAA4B,CAAC,GAAG,EAAE,GAAG;IAC3C,WAAW,CAAC,EAAE,GAAG,CAAC;IAClB,WAAW,CAAC,EAAE,GAAG,CAAC;IAClB,OAAO,EAAE,MAAM,CAAC;IAChB,OAAO,EAAE,MAAM,CAAC;IAChB,WAAW,EAAE,MAAM,CAAC;IACpB,cAAc,CAAC,EAAE,OAAO,CAAC;CAC5B;AAED;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,wBAAgB,iBAAiB,CAAC,OAAO,SAAS,oBAAoB,GAAG,oBAAoB,4BAE5F"}
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.BasicCrawler = void 0;
3
+ exports.createBasicRouter = exports.BasicCrawler = void 0;
4
4
  const tslib_1 = require("tslib");
5
5
  const log_1 = tslib_1.__importDefault(require("@apify/log"));
6
6
  const timeout_1 = require("@apify/timeout");
@@ -50,16 +50,13 @@ const SAFE_MIGRATION_WAIT_MILLIS = 20000;
50
50
  * **Example usage:**
51
51
  *
52
52
  * ```javascript
53
- * const { gotScraping } = require('got-scraping');
53
+ * import { gotScraping } from 'got-scraping';
54
54
  *
55
55
  * // Prepare a list of URLs to crawl
56
- * const requestList = new RequestList({
57
- * sources: [
58
- * { url: 'http://www.example.com/page-1' },
59
- * { url: 'http://www.example.com/page-2' },
60
- * ],
61
- * });
62
- * await requestList.initialize();
56
+ * const requestList = await RequestList.open(null, [
57
+ * { url: 'http://www.example.com/page-1' },
58
+ * { url: 'http://www.example.com/page-2' },
59
+ * ]);
63
60
  *
64
61
  * // Crawl the URLs
65
62
  * const crawler = new BasicCrawler({
@@ -74,7 +71,7 @@ const SAFE_MIGRATION_WAIT_MILLIS = 20000;
74
71
  * headers: request.headers,
75
72
  * });
76
73
  *
77
- * await Actor.pushData({
74
+ * await Dataset.pushData({
78
75
  * url: request.url,
79
76
  * html: body,
80
77
  * })
@@ -89,7 +86,7 @@ class BasicCrawler {
89
86
  /**
90
87
  * All `BasicCrawler` parameters are passed via an options object.
91
88
  */
92
- constructor(options, config = core_1.Configuration.getGlobalConfig()) {
89
+ constructor(options = {}, config = core_1.Configuration.getGlobalConfig()) {
93
90
  Object.defineProperty(this, "config", {
94
91
  enumerable: true,
95
92
  configurable: true,
@@ -151,6 +148,16 @@ class BasicCrawler {
151
148
  writable: true,
152
149
  value: void 0
153
150
  });
151
+ /**
152
+ * Default router instance that will be used if we don't specify any {@link requestHandler}.
153
+ * See {@link Router.addHandler} and {@link Router.addDefaultHandler.}
154
+ */
155
+ Object.defineProperty(this, "router", {
156
+ enumerable: true,
157
+ configurable: true,
158
+ writable: true,
159
+ value: core_1.Router.create()
160
+ });
154
161
  Object.defineProperty(this, "log", {
155
162
  enumerable: true,
156
163
  configurable: true,
@@ -163,6 +170,12 @@ class BasicCrawler {
163
170
  writable: true,
164
171
  value: void 0
165
172
  });
173
+ Object.defineProperty(this, "errorHandler", {
174
+ enumerable: true,
175
+ configurable: true,
176
+ writable: true,
177
+ value: void 0
178
+ });
166
179
  Object.defineProperty(this, "failedRequestHandler", {
167
180
  enumerable: true,
168
181
  configurable: true,
@@ -223,6 +236,12 @@ class BasicCrawler {
223
236
  writable: true,
224
237
  value: void 0
225
238
  });
239
+ Object.defineProperty(this, "_closeEvents", {
240
+ enumerable: true,
241
+ configurable: true,
242
+ writable: true,
243
+ value: void 0
244
+ });
226
245
  (0, ow_1.default)(options, 'BasicCrawlerOptions', ow_1.default.object.exactShape(BasicCrawler.optionsShape));
227
246
  const { requestList, requestQueue, maxRequestRetries = 3, maxRequestsPerCrawl, autoscaledPoolOptions = {}, sessionPoolOptions = {}, useSessionPool = true,
228
247
  // AutoscaledPool shorthands
@@ -230,7 +249,7 @@ class BasicCrawler {
230
249
  // internal
231
250
  log = log_1.default.child({ prefix: this.constructor.name }),
232
251
  // Old and new request handler methods
233
- handleRequestFunction, requestHandler, handleRequestTimeoutSecs, requestHandlerTimeoutSecs, handleFailedRequestFunction, failedRequestHandler, } = options;
252
+ handleRequestFunction, requestHandler, handleRequestTimeoutSecs, requestHandlerTimeoutSecs, errorHandler, handleFailedRequestFunction, failedRequestHandler, } = options;
234
253
  this.requestList = requestList;
235
254
  this.requestQueue = requestQueue;
236
255
  this.log = log;
@@ -241,7 +260,12 @@ class BasicCrawler {
241
260
  propertyKey: 'requestHandler',
242
261
  newProperty: requestHandler,
243
262
  oldProperty: handleRequestFunction,
263
+ allowUndefined: true, // fallback to the default router
244
264
  });
265
+ if (!this.requestHandler) {
266
+ this.requestHandler = this.router;
267
+ }
268
+ this.errorHandler = errorHandler;
245
269
  this._handlePropertyNameChange({
246
270
  newName: 'failedRequestHandler',
247
271
  oldName: 'handleFailedRequestFunction',
@@ -338,6 +362,7 @@ class BasicCrawler {
338
362
  * Runs the crawler. Returns a promise that gets resolved once all the requests are processed.
339
363
  */
340
364
  async run() {
365
+ await (0, core_1.purgeDefaultStorages)();
341
366
  await this._init();
342
367
  await this.stats.startCapturing();
343
368
  try {
@@ -361,6 +386,10 @@ class BasicCrawler {
361
386
  this.requestQueue ?? (this.requestQueue = await core_1.RequestQueue.open());
362
387
  return this.requestQueue;
363
388
  }
389
+ async useState(defaultValue = {}) {
390
+ const kvs = await core_1.KeyValueStore.open(null, { config: this.config });
391
+ return kvs.getAutoSavedValue(BasicCrawler.CRAWLEE_STATE_KEY, defaultValue);
392
+ }
364
393
  /**
365
394
  * Adds requests to be processed by the crawler
366
395
  * @param requests The requests to add
@@ -417,6 +446,10 @@ class BasicCrawler {
417
446
  };
418
447
  }
419
448
  async _init() {
449
+ if (!this.events.isInitialized()) {
450
+ await this.events.init();
451
+ this._closeEvents = true;
452
+ }
420
453
  // Initialize AutoscaledPool before awaiting _loadHandledRequestCount(),
421
454
  // so that the caller can get a reference to it before awaiting the promise returned from run()
422
455
  // (otherwise there would be no way)
@@ -540,22 +573,24 @@ class BasicCrawler {
540
573
  requestQueue: await this.getRequestQueue(),
541
574
  });
542
575
  },
543
- sendRequest: async (req) => {
544
- req ?? (req = request);
576
+ sendRequest: async (overrideOptions) => {
545
577
  return (0, got_scraping_1.gotScraping)({
546
- url: req.url,
547
- method: req.method,
548
- body: req.payload,
549
- headers: req.headers,
550
- retry: {
551
- limit: 0,
552
- },
578
+ url: request.url,
579
+ method: request.method,
580
+ body: request.payload,
581
+ headers: request.headers,
553
582
  proxyUrl: crawlingContext.proxyInfo?.url,
554
583
  sessionToken: session,
555
584
  responseType: 'text',
585
+ ...overrideOptions,
586
+ retry: {
587
+ limit: 0,
588
+ ...overrideOptions?.retry,
589
+ },
556
590
  cookieJar: {
557
591
  getCookieString: (url) => session.getCookieString(url),
558
592
  setCookie: (rawCookie, url) => session.setCookie(rawCookie, url),
593
+ ...overrideOptions?.cookieJar,
559
594
  },
560
595
  });
561
596
  },
@@ -631,13 +666,18 @@ class BasicCrawler {
631
666
  async _requestFunctionErrorHandler(error, crawlingContext, source) {
632
667
  const { request } = crawlingContext;
633
668
  request.pushErrorMessage(error);
634
- const shouldRetryRequest = !request.noRetry && request.retryCount < this.maxRequestRetries;
669
+ if (error instanceof core_1.CriticalError) {
670
+ throw error;
671
+ }
672
+ const shouldRetryRequest = !request.noRetry && request.retryCount < this.maxRequestRetries && !(error instanceof core_1.NonRetryableError);
635
673
  if (shouldRetryRequest) {
636
674
  request.retryCount++;
675
+ await this.errorHandler?.(crawlingContext, error);
637
676
  const { url, retryCount, id } = request;
638
677
  // We don't want to see the stack trace in the logs by default, when we are going to retry the request.
639
678
  // Thus, we print the full stack trace only when CRAWLEE_VERBOSE_LOG environment variable is set to true.
640
- this.log.warning(`Reclaiming failed request back to the list or queue. ${!process.env.CRAWLEE_VERBOSE_LOG ? error : error.stack}`, { id, url, retryCount });
679
+ const message = !process.env.CRAWLEE_VERBOSE_LOG ? error : error.stack;
680
+ this.log.warning(`Reclaiming failed request back to the list or queue. ${message}`, { id, url, retryCount });
641
681
  await source.reclaimRequest(request);
642
682
  }
643
683
  else {
@@ -647,21 +687,17 @@ class BasicCrawler {
647
687
  this.handledRequestsCount++;
648
688
  await source.markRequestHandled(request);
649
689
  this.stats.failJob(request.id || request.uniqueKey);
650
- // @ts-expect-error It is assignable, but TS says otherwise...
651
- const castedErrorContext = crawlingContext;
652
- castedErrorContext.error = error;
653
- await this._handleFailedRequestHandler(castedErrorContext); // This function prints an error message.
690
+ await this._handleFailedRequestHandler(crawlingContext, error); // This function prints an error message.
654
691
  }
655
692
  }
656
- async _handleFailedRequestHandler(crawlingContext) {
693
+ async _handleFailedRequestHandler(crawlingContext, error) {
657
694
  if (this.failedRequestHandler) {
658
- await this.failedRequestHandler(crawlingContext);
695
+ await this.failedRequestHandler(crawlingContext, error);
659
696
  }
660
697
  else {
661
698
  const { id, url, method, uniqueKey } = crawlingContext.request;
662
- this.log.error(`Request failed and reached maximum retries. ${crawlingContext.error instanceof timeout_1.TimeoutError && !process.env.CRAWLEE_VERBOSE_LOG
663
- ? crawlingContext.error.message
664
- : crawlingContext.error.stack}`, { id, url, method, uniqueKey });
699
+ const message = error instanceof timeout_1.TimeoutError && !process.env.CRAWLEE_VERBOSE_LOG ? error.message : error.stack;
700
+ this.log.error(`Request failed and reached maximum retries. ${message}`, { id, url, method, uniqueKey });
665
701
  }
666
702
  }
667
703
  /**
@@ -692,9 +728,13 @@ class BasicCrawler {
692
728
  * @ignore
693
729
  */
694
730
  async teardown() {
731
+ this.events.emit("persistState" /* EventType.PERSIST_STATE */, { isMigrating: false });
695
732
  if (this.useSessionPool) {
696
733
  await this.sessionPool.teardown();
697
734
  }
735
+ if (this._closeEvents) {
736
+ await this.events.close();
737
+ }
698
738
  }
699
739
  _handlePropertyNameChange({ newProperty, newName, oldProperty, oldName, propertyKey, allowUndefined = false, }) {
700
740
  if (newProperty && oldProperty) {
@@ -727,6 +767,12 @@ class BasicCrawler {
727
767
  }
728
768
  }
729
769
  exports.BasicCrawler = BasicCrawler;
770
+ Object.defineProperty(BasicCrawler, "CRAWLEE_STATE_KEY", {
771
+ enumerable: true,
772
+ configurable: true,
773
+ writable: true,
774
+ value: 'CRAWLEE_STATE'
775
+ });
730
776
  Object.defineProperty(BasicCrawler, "optionsShape", {
731
777
  enumerable: true,
732
778
  configurable: true,
@@ -737,13 +783,13 @@ Object.defineProperty(BasicCrawler, "optionsShape", {
737
783
  // Subclasses override this function instead of passing it
738
784
  // in constructor, so this validation needs to apply only
739
785
  // if the user creates an instance of BasicCrawler directly.
740
- // TODO: remove .optional from requestHandler once migration period is over
741
786
  requestHandler: ow_1.default.optional.function,
742
787
  // TODO: remove in a future release
743
788
  handleRequestFunction: ow_1.default.optional.function,
744
789
  requestHandlerTimeoutSecs: ow_1.default.optional.number,
745
790
  // TODO: remove in a future release
746
791
  handleRequestTimeoutSecs: ow_1.default.optional.number,
792
+ errorHandler: ow_1.default.optional.function,
747
793
  failedRequestHandler: ow_1.default.optional.function,
748
794
  // TODO: remove in a future release
749
795
  handleFailedRequestFunction: ow_1.default.optional.function,
@@ -759,4 +805,32 @@ Object.defineProperty(BasicCrawler, "optionsShape", {
759
805
  log: ow_1.default.optional.object,
760
806
  }
761
807
  });
808
+ /**
809
+ * Creates new {@link Router} instance that works based on request labels.
810
+ * This instance can then serve as a `requestHandler` of your {@link BasicCrawler}.
811
+ * Defaults to the {@link BasicCrawlingContext}.
812
+ *
813
+ * > Serves as a shortcut for using `Router.create<BasicCrawlingContext>()`.
814
+ *
815
+ * ```ts
816
+ * import { BasicCrawler, createBasicRouter } from 'crawlee';
817
+ *
818
+ * const router = createBasicRouter();
819
+ * router.addHandler('label-a', async (ctx) => {
820
+ * ctx.log.info('...');
821
+ * });
822
+ * router.addDefaultHandler(async (ctx) => {
823
+ * ctx.log.info('...');
824
+ * });
825
+ *
826
+ * const crawler = new BasicCrawler({
827
+ * requestHandler: router,
828
+ * });
829
+ * await crawler.run();
830
+ * ```
831
+ */
832
+ function createBasicRouter() {
833
+ return core_1.Router.create();
834
+ }
835
+ exports.createBasicRouter = createBasicRouter;
762
836
  //# sourceMappingURL=basic-crawler.js.map