Crawlee—A web scraping and browser automation library for Node.js to build reliable crawlers. In JavaScript and TypeScript. Extract data for AI, LLMs, RAG, or GPTs. Download HTML, PDF, JPG, PNG, and other files from websites. Works with Puppeteer, Playwright, Cheerio, JSDOM, and raw HTTP. Both headful and headless mode. With proxy rotation.
TypeScript apifyautomationcrawlercrawlingheadlessheadless-chromejavascriptnodejsnpmplaywrightpuppeteerscraperscrapingtypescriptweb-crawlerweb-crawlingweb-scraping
feat: custom `httpClient` implementation for `@crawlee/utils` and `Request` storages (#3306)
Jindřich Bärb96749ddf216
diff --git a/docs/guides/custom-http-client/custom-http-client.mdx b/docs/guides/custom-http-client/custom-http-client.mdxindex c593ec3ba..8000f3b86 100644--- a/docs/guides/custom-http-client/custom-http-client.mdx+++ b/docs/guides/custom-http-client/custom-http-client.mdx@@ -12,7 +12,7 @@ import UsageSource from '!!raw-loader!./usage.ts';The <ApiLink to="basic-crawler/class/BasicCrawler">`BasicCrawler`</ApiLink> class allows you to configure the HTTP client implementation using the `httpClient` constructor option. This might be useful for testing or if you need to swap out the default implementation based on `got-scraping` for something else, such as `curl-impersonate` or `axios`.-The HTTP client implementation needs to conform to the <ApiLink to="core/interface/BaseHttpClient">`BaseHttpClient`</ApiLink> interface. For a rough idea on how it might look, see a skeleton implementation that uses the standard `fetch` interface:+The HTTP client implementation needs to conform to the <ApiLink to="types/interface/BaseHttpClient">`BaseHttpClient`</ApiLink> interface. For a rough idea on how it might look, see a skeleton implementation that uses the standard `fetch` interface:<CodeBlock language="ts">{ImplementationSource}</CodeBlock>diff --git a/docs/guides/custom-http-client/implementation.ts b/docs/guides/custom-http-client/implementation.tsindex 9d4988647..bf999683f 100644--- a/docs/guides/custom-http-client/implementation.ts+++ b/docs/guides/custom-http-client/implementation.ts@@ -1,4 +1,4 @@-import type { BaseHttpClient, SendRequestOptions, StreamOptions } from '@crawlee/core';+import type { BaseHttpClient, SendRequestOptions, StreamOptions } from '@crawlee/types';export class FetchHttpClient implements BaseHttpClient {async sendRequest(request: Request, options?: SendRequestOptions): Promise<Response> {diff --git a/docs/guides/proxy_management.mdx b/docs/guides/proxy_management.mdxindex 853042064..70dce2f72 100644--- a/docs/guides/proxy_management.mdx+++ b/docs/guides/proxy_management.mdx@@ -200,7 +200,7 @@ Each call to <ApiLink to="core/class/ProxyConfiguration#newUrl">`proxyConfigurat## Inspecting current proxy in Crawlers`HttpCrawler`, `CheerioCrawler`, `JSDOMCrawler`, `PlaywrightCrawler` and `PuppeteerCrawler` grant access to information about the currently used proxy-in their `requestHandler` using a <ApiLink to="core/interface/ProxyInfo">`proxyInfo`</ApiLink> object.+in their `requestHandler` using a <ApiLink to="types/interface/ProxyInfo">`proxyInfo`</ApiLink> object.With the `proxyInfo` object, we can easily access the proxy URL.<Tabs groupId="proxy_session_management">diff --git a/package.json b/package.jsonindex 54db2fbc9..588be6428 100644--- a/package.json+++ b/package.json@@ -103,9 +103,9 @@"got": "^14.4.7","husky": "^9.1.7","is-ci": "^4.1.0",- "lerna": "^9.0.7",+ "lerna": "^9.0.0","lint-staged": "^17.0.0",- "nock": "^13.5.6",+ "nock": "^14.0.10","playwright": "1.61.1","portastic": "^1.0.1","proxy": "^2.2.0",diff --git a/packages/basic-crawler/src/internals/basic-crawler.ts b/packages/basic-crawler/src/internals/basic-crawler.tsindex ab9079a12..647bf09d6 100644--- a/packages/basic-crawler/src/internals/basic-crawler.ts+++ b/packages/basic-crawler/src/internals/basic-crawler.ts@@ -5,7 +5,6 @@ import type {AddRequestsBatchedOptions,AddRequestsBatchedResult,AutoscaledPoolOptions,- BaseHttpClient,CrawlingContext,DatasetExportOptions,EnqueueLinksOptions,@@ -15,7 +14,6 @@ import type {IRequestList,IRequestManager,ProxyConfiguration,- ProxyInfo,Request,RequestsLike,RequestTransform,@@ -60,7 +58,14 @@ import {validateUserData,validators,} from '@crawlee/core';-import type { Awaitable, BatchAddRequestsResult, Dictionary, SetStatusMessageOptions } from '@crawlee/types';+import type {+ Awaitable,+ BaseHttpClient,+ BatchAddRequestsResult,+ Dictionary,+ ProxyInfo,+ SetStatusMessageOptions,+} from '@crawlee/types';import { getObjectType, isAsyncIterable, isIterable, RobotsTxtFile, ROTATE_PROXY_ERRORS, sleep } from '@crawlee/utils';import { stringify } from 'csv-stringify/sync';import { ensureDir, writeJSON } from 'fs-extra/esm';diff --git a/packages/basic-crawler/src/internals/send-request.ts b/packages/basic-crawler/src/internals/send-request.tsindex 889bd305c..e8d8b5608 100644--- a/packages/basic-crawler/src/internals/send-request.ts+++ b/packages/basic-crawler/src/internals/send-request.ts@@ -1,4 +1,5 @@-import { type BaseHttpClient, type HttpRequestOptions, type Request, type Session } from '@crawlee/core';+import type { Request, Session } from '@crawlee/core';+import type { BaseHttpClient, HttpRequestOptions } from '@crawlee/types';/*** Prepares a function to be used as the `sendRequest` context helper.diff --git a/packages/browser-crawler/src/internals/browser-crawler.ts b/packages/browser-crawler/src/internals/browser-crawler.tsindex b27493957..98c8ef518 100644--- a/packages/browser-crawler/src/internals/browser-crawler.ts+++ b/packages/browser-crawler/src/internals/browser-crawler.ts@@ -7,7 +7,6 @@ import type {EnqueueLinksOptions,ErrorHandler,LoadedRequest,- ProxyInfo,Request,RequestHandler,RequestProvider,@@ -39,7 +38,7 @@ import type {LaunchContext,} from '@crawlee/browser-pool';import { BROWSER_CONTROLLER_EVENTS, BrowserPool } from '@crawlee/browser-pool';-import type { BatchAddRequestsResult, Cookie as CookieObject } from '@crawlee/types';+import type { BatchAddRequestsResult, Cookie as CookieObject, ProxyInfo } from '@crawlee/types';import type { RobotsTxtFile } from '@crawlee/utils';import { CLOUDFLARE_RETRY_CSS_SELECTORS, RETRY_CSS_SELECTORS, sleep } from '@crawlee/utils';import ow from 'ow';diff --git a/packages/core/src/crawlers/crawler_commons.ts b/packages/core/src/crawlers/crawler_commons.tsindex e2e3e7570..d3f4f6591 100644--- a/packages/core/src/crawlers/crawler_commons.ts+++ b/packages/core/src/crawlers/crawler_commons.ts@@ -1,11 +1,10 @@-import type { Dictionary } from '@crawlee/types';+import type { Dictionary, ProxyInfo } from '@crawlee/types';import type { OptionsInit } from 'got-scraping';import type { ReadonlyDeep, SetRequired } from 'type-fest';import type { Configuration } from '../configuration.js';import type { EnqueueLinksOptions } from '../enqueue_links/enqueue_links.js';import type { Log } from '../log.js';-import type { ProxyInfo } from '../proxy_configuration.js';import type { Request, Source } from '../request.js';import type { Session } from '../session_pool/session.js';import type { Dataset } from '../storages/dataset.js';diff --git a/packages/core/src/http_clients/base-http-client.ts b/packages/core/src/http_clients/base-http-client.tsindex 3addb1267..44ae444de 100644--- a/packages/core/src/http_clients/base-http-client.ts+++ b/packages/core/src/http_clients/base-http-client.ts@@ -1,81 +1,9 @@import { Readable } from 'node:stream';-import type { AllowedHttpMethods } from '@crawlee/types';-import { applySearchParams, type SearchParams } from '@crawlee/utils';+import type { HttpRequest, HttpRequestOptions, IResponseWithUrl } from '@crawlee/types';+import { applySearchParams } from '@crawlee/utils';-import type { Session } from '../session_pool/session.js';--// TODO BC with got - remove the options and callback parameters in 4.0-interface ToughCookieJar {- getCookieString: ((- currentUrl: string,- options: Record<string, unknown>,- callback: (error: Error | null, cookies: string) => void,- ) => string) &- ((url: string, callback: (error: Error | null, cookieHeader: string) => void) => string);- setCookie: ((- cookieOrString: unknown,- currentUrl: string,- options: Record<string, unknown>,- callback: (error: Error | null, cookie: unknown) => void,- ) => void) &- ((rawCookie: string, url: string, callback: (error: Error | null, result: unknown) => void) => void);-}--interface PromiseCookieJar {- getCookieString: (url: string) => Promise<string>;- setCookie: (rawCookie: string, url: string) => Promise<unknown>;-}--/**- * HTTP Request as accepted by {@apilink BaseHttpClient} methods.- */-export interface HttpRequest {- url: string | URL;- method?: AllowedHttpMethods;- headers?: Headers;- body?: Readable;-- signal?: AbortSignal;- timeout?: number;-- cookieJar?: ToughCookieJar | PromiseCookieJar;- followRedirect?: boolean | ((response: any) => boolean); // TODO BC with got - specify type better in 4.0- maxRedirects?: number;-- encoding?: BufferEncoding;- throwHttpErrors?: boolean;-- // from got-scraping Context- proxyUrl?: string;- headerGeneratorOptions?: Record<string, unknown>;- useHeaderGenerator?: boolean;- headerGenerator?: {- getHeaders: (options: Record<string, unknown>) => Record<string, string>;- };- insecureHTTPParser?: boolean;- sessionToken?: object;-}--/**- * Additional options for HTTP requests that need to be handled separately before passing to {@apilink BaseHttpClient}.- */-export interface HttpRequestOptions extends HttpRequest {- /** Search (query string) parameters to be appended to the request URL */- searchParams?: SearchParams;-- /** A form to be sent in the HTTP request body (URL encoding will be used) */- form?: Record<string, string>;- /** Artbitrary object to be JSON-serialized and sent as the HTTP request body */- json?: unknown;-- /** Basic HTTP Auth username */- username?: string;- /** Basic HTTP Auth password */- password?: string;-}--export class ResponseWithUrl extends Response {+export class ResponseWithUrl extends Response implements IResponseWithUrl {override url: string;constructor(body: BodyInit | null, init: ResponseInit & { url?: string }) {super(body, init);@@ -83,39 +11,6 @@ export class ResponseWithUrl extends Response {}}-/**- * Type of a function called when an HTTP redirect takes place. It is allowed to mutate the `updatedRequest` argument.- */-export type RedirectHandler = (- redirectResponse: Response,- updatedRequest: { url?: string | URL; headers: Headers },-) => void;--export interface SendRequestOptions {- session?: Session;- cookieJar?: ToughCookieJar;- timeout?: number;-}--export interface StreamOptions extends SendRequestOptions {- onRedirect?: RedirectHandler;-}--/**- * Interface for user-defined HTTP clients to be used for plain HTTP crawling and for sending additional requests during a crawl.- */-export interface BaseHttpClient {- /**- * Perform an HTTP Request and return the complete response.- */- sendRequest(request: Request, options?: SendRequestOptions): Promise<Response>;-- /**- * Perform an HTTP Request and return after the response headers are received. The body may be read from a stream contained in the response.- */- stream(request: Request, options?: StreamOptions): Promise<Response>;-}-/*** Converts {@apilink HttpRequestOptions} to a {@apilink HttpRequest}.*/diff --git a/packages/core/src/http_clients/got-scraping-http-client.ts b/packages/core/src/http_clients/got-scraping-http-client.tsindex caf40e77d..f0c9c4e11 100644--- a/packages/core/src/http_clients/got-scraping-http-client.ts+++ b/packages/core/src/http_clients/got-scraping-http-client.ts@@ -1,9 +1,9 @@import { Readable } from 'node:stream';+import type { BaseHttpClient, SendRequestOptions, StreamOptions } from '@crawlee/types';import type { Options, PlainResponse } from 'got-scraping';import { gotScraping } from 'got-scraping';-import type { BaseHttpClient, SendRequestOptions, StreamOptions } from './base-http-client.js';import { ResponseWithUrl } from './base-http-client.js';/**@@ -47,7 +47,7 @@ export class GotScrapingHttpClient implements BaseHttpClient {* @inheritDoc*/async sendRequest(request: Request, options?: SendRequestOptions): Promise<Response> {- const { session, timeout } = options ?? {};+ const { session, timeout, proxyUrl } = options ?? {};if (!this.validateRequest(request)) {throw new Error(`The HTTP method CONNECT is not supported by the GotScrapingHttpClient.`);@@ -58,7 +58,7 @@ export class GotScrapingHttpClient implements BaseHttpClient {method: request.method as Options['method'],headers: Object.fromEntries(request.headers.entries()),body: request.body ? Readable.fromWeb(request.body as any) : undefined,- proxyUrl: session?.proxyInfo?.url,+ proxyUrl: proxyUrl ?? session?.proxyInfo?.url,timeout: { request: timeout },// We set cookieJar to undefined because// `HttpCrawler` reads the cookies beforehand and sets them in `request.headers`.diff --git a/packages/core/src/proxy_configuration.ts b/packages/core/src/proxy_configuration.tsindex cc9ede3ce..b16f8de04 100644--- a/packages/core/src/proxy_configuration.ts+++ b/packages/core/src/proxy_configuration.ts@@ -1,4 +1,4 @@-import type { Dictionary } from '@crawlee/types';+import type { Dictionary, ProxyInfo } from '@crawlee/types';import ow from 'ow';import log from '@apify/log';@@ -46,72 +46,6 @@ export interface TieredProxy {proxyTier?: number;}-/**- * The main purpose of the ProxyInfo object is to provide information- * about the current proxy connection used by the crawler for the request.- * Outside of crawlers, you can get this object by calling {@apilink ProxyConfiguration.newProxyInfo}.- *- * **Example usage:**- *- * ```javascript- * const proxyConfiguration = new ProxyConfiguration({- * proxyUrls: ['...', '...'] // List of Proxy URLs to rotate- * });- *- * // Getting proxyInfo object by calling class method directly- * const proxyInfo = await proxyConfiguration.newProxyInfo();- *- * // In crawler- * const crawler = new CheerioCrawler({- * // ...- * proxyConfiguration,- * requestHandler({ proxyInfo }) {- * // Getting used proxy URL- * const proxyUrl = proxyInfo.url;- * }- * })- *- * ```- */-export interface ProxyInfo {- /**- * The URL of the proxy.- */- url: string;-- /**- * Username for the proxy.- */- username?: string;-- /**- * User's password for the proxy.- */- password: string;-- /**- * Hostname of your proxy.- */- hostname: string;-- /**- * Proxy port.- */- port: number | string;-- /**- * Proxy tier for the current proxy, if applicable (only for `tieredProxyUrls`).- */- proxyTier?: number;-- /**- * When `true`, the proxy is likely intercepting HTTPS traffic and is able to view and modify its content.- *- * @default false- */- ignoreTlsErrors?: boolean;-}-interface TieredProxyOptions {request?: Request;proxyTier?: number;diff --git a/packages/core/src/session_pool/session.ts b/packages/core/src/session_pool/session.tsindex fc5d8aa36..95c5cd737 100644--- a/packages/core/src/session_pool/session.ts+++ b/packages/core/src/session_pool/session.ts@@ -1,8 +1,8 @@import { EventEmitter } from 'node:events';-import type { Cookie as CookieObject, Dictionary } from '@crawlee/types';+import type { Cookie as CookieObject, Dictionary, ISession, ProxyInfo, SessionState } from '@crawlee/types';import ow from 'ow';-import type { Cookie, SerializedCookieJar } from 'tough-cookie';+import type { Cookie } from 'tough-cookie';import { CookieJar } from 'tough-cookie';import type { Log } from '@apify/log';@@ -15,26 +15,8 @@ import {toughCookieToBrowserPoolCookie,} from '../cookie_utils.js';import { log as defaultLog } from '../log.js';-import type { ProxyInfo } from '../proxy_configuration.js';import { EVENT_SESSION_RETIRED } from './events.js';-/**- * Persistable {@apilink Session} state.- */-export interface SessionState {- id: string;- cookieJar: SerializedCookieJar;- proxyInfo?: ProxyInfo;- userData: object;- errorScore: number;- maxErrorScore: number;- errorScoreDecrement: number;- usageCount: number;- maxUsageCount: number;- expiresAt: string;- createdAt: string;-}-export interface SessionOptions {/** Id of session used for generating fingerprints. It is used as proxy session name. */id?: string;@@ -99,7 +81,7 @@ export interface SessionOptions {* Session internal state can be enriched with custom user data for example some authorization tokens and specific headers in general.* @category Scaling*/-export class Session {+export class Session implements ISession {readonly id: string;private maxAgeSecs: number;userData: Dictionary;diff --git a/packages/core/src/storages/request_list.ts b/packages/core/src/storages/request_list.tsindex 83dd883e2..1ce31de34 100644--- a/packages/core/src/storages/request_list.ts+++ b/packages/core/src/storages/request_list.ts@@ -1,4 +1,4 @@-import type { Dictionary } from '@crawlee/types';+import type { BaseHttpClient, Dictionary } from '@crawlee/types';import { downloadListOfUrls } from '@crawlee/utils';import ow, { ArgumentError } from 'ow';@@ -234,6 +234,13 @@ export interface RequestListOptions {/** @internal */config?: Configuration;++ /**+ * The HTTP client to be used to download `requestsFromUrl` URLs.+ *+ * If not specified the `RequestList` will use the default HTTP client.+ */+ httpClient?: BaseHttpClient;}/**@@ -348,6 +355,7 @@ export class RequestList implements IRequestList {private sourcesFunction?: RequestListSourcesFunction;private proxyConfiguration?: ProxyConfiguration;private events: EventManager;+ private httpClient?: BaseHttpClient;/*** To create new instance of `RequestList` we need to use `RequestList.open()` factory method.@@ -364,6 +372,7 @@ export class RequestList implements IRequestList {proxyConfiguration,keepDuplicateUrls = false,config = Configuration.getGlobalConfig(),+ httpClient,} = options;if (!(sources || sourcesFunction)) {@@ -386,6 +395,7 @@ export class RequestList implements IRequestList {}),keepDuplicateUrls: ow.optional.boolean,proxyConfiguration: ow.optional.object,+ httpClient: ow.optional.object,}),);@@ -393,6 +403,7 @@ export class RequestList implements IRequestList {this.persistRequestsKey = persistRequestsKey ? `SDK_${persistRequestsKey}` : persistRequestsKey;this.initialState = state;this.events = config.getEventManager();+ this.httpClient = httpClient;// If this option is set then all requests will get a pre-generated unique ID and duplicate URLs will be kept in the list.this.keepDuplicateUrls = keepDuplicateUrls;@@ -985,7 +996,10 @@ export class RequestList implements IRequestList {urlRegExp?: RegExp;proxyUrl?: string;}): Promise<string[]> {- return downloadListOfUrls(options);+ return downloadListOfUrls({+ ...options,+ httpClient: this.httpClient,+ });}}diff --git a/packages/core/src/storages/request_provider.ts b/packages/core/src/storages/request_provider.tsindex ff915aa2a..385b7631c 100644--- a/packages/core/src/storages/request_provider.ts+++ b/packages/core/src/storages/request_provider.ts@@ -1,6 +1,7 @@import { inspect } from 'node:util';import type {+ BaseHttpClient,BatchAddRequestsResult,Dictionary,ProcessedRequest,@@ -147,6 +148,8 @@ export abstract class RequestProvider implements IStorage, IRequestManager {protected inProgressRequestBatchCount = 0;+ protected httpClient?: BaseHttpClient;+constructor(options: InternalRequestProviderOptions,readonly config = Configuration.getGlobalConfig(),@@ -920,7 +923,10 @@ export abstract class RequestProvider implements IStorage, IRequestManager {urlRegExp?: RegExp;proxyUrl?: string;}): Promise<string[]> {- return downloadListOfUrls(options);+ return downloadListOfUrls({+ ...options,+ httpClient: this.httpClient,+ });}/**@@ -949,6 +955,7 @@ export abstract class RequestProvider implements IStorage, IRequestManager {config: ow.optional.object.instanceOf(Configuration),storageClient: ow.optional.object,proxyConfiguration: ow.optional.object,+ httpClient: ow.optional.object,}),);@@ -965,6 +972,7 @@ export abstract class RequestProvider implements IStorage, IRequestManager {queue.initialCount = queueInfo?.totalRequestCount ?? 0;queue.initialHandledCount = queueInfo?.handledRequestCount ?? 0;+ queue.httpClient = options.httpClient;return queue;}diff --git a/packages/core/src/storages/sitemap_request_list.ts b/packages/core/src/storages/sitemap_request_list.tsindex 71a045bab..8c0c950e7 100644--- a/packages/core/src/storages/sitemap_request_list.ts+++ b/packages/core/src/storages/sitemap_request_list.ts@@ -1,5 +1,6 @@import { Transform } from 'node:stream';+import type { BaseHttpClient } from '@crawlee/types';import { EnqueueStrategy, parseSitemap, type ParseSitemapOptions } from '@crawlee/utils';import { minimatch } from 'minimatch';import ow from 'ow';@@ -110,6 +111,10 @@ export interface SitemapRequestListOptions extends UrlConstraints {* Crawlee configuration*/config?: Configuration;+ /**+ * Custom HTTP client to be used for sitemap loading.+ */+ httpClient?: BaseHttpClient;}interface SitemapParsingProgress {@@ -197,7 +202,7 @@ export class SitemapRequestList implements IRequestList {/*** Proxy URL to be used for sitemap loading.*/- private proxyUrl: string | undefined;+ private proxyUrl?: string;/*** Enqueue strategy applied to sitemap-derived URLs and stamped onto the emitted `Request` objects.@@ -429,12 +434,14 @@ export class SitemapRequestList implements IRequestList {* Track the loading progress using the `isSitemapFullyLoaded` property.*/static async open(options: SitemapRequestListOptions): Promise<SitemapRequestList> {+ const { httpClient, ...restOptions } = options;+const requestList = new SitemapRequestList({- ...options,+ ...restOptions,persistStateKey: options.persistStateKey ?? STATE_PERSISTENCE_KEY,});await requestList.restoreState();- void requestList.load({ parseSitemapOptions: options.parseSitemapOptions });+ void requestList.load({ parseSitemapOptions: { ...options.parseSitemapOptions, httpClient } });if (requestList.persistenceOptions.enable) {requestList.events.on(EventType.PERSIST_STATE, requestList.persistState);diff --git a/packages/core/src/storages/storage_manager.ts b/packages/core/src/storages/storage_manager.tsindex 27af61732..c50ee160f 100644--- a/packages/core/src/storages/storage_manager.ts+++ b/packages/core/src/storages/storage_manager.ts@@ -1,4 +1,4 @@-import type { Dictionary, StorageClient } from '@crawlee/types';+import type { BaseHttpClient, Dictionary, StorageClient } from '@crawlee/types';import { AsyncQueue } from '@sapphire/async-queue';import { Configuration } from '../configuration.js';@@ -174,4 +174,9 @@ export interface StorageManagerOptions {* If undefined, the `requestsFromUrl` requests will be made without proxy.*/proxyConfiguration?: ProxyConfiguration;++ /**+ * HTTP client to be used to download the list of URLs in `RequestQueue`.+ */+ httpClient?: BaseHttpClient;}diff --git a/packages/impit-client/package.json b/packages/impit-client/package.jsonindex a0d4e8c69..996eaf5ed 100644--- a/packages/impit-client/package.json+++ b/packages/impit-client/package.json@@ -46,14 +46,9 @@"publishConfig": {"access": "public"},- "peerDependencies": {- "@crawlee/core": "4.0.0"- },- "devDependencies": {- "@crawlee/core": "4.0.0"- },"dependencies": {"@apify/datastructures": "^2.0.3",+ "@crawlee/types": "4.0.0","impit": "^0.14.1","tough-cookie": "^6.0.0"}diff --git a/packages/impit-client/src/index.ts b/packages/impit-client/src/index.tsindex 761cd5a89..e6dacc263 100644--- a/packages/impit-client/src/index.ts+++ b/packages/impit-client/src/index.ts@@ -1,8 +1,7 @@import { pipeline, Readable, Transform } from 'node:stream';import type { ReadableStream } from 'node:stream/web';-import type { BaseHttpClient, SendRequestOptions, StreamOptions } from '@crawlee/core';-import { ResponseWithUrl } from '@crawlee/core';+import type { BaseHttpClient, IResponseWithUrl, SendRequestOptions, StreamOptions } from '@crawlee/types';import type { ImpitOptions, ImpitResponse } from 'impit';import { Impit } from 'impit';import type { CookieJar as ToughCookieJar } from 'tough-cookie';@@ -19,6 +18,14 @@ interface ResponseWithRedirects {redirectUrls: URL[];}+class ResponseWithUrl extends Response implements IResponseWithUrl {+ override url: string;+ constructor(body: BodyInit | null, init: ResponseInit & { url?: string }) {+ super(body, init);+ this.url = init.url ?? '';+ }+}+/*** A HTTP client implementation based on the `impit library.*/@@ -139,7 +146,7 @@ export class ImpitHttpClient implements BaseHttpClient {const impit = this.getClient({...this.impitOptions,...(options?.cookieJar ? { cookieJar: options?.cookieJar as any as ToughCookieJar } : {}),- proxyUrl: options?.session?.proxyInfo?.url,+ proxyUrl: options?.proxyUrl ?? options?.session?.proxyInfo?.url,followRedirects: false,});diff --git a/packages/types/package.json b/packages/types/package.jsonindex 1cb7a652e..a664f083d 100644--- a/packages/types/package.json+++ b/packages/types/package.json@@ -43,6 +43,7 @@"access": "public"},"dependencies": {+ "tough-cookie": "^6.0.0","tslib": "^2.8.1"}}diff --git a/packages/types/src/http-client.ts b/packages/types/src/http-client.tsnew file mode 100644index 000000000..a072fdf1a--- /dev/null+++ b/packages/types/src/http-client.ts@@ -0,0 +1,119 @@+import type { Readable } from 'node:stream';++import type { ISession } from './session.js';+import type { AllowedHttpMethods } from './utility-types.js';++export type SearchParams = string | URLSearchParams | Record<string, string | number | boolean | null | undefined>;++// TODO BC with got - remove the options and callback parameters in 4.0+interface ToughCookieJar {+ getCookieString: ((+ currentUrl: string,+ options: Record<string, unknown>,+ callback: (error: Error | null, cookies: string) => void,+ ) => string) &+ ((url: string, callback: (error: Error | null, cookieHeader: string) => void) => string);+ setCookie: ((+ cookieOrString: unknown,+ currentUrl: string,+ options: Record<string, unknown>,+ callback: (error: Error | null, cookie: unknown) => void,+ ) => void) &+ ((rawCookie: string, url: string, callback: (error: Error | null, result: unknown) => void) => void);+}++interface PromiseCookieJar {+ getCookieString: (url: string) => Promise<string>;+ setCookie: (rawCookie: string, url: string) => Promise<unknown>;+}++/**+ * HTTP Request as accepted by {@apilink BaseHttpClient} methods.+ */+export interface HttpRequest {+ url: string | URL;+ method?: AllowedHttpMethods;+ headers?: Headers;+ body?: Readable;++ signal?: AbortSignal;+ timeout?: number;++ cookieJar?: ToughCookieJar | PromiseCookieJar;+ followRedirect?: boolean | ((response: any) => boolean); // TODO BC with got - specify type better in 4.0+ maxRedirects?: number;++ encoding?: BufferEncoding;+ throwHttpErrors?: boolean;++ // from got-scraping Context+ proxyUrl?: string;+ headerGeneratorOptions?: Record<string, unknown>;+ useHeaderGenerator?: boolean;+ headerGenerator?: {+ getHeaders: (options: Record<string, unknown>) => Record<string, string>;+ };+ insecureHTTPParser?: boolean;+ sessionToken?: object;+}++/**+ * Additional options for HTTP requests that need to be handled separately before passing to {@apilink BaseHttpClient}.+ */+export interface HttpRequestOptions extends HttpRequest {+ /** Search (query string) parameters to be appended to the request URL */+ searchParams?: SearchParams;++ /** A form to be sent in the HTTP request body (URL encoding will be used) */+ form?: Record<string, string>;+ /** Arbitrary object to be JSON-serialized and sent as the HTTP request body */+ json?: unknown;++ /** Basic HTTP Auth username */+ username?: string;+ /** Basic HTTP Auth password */+ password?: string;+}++export interface IResponseWithUrl extends Response {+ url: string;+}++/**+ * Type of a function called when an HTTP redirect takes place. It is allowed to mutate the `updatedRequest` argument.+ */+export type RedirectHandler = (+ redirectResponse: Response,+ updatedRequest: { url?: string | URL; headers: Headers },+) => void;++export interface SendRequestOptions {+ session?: ISession;+ cookieJar?: ToughCookieJar;+ timeout?: number;+ /**+ * Overrides the proxy URL set in the `session` for this request.+ *+ * Note that setting this manually can interfere with session proxy rotation.+ */+ proxyUrl?: string;+}++export interface StreamOptions extends SendRequestOptions {+ onRedirect?: RedirectHandler;+}++/**+ * Interface for user-defined HTTP clients to be used for plain HTTP crawling and for sending additional requests during a crawl.+ */+export interface BaseHttpClient {+ /**+ * Perform an HTTP Request and return the complete response.+ */+ sendRequest(request: Request, options?: SendRequestOptions): Promise<Response>;++ /**+ * Perform an HTTP Request and return after the response headers are received. The body may be read from a stream contained in the response.+ */+ stream(request: Request, options?: StreamOptions): Promise<Response>;+}diff --git a/packages/types/src/index.ts b/packages/types/src/index.tsindex 218ef70f0..ef5273f56 100644--- a/packages/types/src/index.ts+++ b/packages/types/src/index.ts@@ -1,3 +1,5 @@export * from './storages.js';export * from './utility-types.js';export * from './browser.js';+export * from './http-client.js';+export * from './session.js';diff --git a/packages/types/src/session.ts b/packages/types/src/session.tsnew file mode 100644index 000000000..7bca512c9--- /dev/null+++ b/packages/types/src/session.ts@@ -0,0 +1,199 @@+import type { CookieJar, SerializedCookieJar } from 'tough-cookie';++import type { Cookie } from './browser.js';+import type { Dictionary } from './utility-types.js';++/**+ * The main purpose of the ProxyInfo object is to provide information+ * about the current proxy connection used by the crawler for the request.+ * Outside of crawlers, you can get this object by calling {@apilink ProxyConfiguration.newProxyInfo}.+ *+ * **Example usage:**+ *+ * ```javascript+ * const proxyConfiguration = new ProxyConfiguration({+ * proxyUrls: ['...', '...'] // List of Proxy URLs to rotate+ * });+ *+ * // Getting proxyInfo object by calling class method directly+ * const proxyInfo = await proxyConfiguration.newProxyInfo();+ *+ * // In crawler+ * const crawler = new CheerioCrawler({+ * // ...+ * proxyConfiguration,+ * requestHandler({ proxyInfo }) {+ * // Getting used proxy URL+ * const proxyUrl = proxyInfo.url;+ * }+ * })+ *+ * ```+ */+export interface ProxyInfo {+ /**+ * The URL of the proxy.+ */+ url: string;++ /**+ * Username for the proxy.+ */+ username?: string;++ /**+ * User's password for the proxy.+ */+ password: string;++ /**+ * Hostname of your proxy.+ */+ hostname: string;++ /**+ * Proxy port.+ */+ port: number | string;++ /**+ * Proxy tier for the current proxy, if applicable (only for `tieredProxyUrls`).+ */+ proxyTier?: number;++ /**+ * When `true`, the proxy is likely intercepting HTTPS traffic and is able to view and modify its content.+ *+ * @default false+ */+ ignoreTlsErrors?: boolean;+}++/**+ * Persistable {@apilink Session} state.+ */+export interface SessionState {+ id: string;+ cookieJar: SerializedCookieJar;+ proxyInfo?: ProxyInfo;+ userData: object;+ errorScore: number;+ maxErrorScore: number;+ errorScoreDecrement: number;+ usageCount: number;+ maxUsageCount: number;+ expiresAt: string;+ createdAt: string;+}++/**+ * Sessions are used to store information such as cookies and can be used for generating fingerprints and proxy sessions.+ * You can imagine each session as a specific user, with its own cookies, IP (via proxy) and potentially a unique browser fingerprint.+ * Session internal state can be enriched with custom user data for example some authorization tokens and specific headers in general.+ * @category Scaling+ */+export interface ISession {+ readonly id: string;+ userData: Dictionary;+ errorScore: number;+ usageCount: number;+ maxErrorScore: number;+ errorScoreDecrement: number;+ expiresAt: Date;+ createdAt: Date;+ maxUsageCount: number;+ cookieJar: CookieJar;+ proxyInfo?: ProxyInfo;++ /**+ * Indicates whether the session is blocked.+ * Session is blocked once it reaches the `maxErrorScore`.+ */+ isBlocked(): boolean;++ /**+ * Indicates whether the session is expired.+ * Session expiration is determined by the `maxAgeSecs`.+ * Once the session is older than `createdAt + maxAgeSecs` the session is considered expired.+ */+ isExpired(): boolean;++ /**+ * Indicates whether the session is used maximum number of times.+ * Session maximum usage count can be changed by `maxUsageCount` parameter.+ */+ isMaxUsageCountReached(): boolean;++ /**+ * Indicates whether the session can be used for next requests.+ * Session is usable when it is not expired, not blocked and the maximum usage count has not be reached.+ */+ isUsable(): boolean;++ /**+ * This method should be called after a successful session usage.+ * It increases `usageCount` and potentially lowers the `errorScore` by the `errorScoreDecrement`.+ */+ markGood(): void;++ /**+ * Gets session state for persistence in KeyValueStore.+ * @returns Represents session internal state.+ */+ getState(): SessionState;++ /**+ * Marks session as blocked and emits event on the `SessionPool`+ * This method should be used if the session usage was unsuccessful+ * and you are sure that it is because of the session configuration and not any external matters.+ * For example when server returns 403 status code.+ * If the session does not work due to some external factors as server error such as 5XX you probably want to use `markBad` method.+ */+ retire(): void;++ /**+ * Increases usage and error count.+ * Should be used when the session has been used unsuccessfully. For example because of timeouts.+ */+ markBad(): void;++ /**+ * With certain status codes: `401`, `403` or `429` we can be certain+ * that the target website is blocking us. This function helps to do this conveniently+ * by retiring the session when such code is received. Optionally, the default status+ * codes can be extended in the second parameter.+ * @param statusCode HTTP status code.+ * @returns Whether the session was retired.+ */+ retireOnBlockedStatusCodes(statusCode: number): boolean;++ /**+ * Saves cookies from an HTTP response to be used with the session.+ * It expects an object with a `headers` property that's either an `Object`+ * (typical Node.js responses) or a `Function` (Puppeteer Response).+ *+ * It then parses and saves the cookies from the `set-cookie` header, if available.+ */+ setCookiesFromResponse(response: Response): void;++ /**+ * Saves an array with cookie objects to be used with the session.+ * The objects should be in the format that+ * [Puppeteer uses](https://pptr.dev/#?product=Puppeteer&version=v2.0.0&show=api-pagecookiesurls),+ * but you can also use this function to set cookies manually:+ *+ * ```+ * [+ * { name: 'cookie1', value: 'my-cookie' },+ * { name: 'cookie2', value: 'your-cookie' }+ * ]+ * ```+ */+ setCookies(cookies: Cookie[], url: string): void;++ /**+ * Returns cookies in a format compatible with puppeteer/playwright and ready to be used with `page.setCookie`.+ * @param url website url. Only cookies stored for this url will be returned+ */+ getCookies(url: string): Cookie[];+}diff --git a/packages/utils/package.json b/packages/utils/package.jsonindex 3cc5ada3a..003b81025 100644--- a/packages/utils/package.json+++ b/packages/utils/package.json@@ -43,12 +43,12 @@"dependencies": {"@apify/log": "^2.5.18","@apify/ps-tree": "^1.2.0",+ "@crawlee/impit-client": "4.0.0","@crawlee/types": "4.0.0","@types/sax": "^1.2.7","cheerio": "^1.0.0","domhandler": "^5.0.3","file-type": "^21.0.0",- "got-scraping": "^4.2.1","ow": "^2.0.0","robots-parser": "^3.0.1","sax": "^1.4.1",diff --git a/packages/utils/src/internals/extract-urls.ts b/packages/utils/src/internals/extract-urls.tsindex beead850f..2b8b97da3 100644--- a/packages/utils/src/internals/extract-urls.ts+++ b/packages/utils/src/internals/extract-urls.ts@@ -1,4 +1,5 @@-import { gotScraping } from 'got-scraping';+import { ImpitHttpClient } from '@crawlee/impit-client';+import type { BaseHttpClient } from '@crawlee/types';import ow from 'ow';import { URL_NO_COMMAS_REGEX } from './general.js';@@ -24,6 +25,11 @@ export interface DownloadListOfUrlsOptions {/** Allows to use a proxy for the download request. */proxyUrl?: string;++ /**+ * Custom HTTP client to use for downloading the file.+ */+ httpClient?: BaseHttpClient;}/**@@ -38,9 +44,16 @@ export async function downloadListOfUrls(options: DownloadListOfUrlsOptions): Prencoding: ow.optional.string,urlRegExp: ow.optional.regExp,proxyUrl: ow.optional.string,+ httpClient: ow.optional.object,}),);- const { url, encoding = 'utf8', urlRegExp = URL_NO_COMMAS_REGEX, proxyUrl } = options;+ const {+ url,+ encoding = 'utf8',+ urlRegExp = URL_NO_COMMAS_REGEX,+ proxyUrl,+ httpClient = new ImpitHttpClient(),+ } = options;// Try to detect wrong urls and fix them. Currently, detects only sharing url instead of csv download one.const match = url.match(/^(https:\/\/docs\.google\.com\/spreadsheets\/d\/(?:\w|-)+)\/?/);@@ -50,7 +63,11 @@ export async function downloadListOfUrls(options: DownloadListOfUrlsOptions): PrfixedUrl = `${match[1]}/gviz/tq?tqx=out:csv`;}- const { body: string } = await gotScraping({ url: fixedUrl, encoding, proxyUrl });+ const response = await httpClient.sendRequest(new Request(fixedUrl, { method: 'GET' }), {+ proxyUrl,+ });++ const string = new TextDecoder(encoding).decode(new Uint8Array(await response.arrayBuffer()));return extractUrls({ string, urlRegExp });}diff --git a/packages/utils/src/internals/robots.ts b/packages/utils/src/internals/robots.tsindex 06a01f04b..1205dfac3 100644--- a/packages/utils/src/internals/robots.ts+++ b/packages/utils/src/internals/robots.ts@@ -1,5 +1,5 @@-import type { HTTPError as HTTPErrorClass } from 'got-scraping';-import { gotScraping } from 'got-scraping';+import { ImpitHttpClient } from '@crawlee/impit-client';+import type { BaseHttpClient } from '@crawlee/types';import type { Robot } from 'robots-parser';import robotsParser from 'robots-parser';@@ -8,8 +8,6 @@ import log from '@apify/log';import { Sitemap } from './sitemap.js';import { type EnqueueStrategy, filterUrl } from './url.js';-let HTTPError: typeof HTTPErrorClass;-export interface RobotsTxtFileSitemapsOptions {/*** Keep only sitemap URLs matching this strategy relative to the robots.txt host; non-`http(s)` schemes@@ -47,21 +45,20 @@ export class RobotsTxtFile {/*** Determine the location of a robots.txt file for a URL and fetch it.* @param url the URL to fetch robots.txt for- * @param [proxyUrl] a proxy to be used for fetching the robots.txt file* @param [options] additional options* @param [options.signal] an AbortSignal to cancel the request* @param [options.timeoutMillis] timeout in milliseconds for the request+ * @param [options.proxyUrl] a proxy to be used for fetching the robots.txt file*/static async find(url: string,- proxyUrl?: string,- options?: { signal?: AbortSignal; timeoutMillis?: number },+ options?: { signal?: AbortSignal; timeoutMillis?: number; proxyUrl?: string; httpClient?: BaseHttpClient },): Promise<RobotsTxtFile> {const robotsTxtFileUrl = new URL(url);robotsTxtFileUrl.pathname = '/robots.txt';robotsTxtFileUrl.search = '';- return RobotsTxtFile.load(robotsTxtFileUrl.toString(), proxyUrl, options);+ return RobotsTxtFile.load(robotsTxtFileUrl.toString(), options);}/**@@ -76,41 +73,36 @@ export class RobotsTxtFile {protected static async load(url: string,- proxyUrl?: string,- options?: { signal?: AbortSignal; timeoutMillis?: number },+ options?: { signal?: AbortSignal; timeoutMillis?: number; proxyUrl?: string; httpClient?: BaseHttpClient },): Promise<RobotsTxtFile> {- if (!HTTPError) {- HTTPError = (await import('got-scraping')).HTTPError;+ const { proxyUrl, httpClient = new ImpitHttpClient({ followRedirects: true }) } = options || {};++ const response = await httpClient.sendRequest(new Request(url, { method: 'GET' }), {+ proxyUrl,+ signal,+ timeout: options?.timeoutMillis,+ });++ if (response.status < 200 || response.status >= 300) {+ throw new Error(`Failed to load robots.txt from ${url}: HTTP ${response.status}`);}- try {- const response = await gotScraping({+ if (response.status === 404) {+ return new RobotsTxtFile(url,- proxyUrl,- method: 'GET',- responseType: 'text',- signal: options?.signal,- ...(options?.timeoutMillis ? { timeout: { request: options.timeoutMillis } } : {}),- });-- return new RobotsTxtFile(url, robotsParser(url.toString(), response.body), proxyUrl);- } catch (e) {- if (e instanceof HTTPError && e.response.statusCode === 404) {- return new RobotsTxtFile(- url,- {- isAllowed() {- return true;- },- getSitemaps() {- return [];- },+ {+ isAllowed() {+ return true;},- proxyUrl,- );- }- throw e;+ getSitemaps() {+ return [];+ },+ },+ proxyUrl,+ );}++ return new RobotsTxtFile(url, robotsParser(url.toString(), await response.text()), proxyUrl);}/**diff --git a/packages/utils/src/internals/sitemap.ts b/packages/utils/src/internals/sitemap.tsindex 465c3582d..80eae1bc1 100644--- a/packages/utils/src/internals/sitemap.ts+++ b/packages/utils/src/internals/sitemap.ts@@ -4,7 +4,9 @@ import { PassThrough, pipeline, Readable, Transform } from 'node:stream';import { StringDecoder } from 'node:string_decoder';import { createGunzip } from 'node:zlib';-import type { Delays } from 'got-scraping';+import { ImpitHttpClient } from '@crawlee/impit-client';+import type { BaseHttpClient } from '@crawlee/types';+import { fileTypeStream } from 'file-type';import sax from 'sax';import MIMEType from 'whatwg-mimetype';@@ -191,14 +193,18 @@ export interface ParseSitemapOptions {*/sitemapRetries?: number;/**- * Network timeouts for sitemap fetching. See [Got documentation](https://github.com/sindresorhus/got/blob/main/documentation/6-timeout.md) for more details.+ * Timeout settings for network requests when fetching sitemaps. By default this is `30000` milliseconds (30 seconds).*/- networkTimeouts?: Delays;+ timeoutMillis?: number;/*** If true, the parser will log a warning if it fails to fetch a sitemap due to a network error* @default true*/reportNetworkErrors?: boolean;+ /**+ * Custom HTTP client to be used for fetching sitemaps.+ */+ httpClient?: BaseHttpClient;/*** Optional filter for nested sitemap URLs discovered in sitemap index files.* Called with the URL of each child sitemap before it is fetched.@@ -220,13 +226,12 @@ export async function* parseSitemap<T extends ParseSitemapOptions>(proxyUrl?: string,options?: T,): AsyncIterable<T['emitNestedSitemaps'] extends true ? SitemapUrl | NestedSitemap : SitemapUrl> {- const { gotScraping } = await import('got-scraping');- const { fileTypeStream } = await import('file-type');const {+ httpClient = new ImpitHttpClient(),emitNestedSitemaps = false,maxDepth = Infinity,sitemapRetries = 3,- networkTimeouts,+ timeoutMillis: timeout = 30000,reportNetworkErrors = true,nestedSitemapFilter,enqueueStrategy = 'same-hostname',@@ -277,28 +282,34 @@ export async function* parseSitemap<T extends ParseSitemapOptions>(while (retriesLeft-- > 0) {try {- const sitemapStream = await new Promise<ReturnType<typeof gotScraping.stream>>(- (resolve, reject) => {- const request = gotScraping.stream({- url: sitemapUrl,- proxyUrl,+ let sitemapResponse: Response | null;++ try {+ sitemapResponse = await httpClient.stream(+ new Request(sitemapUrl, {method: 'GET',- timeout: networkTimeouts,headers: {accept: '*/*',},- });- request.on('response', () => resolve(request));- request.on('error', reject);- },- );+ }),+ {+ proxyUrl,+ timeout,+ },+ );+ } catch (error: any) {+ sitemapResponse = null;+ }let error: { error: Error; type: 'fetch' | 'parser' } | null = null;- if (sitemapStream.response!.statusCode >= 200 && sitemapStream.response!.statusCode < 300) {- let contentType = sitemapStream.response!.headers['content-type'];+ if (sitemapResponse && sitemapResponse.status >= 200 && sitemapResponse.status < 300) {+ let contentType = sitemapResponse.headers.get('content-type');- const streamWithType = await fileTypeStream(sitemapStream);+ if (sitemapResponse.body === null) {+ break;+ }+ const streamWithType = await fileTypeStream(Readable.fromWeb(sitemapResponse.body as any));if (streamWithType.fileType !== undefined) {contentType = streamWithType.fileType.mime;}@@ -320,7 +331,7 @@ export async function* parseSitemap<T extends ParseSitemapOptions>(items = pipeline(streamWithType,isGzipped ? createGunzip() : new PassThrough(),- createParser(contentType, sitemapUrl),+ createParser(contentType ?? undefined, sitemapUrl),(e) => {if (e !== undefined && e !== null) {error = { type: 'parser', error: e };@@ -331,7 +342,7 @@ export async function* parseSitemap<T extends ParseSitemapOptions>(error = {type: 'fetch',error: new Error(- `Failed to fetch sitemap: ${sitemapUrl}, status code: ${sitemapStream.response!.statusCode}`,+ `Failed to fetch sitemap: ${sitemapUrl}, status code: ${sitemapResponse?.status}`,),};}@@ -439,7 +450,11 @@ export class Sitemap {* @param url The domain URL to fetch the sitemap for.* @param proxyUrl A proxy to be used for fetching the sitemap file.*/- static async tryCommonNames(url: string, proxyUrl?: string): Promise<Sitemap> {+ static async tryCommonNames(+ url: string,+ proxyUrl?: string,+ parseSitemapOptions?: ParseSitemapOptions,+ ): Promise<Sitemap> {const sitemapUrls: string[] = [];const sitemapUrl = new URL(url);@@ -451,7 +466,7 @@ export class Sitemap {sitemapUrl.pathname = '/sitemap.txt';sitemapUrls.push(sitemapUrl.toString());- return Sitemap.load(sitemapUrls, proxyUrl, { reportNetworkErrors: false });+ return Sitemap.load(sitemapUrls, proxyUrl, { reportNetworkErrors: false, ...parseSitemapOptions });}/**@@ -476,8 +491,12 @@ export class Sitemap {* @param content XML sitemap content* @param proxyUrl URL of a proxy to be used for fetching sitemap contents*/- static async fromXmlString(content: string, proxyUrl?: string): Promise<Sitemap> {- return await this.parse([{ type: 'raw', content }], proxyUrl);+ static async fromXmlString(+ content: string,+ proxyUrl?: string,+ parseSitemapOptions?: ParseSitemapOptions,+ ): Promise<Sitemap> {+ return await this.parse([{ type: 'raw', content }], proxyUrl, parseSitemapOptions);}protected static async parse(diff --git a/packages/utils/src/internals/url.ts b/packages/utils/src/internals/url.tsindex 9d6fd1f45..3c5fe8db0 100644--- a/packages/utils/src/internals/url.ts+++ b/packages/utils/src/internals/url.ts@@ -1,7 +1,6 @@+import type { SearchParams } from '@crawlee/types';import { getDomain } from 'tldts';-export type SearchParams = string | URLSearchParams | Record<string, string | number | boolean | null | undefined>;-/*** The different enqueueing strategies available.*diff --git a/packages/utils/test/mock-http-client.ts b/packages/utils/test/mock-http-client.tsnew file mode 100644index 000000000..14673d560--- /dev/null+++ b/packages/utils/test/mock-http-client.ts@@ -0,0 +1,13 @@+import type { BaseHttpClient, SendRequestOptions, StreamOptions } from '@crawlee/types';++export class FetchHttpClient implements BaseHttpClient {+ async sendRequest(request: Request, options?: SendRequestOptions): Promise<Response> {+ const signal = AbortSignal.timeout(options?.timeout ?? 30000);+ const response = await fetch(request, { signal });+ return response;+ }++ async stream(request: Request, options?: StreamOptions): Promise<Response> {+ return this.sendRequest(request, options);+ }+}diff --git a/packages/utils/test/robots.test.ts b/packages/utils/test/robots.test.tsindex 3fed9ed77..c7db055f6 100644--- a/packages/utils/test/robots.test.ts+++ b/packages/utils/test/robots.test.ts@@ -2,6 +2,9 @@ import nock from 'nock';import { beforeEach, describe, expect, it } from 'vitest';import { RobotsTxtFile } from '../src/internals/robots.js';+import { FetchHttpClient } from './mock-http-client.js';++const httpClient = new FetchHttpClient();describe('RobotsTxtFile', () => {beforeEach(() => {@@ -38,12 +41,12 @@ describe('RobotsTxtFile', () => {});it('generates the correct robots.txt URL', async () => {- const robots = await RobotsTxtFile.find('http://not-exists.com/nested/index.html');+ const robots = await RobotsTxtFile.find('http://not-exists.com/nested/index.html', { httpClient });expect(robots.getSitemaps()).not.toHaveLength(0);});it('parses allow/deny directives from robots.txt', async () => {- const robots = await RobotsTxtFile.find('http://not-exists.com/robots.txt');+ const robots = await RobotsTxtFile.find('http://not-exists.com/robots.txt', { httpClient });console.log(robots.isAllowed('https://crawlee.dev'));expect(robots.isAllowed('http://not-exists.com/something/page.html')).toBe(true);expect(robots.isAllowed('http://not-exists.com/deny_googlebot/page.html')).toBe(true);@@ -51,7 +54,7 @@ describe('RobotsTxtFile', () => {});it('extracts sitemap urls', async () => {- const robots = await RobotsTxtFile.find('http://not-exists.com/robots.txt');+ const robots = await RobotsTxtFile.find('http://not-exists.com/robots.txt', { httpClient });expect(robots.getSitemaps()).toEqual(['http://not-exists.com/sitemap_1.xml','http://not-exists.com/sitemap_2.xml',diff --git a/packages/utils/test/sitemap.test.ts b/packages/utils/test/sitemap.test.tsindex c955570a1..e952b2000 100644--- a/packages/utils/test/sitemap.test.ts+++ b/packages/utils/test/sitemap.test.ts@@ -5,6 +5,7 @@ import log from '@apify/log';import type { SitemapUrl } from '../src/internals/sitemap.js';import { discoverValidSitemaps, parseSitemap, Sitemap } from '../src/internals/sitemap.js';+import { FetchHttpClient } from './mock-http-client.js';describe('Sitemap', () => {beforeEach(() => {@@ -287,7 +288,9 @@ describe('Sitemap', () => {});it('extracts urls from sitemaps', async () => {- const sitemap = await Sitemap.load('http://not-exists.com/sitemap_child.xml');+ const sitemap = await Sitemap.load('http://not-exists.com/sitemap_child.xml', undefined, {+ httpClient: new FetchHttpClient(),+ });expect(new Set(sitemap.urls)).toEqual(new Set(['http://not-exists.com/',@@ -302,7 +305,11 @@ describe('Sitemap', () => {it('extracts metadata from sitemaps', async () => {const items: SitemapUrl[] = [];- for await (const item of parseSitemap([{ type: 'url', url: 'http://not-exists.com/sitemap_child.xml' }])) {+ for await (const item of parseSitemap(+ [{ type: 'url', url: 'http://not-exists.com/sitemap_child.xml' }],+ undefined,+ { httpClient: new FetchHttpClient() },+ )) {items.push(item);}@@ -318,7 +325,9 @@ describe('Sitemap', () => {});it('extracts urls from gzipped sitemaps', async () => {- const sitemap = await Sitemap.load('http://not-exists.com/sitemap_child.xml.gz');+ const sitemap = await Sitemap.load('http://not-exists.com/sitemap_child.xml.gz', undefined, {+ httpClient: new FetchHttpClient(),+ });expect(new Set(sitemap.urls)).toEqual(new Set(['http://not-exists.com/',@@ -331,12 +340,16 @@ describe('Sitemap', () => {});it('identifies incorrect gzipped sitemaps as malformed', async () => {- const sitemap = await Sitemap.load('http://not-exists.com/invalid_sitemap_child.xml.gz');+ const sitemap = await Sitemap.load('http://not-exists.com/invalid_sitemap_child.xml.gz', undefined, {+ httpClient: new FetchHttpClient(),+ });expect(new Set(sitemap.urls)).toEqual(new Set([]));});it('follows links in sitemap indexes', async () => {- const sitemap = await Sitemap.load('http://not-exists.com/sitemap_parent.xml');+ const sitemap = await Sitemap.load('http://not-exists.com/sitemap_parent.xml', undefined, {+ httpClient: new FetchHttpClient(),+ });expect(new Set(sitemap.urls)).toEqual(new Set(['http://not-exists.com/',@@ -376,17 +389,23 @@ describe('Sitemap', () => {});it('does not break on invalid xml', async () => {- const sitemap = await Sitemap.load('http://not-exists.com/not_actual_xml.xml');+ const sitemap = await Sitemap.load('http://not-exists.com/not_actual_xml.xml', undefined, {+ httpClient: new FetchHttpClient(),+ });expect(sitemap.urls).toEqual([]);});it('handles CDATA in loc tags', async () => {- const sitemap = await Sitemap.load('http://not-exists.com/sitemap_cdata.xml');+ const sitemap = await Sitemap.load('http://not-exists.com/sitemap_cdata.xml', undefined, {+ httpClient: new FetchHttpClient(),+ });expect(new Set(sitemap.urls)).toEqual(new Set(['http://not-exists.com/catalog']));});it('autodetects sitemaps', async () => {- const sitemap = await Sitemap.tryCommonNames('http://not-exists.com/arbitrary_url?search=xyz');+ const sitemap = await Sitemap.tryCommonNames('http://not-exists.com/arbitrary_url?search=xyz', undefined, {+ httpClient: new FetchHttpClient(),+ });expect(new Set(sitemap.urls)).toEqual(new Set(['http://not-exists.com/catalog?item=80&desc=vacation_turkey',@@ -400,14 +419,18 @@ describe('Sitemap', () => {it('keeps quiet if autodetection does not find anything', async () => {const spy = vi.spyOn(log, 'warning');- const sitemap = await Sitemap.tryCommonNames('http://not-exists-2.com/arbitrary_url?search=xyz');+ const sitemap = await Sitemap.tryCommonNames('http://not-exists-2.com/arbitrary_url?search=xyz', undefined, {+ httpClient: new FetchHttpClient(),+ });expect(sitemap.urls).toHaveLength(0);expect(spy).not.toHaveBeenCalled();});it('handles sitemap.txt correctly', async () => {- const sitemap = await Sitemap.load('http://not-exists.com/sitemap.txt');+ const sitemap = await Sitemap.load('http://not-exists.com/sitemap.txt', undefined, {+ httpClient: new FetchHttpClient(),+ });expect(new Set(sitemap.urls)).toEqual(new Set(['http://not-exists.com/catalog?item=78&desc=vacation_crete',@@ -417,14 +440,20 @@ describe('Sitemap', () => {});it('handles pretty-printed XML correctly', async () => {- const sitemap = await Sitemap.load('http://not-exists.com/sitemap_pretty.xml');+ const sitemap = await Sitemap.load('http://not-exists.com/sitemap_pretty.xml', undefined, {+ httpClient: new FetchHttpClient(),+ });expect(new Set(sitemap.urls)).toEqual(new Set(['http://not-exists.com/catalog?item=80&desc=vacation_turkey']));});it('extracts metadata from pretty-printed XML', async () => {const items: SitemapUrl[] = [];- for await (const item of parseSitemap([{ type: 'url', url: 'http://not-exists.com/sitemap_pretty.xml' }])) {+ for await (const item of parseSitemap(+ [{ type: 'url', url: 'http://not-exists.com/sitemap_pretty.xml' }],+ undefined,+ { httpClient: new FetchHttpClient() },+ )) {items.push(item);}@@ -440,7 +469,9 @@ describe('Sitemap', () => {});it('handles pretty-printed nested sitemaps XML correctly', async () => {- const sitemap = await Sitemap.load('http://not-exists.com/sitemap_parent_pretty.xml');+ const sitemap = await Sitemap.load('http://not-exists.com/sitemap_parent_pretty.xml', undefined, {+ httpClient: new FetchHttpClient(),+ });expect(new Set(sitemap.urls)).toEqual(new Set(['http://not-exists.com/',@@ -525,6 +556,8 @@ describe('Sitemap', () => {'</sitemap>','</sitemapindex>',].join('\n'),+ undefined,+ { httpClient: new FetchHttpClient() },);expect(new Set(sitemap.urls)).toEqual(@@ -539,7 +572,9 @@ describe('Sitemap', () => {});it("loads XML sitemap even though it's gzipped according to file extension", async () => {- const sitemap = await Sitemap.load('http://not-exists.com/non_gzipped_sitemap.xml.gz');+ const sitemap = await Sitemap.load('http://not-exists.com/non_gzipped_sitemap.xml.gz', undefined, {+ httpClient: new FetchHttpClient(),+ });expect(new Set(sitemap.urls)).toEqual(new Set([@@ -550,7 +585,9 @@ describe('Sitemap', () => {});it("loads gzipped sitemap even though it's not gzipped according to file extension", async () => {- const sitemap = await Sitemap.load('http://not-exists.com/sneakily_gzipped_sitemap.xml');+ const sitemap = await Sitemap.load('http://not-exists.com/sneakily_gzipped_sitemap.xml', undefined, {+ httpClient: new FetchHttpClient(),+ });expect(new Set(sitemap.urls)).toEqual(new Set([diff --git a/test/core/crawlers/cheerio_crawler.test.ts b/test/core/crawlers/cheerio_crawler.test.tsindex aa0a8365e..8e68dc574 100644--- a/test/core/crawlers/cheerio_crawler.test.ts+++ b/test/core/crawlers/cheerio_crawler.test.ts@@ -1,14 +1,6 @@-import type { IncomingHttpHeaders, Server } from 'node:http';-import { Readable } from 'node:stream';--import type {- BasicCrawlingContext,- CheerioCrawlingContext,- CheerioRequestHandler,- CrawlingContext,- ProxyInfo,- Source,-} from '@crawlee/cheerio';+import type { Server } from 'node:http';++import type { BasicCrawlingContext, CheerioCrawlingContext, CheerioRequestHandler, Source } from '@crawlee/cheerio';import {CheerioCrawler,createCheerioRouter,@@ -20,6 +12,7 @@ import {Session,} from '@crawlee/cheerio';import { ImpitHttpClient } from '@crawlee/impit-client';+import type { ProxyInfo } from '@crawlee/types';import type { Dictionary } from '@crawlee/utils';import { sleep } from '@crawlee/utils';import type { OptionsInit } from 'got-scraping';diff --git a/test/core/request_list.test.ts b/test/core/request_list.test.tsindex 4abcd129b..045fc6363 100644--- a/test/core/request_list.test.ts+++ b/test/core/request_list.test.ts@@ -8,7 +8,6 @@ import {RequestList,} from '@crawlee/core';import { sleep } from '@crawlee/utils';-import { gotScraping } from 'got-scraping';import { MemoryStorageEmulator } from 'test/shared/MemoryStorageEmulator.js';import { beforeAll, type MockedFunction } from 'vitest';@@ -26,16 +25,24 @@ function shuffle(array: unknown[]): unknown[] {return out;}-vitest.mock('got-scraping', async () => {- return {- gotScraping: vitest.fn(),- };+let mockHttpClient = vitest.mockObject({+ async sendRequest(_request: any, _options?: any) {+ return new Response();+ },+ async stream() {+ return new Response();+ },});-let gotScrapingSpy: MockedFunction<typeof gotScraping>;--beforeAll(async () => {- gotScrapingSpy = vitest.mocked(gotScraping);+beforeEach(async () => {+ mockHttpClient = vitest.mockObject({+ async sendRequest() {+ return new Response();+ },+ async stream() {+ return new Response();+ },+ });});describe('RequestList', () => {@@ -189,9 +196,11 @@ describe('RequestList', () => {test('should use regex parameter to parse urls', async () => {const listStr = 'kjnjkn"https://example.com/a/b/c?q=1#abc";,"HTTP://google.com/a/b/c";dgg:dd';const listArr = ['https://example.com', 'HTTP://google.com'];- gotScrapingSpy.mockResolvedValue({ body: listStr } as any);const regex = /(https:\/\/example.com|HTTP:\/\/google.com)/g;++ mockHttpClient.sendRequest.mockResolvedValueOnce(new Response(listStr));+const requestList = await RequestList.open({sources: [{@@ -200,12 +209,14 @@ describe('RequestList', () => {regex,},],+ httpClient: mockHttpClient,});expect(await requestList.fetchNextRequest()).toMatchObject({ method: 'GET', url: listArr[0] });expect(await requestList.fetchNextRequest()).toMatchObject({ method: 'GET', url: listArr[1] });- expect(gotScrapingSpy).toBeCalledWith({ url: 'http://example.com/list-1', encoding: 'utf8' });+ expect(mockHttpClient.sendRequest).toBeCalled();+ expect(mockHttpClient.sendRequest.mock.calls[0][0].url).toBe('http://example.com/list-1');});test('should fix gdoc sharing url in `requestsFromUrl` automatically (GH issue #639)', async () => {@@ -221,17 +232,18 @@ describe('RequestList', () => {const correctUrl ='https://docs.google.com/spreadsheets/d/11UGSBOSXy5Ov2WEP9nr4kSIxQJmH18zh-5onKtBsovU/gviz/tq?tqx=out:csv';- gotScrapingSpy.mockResolvedValue({ body: JSON.stringify(list) } as any);+ mockHttpClient.sendRequest.mockImplementation(async () => new Response(list.join('\n')));const requestList = await RequestList.open({sources: wrongUrls.map((requestsFromUrl) => ({ requestsFromUrl })),+ httpClient: mockHttpClient,});expect(await requestList.fetchNextRequest()).toMatchObject({ method: 'GET', url: list[0] });expect(await requestList.fetchNextRequest()).toMatchObject({ method: 'GET', url: list[1] });expect(await requestList.fetchNextRequest()).toMatchObject({ method: 'GET', url: list[2] });- expect(gotScrapingSpy).toBeCalledWith({ url: correctUrl, encoding: 'utf8' });+ expect(mockHttpClient.sendRequest.mock.calls[0][0]?.url).toBe(correctUrl);});test('should handle requestsFromUrl with no URLs', async () => {diff --git a/test/core/sitemap_request_list.test.ts b/test/core/sitemap_request_list.test.tsindex e92423f1e..d98e741f4 100644--- a/test/core/sitemap_request_list.test.ts+++ b/test/core/sitemap_request_list.test.ts@@ -517,8 +517,9 @@ describe('SitemapRequestList', () => {while (!(await list.isFinished())) {const request = await list.fetchNextRequest();- await list.markRequestHandled(request!);- requests.push(request!);+ if (!request) break;+ await list.markRequestHandled(request);+ requests.push(request);}await expect(list.isEmpty()).resolves.toBe(true);@@ -542,12 +543,13 @@ describe('SitemapRequestList', () => {while (!(await list.isFinished())) {const request = await list.fetchNextRequest();+ if (!request) break;if (counter % 2 === 0) {- await list.markRequestHandled(request!);- requests.push(request!);+ await list.markRequestHandled(request);+ requests.push(request);} else {- await list.reclaimRequest(request!);+ await list.reclaimRequest(request);}counter += 1;@@ -585,7 +587,8 @@ describe('SitemapRequestList', () => {while (!(await newList.isFinished())) {const request = await newList.fetchNextRequest();- await newList.markRequestHandled(request!);+ if (!request) break;+ await newList.markRequestHandled(request);}expect(list.handledCount()).toBe(1);diff --git a/test/core/storages/request_queue.test.ts b/test/core/storages/request_queue.test.tsindex 9ef3194f8..a15d44828 100644--- a/test/core/storages/request_queue.test.ts+++ b/test/core/storages/request_queue.test.ts@@ -16,16 +16,24 @@ import type { MockedFunction } from 'vitest';import { MemoryStorageEmulator } from '../../shared/MemoryStorageEmulator.js';-vitest.mock('got-scraping', async () => {- return {- gotScraping: vitest.fn(),- };+let mockHttpClient = vitest.mockObject({+ async sendRequest(_request: any, _options?: any) {+ return new Response();+ },+ async stream() {+ return new Response();+ },});-let gotScrapingSpy: MockedFunction<typeof gotScraping>;--beforeAll(async () => {- gotScrapingSpy = vitest.mocked(gotScraping);+beforeEach(async () => {+ mockHttpClient = vitest.mockObject({+ async sendRequest() {+ return new Response();+ },+ async stream() {+ return new Response();+ },+ });});describe('RequestQueue remote', () => {@@ -847,10 +855,13 @@ describe('RequestQueue with requestsFromUrl', () => {test('should use regex parameter to parse urls', async () => {const listStr = 'kjnjkn"https://example.com/a/b/c?q=1#abc";,"HTTP://google.com/a/b/c";dgg:dd';const listArr = ['https://example.com', 'HTTP://google.com'];- gotScrapingSpy.mockResolvedValue({ body: listStr } as any);++ mockHttpClient.sendRequest.mockResolvedValueOnce(new Response(listStr));const regex = /(https:\/\/example.com|HTTP:\/\/google.com)/g;- const queue = await RequestQueue.open();+ const queue = await RequestQueue.open(null, {+ httpClient: mockHttpClient,+ });await queue.addRequest({method: 'GET',requestsFromUrl: 'http://example.com/list-1',@@ -861,7 +872,8 @@ describe('RequestQueue with requestsFromUrl', () => {expect(await queue.fetchNextRequest()).toMatchObject({ method: 'GET', url: listArr[1] });await queue.drop();- expect(gotScrapingSpy).toBeCalledWith({ url: 'http://example.com/list-1', encoding: 'utf8' });+ expect(mockHttpClient.sendRequest).toBeCalled();+ expect(mockHttpClient.sendRequest.mock.calls[0][0].url).toBe('http://example.com/list-1');});test('should fix gdoc sharing url in `requestsFromUrl` automatically (GH issue #639)', async () => {@@ -877,16 +889,18 @@ describe('RequestQueue with requestsFromUrl', () => {const correctUrl ='https://docs.google.com/spreadsheets/d/11UGSBOSXy5Ov2WEP9nr4kSIxQJmH18zh-5onKtBsovU/gviz/tq?tqx=out:csv';- gotScrapingSpy.mockResolvedValue({ body: JSON.stringify(list) } as any);+ mockHttpClient.sendRequest.mockImplementation(async () => new Response(list.join('\n'), { status: 200 }));- const queue = await RequestQueue.open();+ const queue = await RequestQueue.open(null, {+ httpClient: mockHttpClient,+ });await queue.addRequests(wrongUrls.map((requestsFromUrl) => ({ requestsFromUrl })));expect(await queue.fetchNextRequest()).toMatchObject({ method: 'GET', url: list[0] });expect(await queue.fetchNextRequest()).toMatchObject({ method: 'GET', url: list[1] });expect(await queue.fetchNextRequest()).toMatchObject({ method: 'GET', url: list[2] });- expect(gotScrapingSpy).toBeCalledWith({ url: correctUrl, encoding: 'utf8' });+ expect(mockHttpClient.sendRequest.mock.calls[0][0].url).toBe(correctUrl);await queue.drop();});diff --git a/test/utils/extract-urls.test.ts b/test/utils/extract-urls.test.tsindex 997ac1b12..68b14930c 100644--- a/test/utils/extract-urls.test.ts+++ b/test/utils/extract-urls.test.ts@@ -1,14 +1,8 @@import fs from 'node:fs';import path from 'node:path';+import type { BaseHttpClient } from '@crawlee/types';import { downloadListOfUrls, extractUrls, URL_WITH_COMMAS_REGEX } from '@crawlee/utils';-import { gotScraping } from 'got-scraping';--vitest.mock('got-scraping', async () => {- return {- gotScraping: vitest.fn(),- };-});const baseDataPath = path.join(import.meta.dirname, '..', 'shared', 'data');@@ -20,12 +14,19 @@ describe('downloadListOfUrls()', () => {.split(/[\r\n]+/g).map((u) => u.trim());- const gotScrapingSpy = vitest.mocked(gotScraping);- gotScrapingSpy.mockResolvedValueOnce({ body: text });+ const mockClient: BaseHttpClient = {+ async sendRequest() {+ return new Response(text);+ },+ async stream() {+ return new Response(text);+ },+ };await expect(downloadListOfUrls({url: 'http://www.nowhere12345.com',+ httpClient: mockClient,}),).resolves.toEqual(arr);});