@crawlee/http 4.0.0-beta.99 → 4.0.0-rc.1

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.
package/README.md CHANGED
@@ -34,7 +34,7 @@ Crawlee is available as the [`crawlee`](https://www.npmjs.com/package/crawlee) N
34
34
 
35
35
  We recommend visiting the [Introduction tutorial](https://crawlee.dev/js/docs/introduction) in Crawlee documentation for more information.
36
36
 
37
- > Crawlee requires **Node.js 16 or higher**.
37
+ > Crawlee requires **Node.js 22.13 or higher**.
38
38
 
39
39
  ### With Crawlee CLI
40
40
 
package/index.d.ts CHANGED
@@ -1,3 +1,4 @@
1
1
  export * from '@crawlee/basic';
2
2
  export * from './internals/http-crawler.js';
3
+ export * from './internals/dom-crawler.js';
3
4
  export * from './internals/file-download.js';
package/index.js CHANGED
@@ -1,3 +1,4 @@
1
1
  export * from '@crawlee/basic';
2
2
  export * from './internals/http-crawler.js';
3
+ export * from './internals/dom-crawler.js';
3
4
  export * from './internals/file-download.js';
@@ -0,0 +1,131 @@
1
+ import type { AddRequestsBatchedResult, ContextPipeline, CrawlingContext, EnqueueLinksOptions, ExtractLinksOptions, GetUserDataFromRequest } from '@crawlee/basic';
2
+ import type { Awaitable, Dictionary } from '@crawlee/types';
3
+ import type { CheerioAPI } from 'cheerio';
4
+ import type { HttpCrawlerOptions, InternalHttpCrawlingContext } from './http-crawler.js';
5
+ import { HttpCrawler } from './http-crawler.js';
6
+ /**
7
+ * The minimum a {@link DOMParser} has to contribute to the crawling context - the serialized document, used by
8
+ * the {@link DOMCrawlingContext.parseWithCheerio|`parseWithCheerio`} helper.
9
+ */
10
+ export interface DOMParseResult {
11
+ body: string;
12
+ }
13
+ /**
14
+ * Turns a response body into a DOM representation and knows how to query it. Passing one to {@link DOMCrawler}
15
+ * is what makes the crawler jsdom-based, linkedom-based, or based on a DOM implementation of your own.
16
+ *
17
+ * **Example usage:**
18
+ * ```ts
19
+ * import { DOMCrawler } from 'crawlee';
20
+ * import type { DOMParser } from 'crawlee';
21
+ *
22
+ * const myParser: DOMParser<{ body: string }> = {
23
+ * // ...
24
+ * };
25
+ *
26
+ * const crawler = new DOMCrawler({
27
+ * parser: myParser,
28
+ * async requestHandler({ body }) {
29
+ * // ...
30
+ * },
31
+ * });
32
+ * ```
33
+ */
34
+ export interface DOMParser<Parsed extends DOMParseResult> {
35
+ /**
36
+ * The context members {@link DOMParser.parse|`parse`} contributes, mapped to `true`. Used to build the
37
+ * placeholders that report a helpful error when the members are accessed after `skipNavigation` - the `Record`
38
+ * type forces every key of `Parsed` to be listed, so the compiler catches an omission that would otherwise
39
+ * yield `undefined` (rather than throwing) after `skipNavigation`.
40
+ */
41
+ readonly placeholderMembers: Record<keyof Parsed & string, true>;
42
+ parse(context: InternalHttpCrawlingContext): Awaitable<Parsed>;
43
+ /**
44
+ * Returns the URLs the `selector` matches, resolved against `baseUrl`.
45
+ */
46
+ extractLinks(parsed: Parsed, selector: string, baseUrl: string): Awaitable<string[]>;
47
+ /**
48
+ * Returns the current matches of `selector`. Only the count is used, by
49
+ * {@link DOMCrawlingContext.waitForSelector|`waitForSelector`}.
50
+ */
51
+ select(parsed: Parsed, selector: string): Awaitable<ArrayLike<unknown>>;
52
+ /**
53
+ * Whether the parse result can change after {@link DOMParser.parse|`parse`} returned - the case when the DOM
54
+ * implementation runs the page scripts. If it can, {@link DOMCrawlingContext.waitForSelector|`waitForSelector`}
55
+ * polls until the timeout elapses; otherwise it fails as soon as the selector does not match.
56
+ */
57
+ readonly mutable?: boolean;
58
+ /**
59
+ * Returns a Cheerio handle over the parse result, for parsers that are backed by Cheerio anyway. Without it,
60
+ * {@link DOMCrawlingContext.parseWithCheerio|`parseWithCheerio`} parses
61
+ * {@link DOMParseResult.body|`body`} again.
62
+ */
63
+ toCheerio?(parsed: Parsed): Awaitable<CheerioAPI>;
64
+ /**
65
+ * Releases whatever {@link DOMParser.parse|`parse`} allocated. Called after the request handler finishes or
66
+ * fails, and skipped entirely when navigation was skipped.
67
+ */
68
+ cleanup?(parsed: Parsed): Awaitable<void>;
69
+ }
70
+ export interface DOMCrawlingHelpers {
71
+ /**
72
+ * Extracts URLs from the parsed DOM, without adding them to the request queue.
73
+ */
74
+ extractLinks(options?: ExtractLinksOptions): Promise<string[]>;
75
+ /**
76
+ * Helper function for extracting URLs from the parsed DOM and adding them to the request queue.
77
+ */
78
+ enqueueLinks(options?: EnqueueLinksOptions): Promise<AddRequestsBatchedResult>;
79
+ /**
80
+ * Wait for an element matching the selector to appear. The `timeoutMs` only has an effect when the parser is
81
+ * {@link DOMParser.mutable|`mutable`} (e.g. {@link JSDOMCrawler} with `runScripts: true`); otherwise the
82
+ * selector is checked once and the call resolves or throws immediately.
83
+ * Timeout defaults to 5s.
84
+ *
85
+ * **Example usage:**
86
+ * ```ts
87
+ * async requestHandler({ waitForSelector, parseWithCheerio }) {
88
+ * await waitForSelector('article h1');
89
+ * const $ = await parseWithCheerio();
90
+ * const title = $('title').text();
91
+ * });
92
+ * ```
93
+ */
94
+ waitForSelector(selector: string, timeoutMs?: number): Promise<void>;
95
+ /**
96
+ * Returns Cheerio handle, allowing to work with the data same way as with {@link CheerioCrawler}.
97
+ * When provided with the `selector` argument, it will throw if it's not available.
98
+ *
99
+ * **Example usage:**
100
+ * ```javascript
101
+ * async requestHandler({ parseWithCheerio }) {
102
+ * const $ = await parseWithCheerio();
103
+ * const title = $('title').text();
104
+ * });
105
+ * ```
106
+ */
107
+ parseWithCheerio(selector?: string, timeoutMs?: number): Promise<CheerioAPI>;
108
+ }
109
+ export type DOMCrawlingContext<Parsed extends DOMParseResult = DOMParseResult, UserData extends Dictionary = any, // with default to Dictionary we cant use a typed router in untyped crawler
110
+ JSONData extends Dictionary = any> = InternalHttpCrawlingContext<UserData, JSONData> & Parsed & DOMCrawlingHelpers;
111
+ export interface DOMCrawlerOptions<Parsed extends DOMParseResult = DOMParseResult, ContextExtension = Dictionary<never>, ExtendedContext extends DOMCrawlingContext<Parsed> = DOMCrawlingContext<Parsed> & ContextExtension, Routes extends Record<keyof Routes, Dictionary> = Record<string, any>, StatisticStateExtension extends object = {}> extends Omit<HttpCrawlerOptions<DOMCrawlingContext<Parsed>, ContextExtension, ExtendedContext, Routes, StatisticStateExtension>, 'contextPipelineBuilder'> {
112
+ /**
113
+ * The DOM implementation to parse the response bodies with. Its parse result becomes part of the crawling
114
+ * context, so the members the request handler receives follow from the parser you pass.
115
+ */
116
+ parser: DOMParser<Parsed>;
117
+ }
118
+ /**
119
+ * An {@link HttpCrawler} that parses each response into a DOM using the {@link DOMCrawlerOptions.parser|`parser`}
120
+ * it is given, and exposes the parse result plus the {@link DOMCrawlingContext.enqueueLinks|`enqueueLinks`} and
121
+ * {@link DOMCrawlingContext.extractLinks|`extractLinks`} helpers on the crawling context.
122
+ *
123
+ * {@link JSDOMCrawler} and {@link LinkeDOMCrawler} are this crawler with a parser already chosen.
124
+ *
125
+ * @category Crawlers
126
+ */
127
+ export declare class DOMCrawler<Parsed extends DOMParseResult = DOMParseResult, ContextExtension = Dictionary<never>, ExtendedContext extends DOMCrawlingContext<Parsed> = DOMCrawlingContext<Parsed> & ContextExtension, Routes extends Record<keyof Routes, Dictionary> = Record<string, GetUserDataFromRequest<DOMCrawlingContext<Parsed>['request']>>, StatisticStateExtension extends object = {}> extends HttpCrawler<DOMCrawlingContext<Parsed>, ContextExtension, ExtendedContext, Routes, StatisticStateExtension> {
128
+ #private;
129
+ constructor(options: DOMCrawlerOptions<Parsed, ContextExtension, ExtendedContext, Routes, StatisticStateExtension>);
130
+ protected buildContextPipeline(): ContextPipeline<CrawlingContext, DOMCrawlingContext<Parsed>>;
131
+ }
@@ -0,0 +1,93 @@
1
+ import { EnqueueStrategy, NavigationSkippedError, resolveBaseUrlForEnqueueLinksFiltering } from '@crawlee/basic';
2
+ import { sleep } from '@crawlee/utils';
3
+ import { HttpCrawler } from './http-crawler.js';
4
+ /**
5
+ * An {@link HttpCrawler} that parses each response into a DOM using the {@link DOMCrawlerOptions.parser|`parser`}
6
+ * it is given, and exposes the parse result plus the {@link DOMCrawlingContext.enqueueLinks|`enqueueLinks`} and
7
+ * {@link DOMCrawlingContext.extractLinks|`extractLinks`} helpers on the crawling context.
8
+ *
9
+ * {@link JSDOMCrawler} and {@link LinkeDOMCrawler} are this crawler with a parser already chosen.
10
+ *
11
+ * @category Crawlers
12
+ */
13
+ export class DOMCrawler extends HttpCrawler {
14
+ #parser;
15
+ constructor(options) {
16
+ const { parser, ...rest } = options;
17
+ super({ ...rest, contextPipelineBuilder: () => this.buildContextPipeline() });
18
+ this.#parser = parser;
19
+ }
20
+ buildContextPipeline() {
21
+ return super
22
+ .buildContextPipeline()
23
+ .compose(this.#parseContent.bind(this))
24
+ .compose(async (context) => this.#addHelpers(context));
25
+ }
26
+ async #parseContent(context, onCleanup) {
27
+ try {
28
+ const parsed = await this.#parser.parse(context);
29
+ onCleanup(() => this.#parser.cleanup?.(parsed));
30
+ return parsed;
31
+ }
32
+ catch (err) {
33
+ // The `skipNavigation` placeholders below throw on access, so there is nothing to clean up.
34
+ if (err instanceof NavigationSkippedError) {
35
+ return Object.defineProperties({}, Object.fromEntries(Object.keys(this.#parser.placeholderMembers).map((member) => [
36
+ member,
37
+ {
38
+ configurable: true,
39
+ enumerable: true,
40
+ get() {
41
+ throw new NavigationSkippedError(`The \`${member}\` property is not available - \`skipNavigation\` was used`, { cause: err });
42
+ },
43
+ },
44
+ ])));
45
+ }
46
+ throw err;
47
+ }
48
+ }
49
+ async #addHelpers(context) {
50
+ const { addRequests } = context;
51
+ const parser = this.#parser;
52
+ const extractLinks = async (options) => parser.extractLinks(context, options?.selector ?? 'a', options?.baseUrl ?? context.request.loadedUrl ?? context.request.url);
53
+ const waitForSelector = async (selector, timeoutMs = 5_000) => {
54
+ let remaining = parser.mutable ? timeoutMs : 0;
55
+ while ((await parser.select(context, selector)).length === 0) {
56
+ if (remaining <= 0) {
57
+ throw new Error(`Selector '${selector}' not found.`);
58
+ }
59
+ await sleep(50);
60
+ remaining -= 50;
61
+ }
62
+ };
63
+ return {
64
+ extractLinks,
65
+ waitForSelector,
66
+ enqueueLinks: async (options = {}) => {
67
+ const baseUrl = resolveBaseUrlForEnqueueLinksFiltering({
68
+ enqueueStrategy: options.strategy,
69
+ finalRequestUrl: context.request.loadedUrl,
70
+ originalRequestUrl: context.request.url,
71
+ userProvidedBaseUrl: options.baseUrl,
72
+ });
73
+ const urls = await extractLinks(options);
74
+ return addRequests(urls, {
75
+ ...options,
76
+ baseUrl,
77
+ strategy: options.strategy ?? EnqueueStrategy.SameHostname,
78
+ });
79
+ },
80
+ async parseWithCheerio(selector, _timeoutMs = 5_000) {
81
+ // Import full cheerio (not cheerio/slim) to be browser-compliant for DOM Crawlers (not CheerioCrawler).
82
+ const $ = (await parser.toCheerio?.(context)) ??
83
+ (await import('cheerio')).load(context.body, {
84
+ xmlMode: context.contentType.type.includes('xml'),
85
+ });
86
+ if (selector && $(selector).get().length === 0) {
87
+ throw new Error(`Selector '${selector}' not found.`);
88
+ }
89
+ return $;
90
+ },
91
+ };
92
+ }
93
+ }
@@ -1,16 +1,11 @@
1
- import { Transform } from 'node:stream';
2
- import type { BasicCrawlerOptions } from '@crawlee/basic';
1
+ import type { BasicCrawlerOptions, CrawlingContext, CrawlingRequest, LoadedRequest } from '@crawlee/basic';
3
2
  import { BasicCrawler } from '@crawlee/basic';
4
- import type { CrawlingContext, LoadedRequest, Request } from '@crawlee/core';
5
- import { ResponseWithUrl } from '@crawlee/http-client';
6
3
  import type { Dictionary } from '@crawlee/types';
7
- import type { ErrorHandler, GetUserDataFromRequest, InternalHttpHook, RequestHandler, RouterRoutes } from '../index.js';
8
- declare const kBodyDrained: unique symbol;
4
+ import type { ErrorHandler, GetUserDataFromRequest, RequestHandler, RouterHandler, RouterRoutes, RouteSchemas, RoutesFromSchemas } from '../index.js';
9
5
  export type FileDownloadErrorHandler<UserData extends Dictionary = any, // with default to Dictionary we cant use a typed router in untyped crawler
10
6
  ContextExtension = Dictionary<never>> = ErrorHandler<CrawlingContext, FileDownloadCrawlingContext<UserData> & ContextExtension>;
11
- export type FileDownloadHook<UserData extends Dictionary = any> = InternalHttpHook<FileDownloadCrawlingContext<UserData>>;
12
7
  export interface FileDownloadCrawlingContext<UserData extends Dictionary = any> extends CrawlingContext<UserData> {
13
- request: LoadedRequest<Request<UserData>>;
8
+ request: LoadedRequest<CrawlingRequest<UserData>>;
14
9
  response: Response;
15
10
  contentType: {
16
11
  type: string;
@@ -18,31 +13,6 @@ export interface FileDownloadCrawlingContext<UserData extends Dictionary = any>
18
13
  };
19
14
  }
20
15
  export type FileDownloadRequestHandler<UserData extends Dictionary = any> = RequestHandler<FileDownloadCrawlingContext<UserData>>;
21
- /**
22
- * Creates a transform stream that throws an error if the source data speed is below the specified minimum speed.
23
- * This `Transform` checks the amount of data every `checkProgressInterval` milliseconds.
24
- * If the stream has received less than `minSpeedKbps * historyLengthMs / 1000` bytes in the last `historyLengthMs` milliseconds,
25
- * it will throw an error.
26
- *
27
- * Can be used e.g. to abort a download if the network speed is too slow.
28
- * @returns Transform stream that monitors the speed of the incoming data.
29
- */
30
- export declare function MinimumSpeedStream({ minSpeedKbps, historyLengthMs, checkProgressInterval: checkProgressIntervalMs, }: {
31
- minSpeedKbps: number;
32
- historyLengthMs?: number;
33
- checkProgressInterval?: number;
34
- }): Transform;
35
- /**
36
- * Creates a transform stream that logs the progress of the incoming data.
37
- * This `Transform` calls the `logProgress` function every `loggingInterval` milliseconds with the number of bytes received so far.
38
- *
39
- * Can be used e.g. to log the progress of a download.
40
- * @returns Transform stream logging the progress of the incoming data.
41
- */
42
- export declare function ByteCounterStream({ logTransferredBytes, loggingInterval, }: {
43
- logTransferredBytes: (transferredBytes: number) => void;
44
- loggingInterval?: number;
45
- }): Transform;
46
16
  /**
47
17
  * Provides a framework for downloading files in parallel using plain HTTP requests. The URLs to download are fed either from a static list of URLs or they can be added on the fly from another crawler.
48
18
  *
@@ -50,24 +20,14 @@ export declare function ByteCounterStream({ logTransferredBytes, loggingInterval
50
20
  * However, it doesn't parse the content - if you need to e.g. extract data from the downloaded files,
51
21
  * you might need to use {@link CheerioCrawler}, {@link PuppeteerCrawler} or {@link PlaywrightCrawler} instead.
52
22
  *
53
- * `FileCrawler` downloads each URL using a plain HTTP request and then invokes the user-provided {@link FileDownloadOptions.requestHandler} where the user can specify what to do with the downloaded data.
23
+ * `FileCrawler` downloads each URL using a plain HTTP request and then invokes the user-provided {@link BasicCrawlerOptions.requestHandler} where the user can specify what to do with the downloaded data.
54
24
  *
55
- * The source URLs are represented using {@link Request} objects that are fed from the {@link IRequestManager|request manager} provided via the {@link FileDownloadOptions.requestManager|`requestManager`} constructor option (a {@link RequestQueue} is itself a request manager). To read from a read-only source such as a {@link RequestList} while still being able to enqueue new requests, combine it with a queue into a {@link RequestManagerTandem} via {@link IRequestLoader.toTandem|`requestLoader.toTandem()`} and pass the result as `requestManager`.
25
+ * The source URLs are represented using {@link Request} objects that are fed from the {@link IRequestManager|request manager} provided via the {@link BasicCrawlerOptions.requestManager|`requestManager`} constructor option (a {@link RequestQueue} is itself a request manager). To read from a read-only source such as a {@link RequestList} while still being able to enqueue new requests, combine it with a queue into a {@link RequestManagerTandem} via {@link IRequestLoader.toTandem|`requestLoader.toTandem()`} and pass the result as `requestManager`.
56
26
  *
57
- * > The {@link FileDownloadOptions.requestList|`requestList`} and {@link FileDownloadOptions.requestQueue|`requestQueue`} options are deprecated; they are still accepted and folded into a single `requestManager` for back-compat.
27
+ * > The {@link BasicCrawlerOptions.requestList|`requestList`} and {@link BasicCrawlerOptions.requestQueue|`requestQueue`} options are deprecated; they are still accepted and folded into a single `requestManager` for back-compat.
58
28
  *
59
29
  * The crawler finishes when there are no more {@link Request} objects to crawl.
60
30
  *
61
- * We can use the `preNavigationHooks` to adjust the crawling context before the request is made:
62
- *
63
- * ```
64
- * preNavigationHooks: [
65
- * (crawlingContext) => {
66
- * // ...
67
- * },
68
- * ]
69
- * ```
70
- *
71
31
  * New requests are only dispatched when there is enough free CPU and memory available, as judged by the crawler's {@link ConcurrencySystem}. Concurrency is tuned via the `minConcurrency`, `maxConcurrency` and `maxRequestsPerMinute` options of the `FileCrawler` constructor, or, for finer control, by injecting a pre-configured {@link ConcurrencySystem|`concurrencySystem`}.
72
32
  *
73
33
  * ## Example usage
@@ -87,18 +47,8 @@ export declare function ByteCounterStream({ logTransferredBytes, loggingInterval
87
47
  * ```
88
48
  */
89
49
  export declare class FileDownload extends BasicCrawler<FileDownloadCrawlingContext> {
90
- constructor(options?: BasicCrawlerOptions<FileDownloadCrawlingContext>);
91
- // @ts-ignore optional peer dependency or compatibility with es2022
92
- protected buildContextPipeline(): import("@crawlee/basic").ContextPipeline<CrawlingContext<Dictionary>, CrawlingContext<Dictionary> & {
93
- request: LoadedRequest<Request>;
94
- response: ResponseWithUrl;
95
- contentType: {
96
- type: string;
97
- encoding: BufferEncoding;
98
- };
99
- [kBodyDrained]: Promise<void>;
100
- }>;
101
- private initiateDownload;
50
+ #private;
51
+ constructor(options?: Omit<BasicCrawlerOptions<FileDownloadCrawlingContext>, 'contextPipelineBuilder'>);
102
52
  }
103
53
  /**
104
54
  * Creates new {@link Router} instance that works based on request labels.
@@ -124,6 +74,6 @@ export declare class FileDownload extends BasicCrawler<FileDownloadCrawlingConte
124
74
  * await crawler.run();
125
75
  * ```
126
76
  */
127
- // @ts-ignore optional peer dependency or compatibility with es2022
128
- export declare function createFileRouter<Context extends FileDownloadCrawlingContext = FileDownloadCrawlingContext, UserData extends Dictionary = GetUserDataFromRequest<Context['request']>>(routes?: RouterRoutes<Context, UserData>): import("@crawlee/basic").RouterHandler<Context, Record<string, GetUserDataFromRequest<Context["request"]>>>;
129
- export {};
77
+ export declare function createFileRouter<Context extends FileDownloadCrawlingContext = FileDownloadCrawlingContext, Routes extends Record<keyof Routes, Dictionary> = Record<string, GetUserDataFromRequest<Context['request']>>>(routes?: RouterRoutes<Context, Routes>): RouterHandler<Context, Routes>;
78
+ export declare function createFileRouter<Context extends FileDownloadCrawlingContext = FileDownloadCrawlingContext, UserData extends Dictionary = GetUserDataFromRequest<Context['request']>>(routes?: RouterRoutes<Context, Record<string, UserData>>): RouterHandler<Context, Record<string, UserData>>;
79
+ export declare function createFileRouter<Context extends FileDownloadCrawlingContext = FileDownloadCrawlingContext, const Schemas extends RouteSchemas = RouteSchemas>(schemas: Schemas): RouterHandler<Context, RoutesFromSchemas<Schemas>>;
@@ -1,67 +1,7 @@
1
- import { Transform } from 'node:stream';
2
- import { BasicCrawler } from '@crawlee/basic';
1
+ import { BasicCrawler, ContextPipeline } from '@crawlee/basic';
3
2
  import { ResponseWithUrl } from '@crawlee/http-client';
4
3
  import { Router } from '../index.js';
5
4
  import { parseContentTypeFromResponse } from './utils.js';
6
- const kBodyDrained = Symbol('bodyDrained');
7
- /**
8
- * Creates a transform stream that throws an error if the source data speed is below the specified minimum speed.
9
- * This `Transform` checks the amount of data every `checkProgressInterval` milliseconds.
10
- * If the stream has received less than `minSpeedKbps * historyLengthMs / 1000` bytes in the last `historyLengthMs` milliseconds,
11
- * it will throw an error.
12
- *
13
- * Can be used e.g. to abort a download if the network speed is too slow.
14
- * @returns Transform stream that monitors the speed of the incoming data.
15
- */
16
- export function MinimumSpeedStream({ minSpeedKbps, historyLengthMs = 10e3, checkProgressInterval: checkProgressIntervalMs = 5e3, }) {
17
- let snapshots = [];
18
- const checkInterval = setInterval(() => {
19
- const now = Date.now();
20
- snapshots = snapshots.filter((snapshot) => now - snapshot.timestamp < historyLengthMs);
21
- const totalBytes = snapshots.reduce((acc, snapshot) => acc + snapshot.bytes, 0);
22
- const elapsed = (now - (snapshots[0]?.timestamp ?? 0)) / 1000;
23
- if (totalBytes / 1024 / elapsed < minSpeedKbps) {
24
- clearInterval(checkInterval);
25
- stream.emit('error', new Error(`Stream speed too slow, aborting...`));
26
- }
27
- }, checkProgressIntervalMs);
28
- const stream = new Transform({
29
- transform: (chunk, _, callback) => {
30
- snapshots.push({ timestamp: Date.now(), bytes: chunk.length });
31
- callback(null, chunk);
32
- },
33
- final: (callback) => {
34
- clearInterval(checkInterval);
35
- callback();
36
- },
37
- });
38
- return stream;
39
- }
40
- /**
41
- * Creates a transform stream that logs the progress of the incoming data.
42
- * This `Transform` calls the `logProgress` function every `loggingInterval` milliseconds with the number of bytes received so far.
43
- *
44
- * Can be used e.g. to log the progress of a download.
45
- * @returns Transform stream logging the progress of the incoming data.
46
- */
47
- export function ByteCounterStream({ logTransferredBytes, loggingInterval = 5000, }) {
48
- let transferredBytes = 0;
49
- let lastLogTime = Date.now();
50
- return new Transform({
51
- transform: (chunk, _, callback) => {
52
- transferredBytes += chunk.length;
53
- if (Date.now() - lastLogTime > loggingInterval) {
54
- lastLogTime = Date.now();
55
- logTransferredBytes(transferredBytes);
56
- }
57
- callback(null, chunk);
58
- },
59
- flush: (callback) => {
60
- logTransferredBytes(transferredBytes);
61
- callback();
62
- },
63
- });
64
- }
65
5
  /**
66
6
  * Provides a framework for downloading files in parallel using plain HTTP requests. The URLs to download are fed either from a static list of URLs or they can be added on the fly from another crawler.
67
7
  *
@@ -69,24 +9,14 @@ export function ByteCounterStream({ logTransferredBytes, loggingInterval = 5000,
69
9
  * However, it doesn't parse the content - if you need to e.g. extract data from the downloaded files,
70
10
  * you might need to use {@link CheerioCrawler}, {@link PuppeteerCrawler} or {@link PlaywrightCrawler} instead.
71
11
  *
72
- * `FileCrawler` downloads each URL using a plain HTTP request and then invokes the user-provided {@link FileDownloadOptions.requestHandler} where the user can specify what to do with the downloaded data.
12
+ * `FileCrawler` downloads each URL using a plain HTTP request and then invokes the user-provided {@link BasicCrawlerOptions.requestHandler} where the user can specify what to do with the downloaded data.
73
13
  *
74
- * The source URLs are represented using {@link Request} objects that are fed from the {@link IRequestManager|request manager} provided via the {@link FileDownloadOptions.requestManager|`requestManager`} constructor option (a {@link RequestQueue} is itself a request manager). To read from a read-only source such as a {@link RequestList} while still being able to enqueue new requests, combine it with a queue into a {@link RequestManagerTandem} via {@link IRequestLoader.toTandem|`requestLoader.toTandem()`} and pass the result as `requestManager`.
14
+ * The source URLs are represented using {@link Request} objects that are fed from the {@link IRequestManager|request manager} provided via the {@link BasicCrawlerOptions.requestManager|`requestManager`} constructor option (a {@link RequestQueue} is itself a request manager). To read from a read-only source such as a {@link RequestList} while still being able to enqueue new requests, combine it with a queue into a {@link RequestManagerTandem} via {@link IRequestLoader.toTandem|`requestLoader.toTandem()`} and pass the result as `requestManager`.
75
15
  *
76
- * > The {@link FileDownloadOptions.requestList|`requestList`} and {@link FileDownloadOptions.requestQueue|`requestQueue`} options are deprecated; they are still accepted and folded into a single `requestManager` for back-compat.
16
+ * > The {@link BasicCrawlerOptions.requestList|`requestList`} and {@link BasicCrawlerOptions.requestQueue|`requestQueue`} options are deprecated; they are still accepted and folded into a single `requestManager` for back-compat.
77
17
  *
78
18
  * The crawler finishes when there are no more {@link Request} objects to crawl.
79
19
  *
80
- * We can use the `preNavigationHooks` to adjust the crawling context before the request is made:
81
- *
82
- * ```
83
- * preNavigationHooks: [
84
- * (crawlingContext) => {
85
- * // ...
86
- * },
87
- * ]
88
- * ```
89
- *
90
20
  * New requests are only dispatched when there is enough free CPU and memory available, as judged by the crawler's {@link ConcurrencySystem}. Concurrency is tuned via the `minConcurrency`, `maxConcurrency` and `maxRequestsPerMinute` options of the `FileCrawler` constructor, or, for finer control, by injecting a pre-configured {@link ConcurrencySystem|`concurrencySystem`}.
91
21
  *
92
22
  * ## Example usage
@@ -110,36 +40,32 @@ export class FileDownload extends BasicCrawler {
110
40
  constructor(options = {}) {
111
41
  super({
112
42
  ...options,
113
- contextPipelineBuilder: () => this.buildContextPipeline(),
43
+ contextPipelineBuilder: () => this.#buildContextPipeline(),
114
44
  });
115
45
  }
116
- buildContextPipeline() {
117
- return super.buildContextPipeline().compose({
118
- action: async (context) => this.initiateDownload(context),
119
- cleanup: async (context) => {
120
- if (!context.response.bodyUsed) {
121
- // Nobody consumed the body — cancel it so the
122
- // underlying connection can be released.
123
- await context.response.body?.cancel();
124
- }
125
- await context[kBodyDrained];
126
- },
127
- });
46
+ #buildContextPipeline() {
47
+ return ContextPipeline.create().compose(this.#initiateDownload.bind(this));
128
48
  }
129
- async initiateDownload(context) {
49
+ async #initiateDownload(context, onCleanup) {
130
50
  const response = await this.httpClient.sendRequest(context.request.intoFetchAPIRequest(), {
131
51
  session: context.session,
132
52
  });
133
53
  const { type, charset: encoding } = parseContentTypeFromResponse(response);
134
54
  context.request.url = response.url;
135
55
  const { response: trackedResponse, bodyDrained } = trackBodyConsumption(response);
136
- const contextExtension = {
56
+ onCleanup(async () => {
57
+ if (!trackedResponse.bodyUsed) {
58
+ // Nobody consumed the body — cancel it so the
59
+ // underlying connection can be released.
60
+ await trackedResponse.body?.cancel();
61
+ }
62
+ await bodyDrained;
63
+ });
64
+ return {
137
65
  request: context.request,
138
66
  response: trackedResponse,
139
67
  contentType: { type, encoding },
140
- [kBodyDrained]: bodyDrained,
141
68
  };
142
- return contextExtension;
143
69
  }
144
70
  }
145
71
  /**
@@ -162,30 +88,6 @@ function trackBodyConsumption(response) {
162
88
  });
163
89
  return { response: trackedResponse, bodyDrained };
164
90
  }
165
- /**
166
- * Creates new {@link Router} instance that works based on request labels.
167
- * This instance can then serve as a `requestHandler` of your {@link FileDownload}.
168
- * Defaults to the {@link FileDownloadCrawlingContext}.
169
- *
170
- * > Serves as a shortcut for using `Router.create<FileDownloadCrawlingContext>()`.
171
- *
172
- * ```ts
173
- * import { FileDownload, createFileRouter } from 'crawlee';
174
- *
175
- * const router = createFileRouter();
176
- * router.addHandler('label-a', async (ctx) => {
177
- * ctx.log.info('...');
178
- * });
179
- * router.addDefaultHandler(async (ctx) => {
180
- * ctx.log.info('...');
181
- * });
182
- *
183
- * const crawler = new FileDownload({
184
- * requestHandler: router,
185
- * });
186
- * await crawler.run();
187
- * ```
188
- */
189
- export function createFileRouter(routes) {
190
- return Router.create(routes);
91
+ export function createFileRouter(routesOrSchemas) {
92
+ return Router.create(routesOrSchemas);
191
93
  }