@crawlee/linkedom 4.0.0-beta.16 → 4.0.0-beta.161

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
@@ -1,23 +1,23 @@
1
1
  <h1 align="center">
2
2
  <a href="https://crawlee.dev">
3
3
  <picture>
4
- <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/apify/crawlee/master/website/static/img/crawlee-dark.svg?sanitize=true">
5
- <img alt="Crawlee" src="https://raw.githubusercontent.com/apify/crawlee/master/website/static/img/crawlee-light.svg?sanitize=true" width="500">
4
+ <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/apify/crawlee/master/website/static/img/crawlee-dark.svg?sanitize=true" />
5
+ <img alt="Crawlee" src="https://raw.githubusercontent.com/apify/crawlee/master/website/static/img/crawlee-light.svg?sanitize=true" width="500" />
6
6
  </picture>
7
7
  </a>
8
- <br>
8
+ <br />
9
9
  <small>A web scraping and browser automation library</small>
10
10
  </h1>
11
11
 
12
- <p align=center>
13
- <a href="https://trendshift.io/repositories/5179" target="_blank"><img src="https://trendshift.io/api/badge/repositories/5179" alt="apify%2Fcrawlee | Trendshift" style="width: 250px; height: 55px;" width="250" height="55"/></a>
12
+ <p align="center">
13
+ <a href="https://trendshift.io/repositories/5179" target="_blank"><img src="https://trendshift.io/api/badge/repositories/5179" alt="apify%2Fcrawlee | Trendshift" width="250" height="55"/></a>
14
14
  </p>
15
15
 
16
- <p align=center>
17
- <a href="https://www.npmjs.com/package/@crawlee/core" rel="nofollow"><img src="https://img.shields.io/npm/v/@crawlee/core.svg" alt="NPM latest version" data-canonical-src="https://img.shields.io/npm/v/@crawlee/core/next.svg" style="max-width: 100%;"></a>
18
- <a href="https://www.npmjs.com/package/@crawlee/core" rel="nofollow"><img src="https://img.shields.io/npm/dm/@crawlee/core.svg" alt="Downloads" data-canonical-src="https://img.shields.io/npm/dm/@crawlee/core.svg" style="max-width: 100%;"></a>
19
- <a href="https://discord.gg/jyEM2PRvMU" rel="nofollow"><img src="https://img.shields.io/discord/801163717915574323?label=discord" alt="Chat on discord" data-canonical-src="https://img.shields.io/discord/801163717915574323?label=discord" style="max-width: 100%;"></a>
20
- <a href="https://github.com/apify/crawlee/actions/workflows/test-ci.yml"><img src="https://github.com/apify/crawlee/actions/workflows/test-ci.yml/badge.svg?branch=master" alt="Build Status" style="max-width: 100%;"></a>
16
+ <p align="center">
17
+ <a href="https://www.npmjs.com/package/@crawlee/core" rel="nofollow"><img src="https://img.shields.io/npm/v/@crawlee/core.svg" alt="NPM latest version" data-canonical-src="https://img.shields.io/npm/v/@crawlee/core/next.svg" /></a>
18
+ <a href="https://www.npmjs.com/package/@crawlee/core" rel="nofollow"><img src="https://img.shields.io/npm/dm/@crawlee/core.svg" alt="Downloads" data-canonical-src="https://img.shields.io/npm/dm/@crawlee/core.svg" /></a>
19
+ <a href="https://discord.gg/jyEM2PRvMU" rel="nofollow"><img src="https://img.shields.io/discord/801163717915574323?label=discord" alt="Chat on discord" data-canonical-src="https://img.shields.io/discord/801163717915574323?label=discord" /></a>
20
+ <a href="https://github.com/apify/crawlee/actions/workflows/test-ci.yml"><img src="https://github.com/apify/crawlee/actions/workflows/test-ci.yml/badge.svg?branch=master" alt="Build Status" /></a>
21
21
  </p>
22
22
 
23
23
  Crawlee covers your crawling and scraping end-to-end and **helps you build reliable scrapers. Fast.**
@@ -89,7 +89,7 @@ By default, Crawlee stores data to `./storage` in the current working directory.
89
89
  We provide automated beta builds for every merged code change in Crawlee. You can find them in the npm [list of releases](https://www.npmjs.com/package/crawlee?activeTab=versions). If you want to test new features or bug fixes before we release them, feel free to install a beta build like this:
90
90
 
91
91
  ```bash
92
- npm install crawlee@3.12.3-beta.13
92
+ npm install crawlee@next
93
93
  ```
94
94
 
95
95
  If you also use the [Apify SDK](https://github.com/apify/apify-sdk-js), you need to specify dependency overrides in your `package.json` file so that you don't end up with multiple versions of Crawlee installed:
@@ -98,9 +98,9 @@ If you also use the [Apify SDK](https://github.com/apify/apify-sdk-js), you need
98
98
  {
99
99
  "overrides": {
100
100
  "apify": {
101
- "@crawlee/core": "3.12.3-beta.13",
102
- "@crawlee/types": "3.12.3-beta.13",
103
- "@crawlee/utils": "3.12.3-beta.13"
101
+ "@crawlee/core": "$crawlee",
102
+ "@crawlee/types": "$crawlee",
103
+ "@crawlee/utils": "$crawlee"
104
104
  }
105
105
  }
106
106
  }
package/index.d.ts CHANGED
@@ -1,3 +1,2 @@
1
1
  export * from '@crawlee/http';
2
2
  export * from './internals/linkedom-crawler.js';
3
- //# sourceMappingURL=index.d.ts.map
package/index.js CHANGED
@@ -1,3 +1,2 @@
1
1
  export * from '@crawlee/http';
2
2
  export * from './internals/linkedom-crawler.js';
3
- //# sourceMappingURL=index.js.map
@@ -1,13 +1,13 @@
1
- import type { BasicCrawlingContext, EnqueueLinksOptions, ErrorHandler, GetUserDataFromRequest, HttpCrawlerOptions, InternalHttpCrawlingContext, InternalHttpHook, RequestHandler, RequestProvider, RouterRoutes, SkippedRequestCallback } from '@crawlee/http';
1
+ import type { AddRequestsBatchedResult, ContextPipeline, CrawlingContext, EnqueueLinksOptions, ErrorHandler, ExtractLinksOptions, GetUserDataFromRequest, HttpCrawlerOptions, InternalHttpCrawlingContext, InternalHttpHook, RequestHandler, RouterHandler, RouterRoutes, RouteSchemas, RoutesFromSchemas } from '@crawlee/http';
2
2
  import { HttpCrawler } from '@crawlee/http';
3
3
  import type { Dictionary } from '@crawlee/types';
4
- import { type CheerioRoot, type RobotsTxtFile } from '@crawlee/utils';
4
+ import type { CheerioAPI } from 'cheerio';
5
5
  export type LinkeDOMErrorHandler<UserData extends Dictionary = any, // with default to Dictionary we cant use a typed router in untyped crawler
6
- JSONData extends Dictionary = any> = ErrorHandler<LinkeDOMCrawlingContext<UserData, JSONData>>;
6
+ JSONData extends Dictionary = any, // with default to Dictionary we cant use a typed router in untyped crawler
7
+ ContextExtension = Dictionary<never>> = ErrorHandler<CrawlingContext, LinkeDOMCrawlingContext<UserData, JSONData> & ContextExtension>;
7
8
  export interface LinkeDOMCrawlerOptions<ContextExtension = Dictionary<never>, ExtendedContext extends LinkeDOMCrawlingContext = LinkeDOMCrawlingContext & ContextExtension, UserData extends Dictionary = any, // with default to Dictionary we cant use a typed router in untyped crawler
8
- JSONData extends Dictionary = any> extends HttpCrawlerOptions<LinkeDOMCrawlingContext<UserData, JSONData>, ContextExtension, ExtendedContext> {
9
- }
10
- export interface LinkeDOMCrawlerEnqueueLinksOptions extends Omit<EnqueueLinksOptions, 'urls' | 'requestQueue'> {
9
+ JSONData extends Dictionary = any, // with default to Dictionary we cant use a typed router in untyped crawler
10
+ Routes extends Record<keyof Routes, Dictionary> = Record<string, UserData>, StatisticStateExtension extends object = {}> extends HttpCrawlerOptions<LinkeDOMCrawlingContext<UserData, JSONData>, ContextExtension, ExtendedContext, Routes, StatisticStateExtension> {
11
11
  }
12
12
  export type LinkeDOMHook<UserData extends Dictionary = any, // with default to Dictionary we cant use a typed router in untyped crawler
13
13
  JSONData extends Dictionary = any> = InternalHttpHook<LinkeDOMCrawlingContext<UserData, JSONData>>;
@@ -41,7 +41,15 @@ JSONData extends Dictionary = any> extends InternalHttpCrawlingContext<UserData,
41
41
  * });
42
42
  * ```
43
43
  */
44
- parseWithCheerio(selector?: string, timeoutMs?: number): Promise<CheerioRoot>;
44
+ parseWithCheerio(selector?: string, timeoutMs?: number): Promise<CheerioAPI>;
45
+ /**
46
+ * Extracts URLs from the parsed DOM, without adding them to the request queue.
47
+ */
48
+ extractLinks(options?: ExtractLinksOptions): Promise<string[]>;
49
+ /**
50
+ * Helper function for extracting URLs from the parsed DOM and adding them to the request queue.
51
+ */
52
+ enqueueLinks(options?: EnqueueLinksOptions): Promise<AddRequestsBatchedResult>;
45
53
  }
46
54
  export type LinkeDOMRequestHandler<UserData extends Dictionary = any, // with default to Dictionary we cant use a typed router in untyped crawler
47
55
  JSONData extends Dictionary = any> = RequestHandler<LinkeDOMCrawlingContext<UserData, JSONData>>;
@@ -64,38 +72,40 @@ JSONData extends Dictionary = any> = RequestHandler<LinkeDOMCrawlingContext<User
64
72
  * and then invokes the user-provided {@link LinkeDOMCrawlerOptions.requestHandler} to extract page data
65
73
  * using the `window` object.
66
74
  *
67
- * The source URLs are represented using {@link Request} objects that are fed from
68
- * {@link RequestList} or {@link RequestQueue} instances provided by the {@link LinkeDOMCrawlerOptions.requestList}
69
- * or {@link LinkeDOMCrawlerOptions.requestQueue} constructor options, respectively.
75
+ * The source URLs are represented using {@link Request} objects that are fed from the
76
+ * {@link IRequestManager|request manager} provided via the {@link LinkeDOMCrawlerOptions.requestManager|`requestManager`}
77
+ * constructor option (a {@link RequestQueue} is itself a request manager). To read from a read-only source such
78
+ * as a {@link RequestList} while still being able to enqueue new requests, combine it with a queue into a
79
+ * {@link RequestManagerTandem} via {@link IRequestLoader.toTandem|`requestLoader.toTandem()`} and pass the
80
+ * result as `requestManager`.
70
81
  *
71
- * If both {@link LinkeDOMCrawlerOptions.requestList} and {@link LinkeDOMCrawlerOptions.requestQueue} are used,
72
- * the instance first processes URLs from the {@link RequestList} and automatically enqueues all of them
73
- * to {@link RequestQueue} before it starts their processing. This ensures that a single URL is not crawled multiple times.
82
+ * > The {@link LinkeDOMCrawlerOptions.requestList|`requestList`} and {@link LinkeDOMCrawlerOptions.requestQueue|`requestQueue`}
83
+ * > options are deprecated; they are still accepted and folded into a single `requestManager` for back-compat.
74
84
  *
75
85
  * The crawler finishes when there are no more {@link Request} objects to crawl.
76
86
  *
77
- * We can use the `preNavigationHooks` to adjust `gotOptions`:
87
+ * We can use the `preNavigationHooks` to adjust the crawling context before the request is made:
78
88
  *
79
89
  * ```
80
90
  * preNavigationHooks: [
81
- * (crawlingContext, gotOptions) => {
91
+ * (crawlingContext) => {
82
92
  * // ...
83
93
  * },
84
94
  * ]
85
95
  * ```
86
96
  *
87
- * By default, `LinkeDOMCrawler` only processes web pages with the `text/html`
88
- * and `application/xhtml+xml` MIME content types (as reported by the `Content-Type` HTTP header),
97
+ * By default, `LinkeDOMCrawler` only processes web pages with the `text/html`, `application/xhtml+xml`, `text/xml`, `application/xml`,
98
+ * and `application/json` MIME content types (as reported by the `Content-Type` HTTP header),
89
99
  * and skips pages with other content types. If you want the crawler to process other content types,
90
100
  * use the {@link LinkeDOMCrawlerOptions.additionalMimeTypes} constructor option.
91
101
  * Beware that the parsing behavior differs for HTML, XML, JSON and other types of content.
92
102
  * For more details, see {@link LinkeDOMCrawlerOptions.requestHandler}.
93
103
  *
94
- * New requests are only dispatched when there is enough free CPU and memory available,
95
- * using the functionality provided by the {@link AutoscaledPool} class.
96
- * All {@link AutoscaledPool} configuration options can be passed to the `autoscaledPoolOptions`
97
- * parameter of the `CheerioCrawler` constructor. For user convenience, the `minConcurrency` and `maxConcurrency`
98
- * {@link AutoscaledPool} options are available directly in the `CheerioCrawler` constructor.
104
+ * New requests are only dispatched when there is enough free CPU and memory available, as judged by the crawler's
105
+ * {@link ConcurrencySystem}.
106
+ * Concurrency is tuned via the `minConcurrency`, `maxConcurrency` and `maxRequestsPerMinute` options of the
107
+ * `LinkeDOMCrawler` constructor, or, for finer control, by injecting a pre-configured
108
+ * {@link ConcurrencySystem|`concurrencySystem`}.
99
109
  *
100
110
  * **Example usage:**
101
111
  *
@@ -115,30 +125,13 @@ JSONData extends Dictionary = any> = RequestHandler<LinkeDOMCrawlingContext<User
115
125
  * ```
116
126
  * @category Crawlers
117
127
  */
118
- export declare class LinkeDOMCrawler<ContextExtension = Dictionary<never>, ExtendedContext extends LinkeDOMCrawlingContext = LinkeDOMCrawlingContext & ContextExtension> extends HttpCrawler<LinkeDOMCrawlingContext, ContextExtension, ExtendedContext> {
119
- private static parser;
120
- constructor(options: LinkeDOMCrawlerOptions<ContextExtension, ExtendedContext>);
128
+ export declare class LinkeDOMCrawler<ContextExtension = Dictionary<never>, ExtendedContext extends LinkeDOMCrawlingContext = LinkeDOMCrawlingContext & ContextExtension, Routes extends Record<keyof Routes, Dictionary> = Record<string, GetUserDataFromRequest<LinkeDOMCrawlingContext['request']>>, StatisticStateExtension extends object = {}> extends HttpCrawler<LinkeDOMCrawlingContext, ContextExtension, ExtendedContext, Routes, StatisticStateExtension> {
129
+ #private;
130
+ constructor(options?: LinkeDOMCrawlerOptions<ContextExtension, ExtendedContext, any, any, Routes, StatisticStateExtension>);
131
+ protected buildContextPipeline(): ContextPipeline<CrawlingContext, LinkeDOMCrawlingContext>;
121
132
  private parseContent;
122
133
  private addHelpers;
123
134
  }
124
- interface EnqueueLinksInternalOptions {
125
- options?: EnqueueLinksOptions;
126
- window: Window | null;
127
- requestQueue: RequestProvider;
128
- robotsTxtFile?: RobotsTxtFile;
129
- onSkippedRequest?: SkippedRequestCallback;
130
- originalRequestUrl: string;
131
- finalRequestUrl?: string;
132
- }
133
- interface BoundEnqueueLinksInternalOptions {
134
- enqueueLinks: BasicCrawlingContext['enqueueLinks'];
135
- options?: EnqueueLinksOptions;
136
- window: Window | null;
137
- originalRequestUrl: string;
138
- finalRequestUrl?: string;
139
- }
140
- /** @internal */
141
- export declare function linkedomCrawlerEnqueueLinks(options: EnqueueLinksInternalOptions | BoundEnqueueLinksInternalOptions): Promise<unknown>;
142
135
  /**
143
136
  * Creates new {@link Router} instance that works based on request labels.
144
137
  * This instance can then serve as a `requestHandler` of your {@link LinkeDOMCrawler}.
@@ -163,7 +156,6 @@ export declare function linkedomCrawlerEnqueueLinks(options: EnqueueLinksInterna
163
156
  * await crawler.run();
164
157
  * ```
165
158
  */
166
- // @ts-ignore optional peer dependency or compatibility with es2022
167
- export declare function createLinkeDOMRouter<Context extends LinkeDOMCrawlingContext = LinkeDOMCrawlingContext, UserData extends Dictionary = GetUserDataFromRequest<Context['request']>>(routes?: RouterRoutes<Context, UserData>): import("@crawlee/http").RouterHandler<Context>;
168
- export {};
169
- //# sourceMappingURL=linkedom-crawler.d.ts.map
159
+ export declare function createLinkeDOMRouter<Context extends LinkeDOMCrawlingContext = LinkeDOMCrawlingContext, Routes extends Record<keyof Routes, Dictionary> = Record<string, GetUserDataFromRequest<Context['request']>>>(routes?: RouterRoutes<Context, Routes>): RouterHandler<Context, Routes>;
160
+ export declare function createLinkeDOMRouter<Context extends LinkeDOMCrawlingContext = LinkeDOMCrawlingContext, UserData extends Dictionary = GetUserDataFromRequest<Context['request']>>(routes?: RouterRoutes<Context, Record<string, UserData>>): RouterHandler<Context, Record<string, UserData>>;
161
+ export declare function createLinkeDOMRouter<Context extends LinkeDOMCrawlingContext = LinkeDOMCrawlingContext, const Schemas extends RouteSchemas = RouteSchemas>(schemas: Schemas): RouterHandler<Context, RoutesFromSchemas<Schemas>>;
@@ -1,5 +1,6 @@
1
- import { enqueueLinks, HttpCrawler, resolveBaseUrlForEnqueueLinksFiltering, Router, tryAbsoluteURL, } from '@crawlee/http';
1
+ import { EnqueueStrategy, HttpCrawler, NavigationSkippedError, resolveBaseUrlForEnqueueLinksFiltering, Router, } from '@crawlee/http';
2
2
  import { sleep } from '@crawlee/utils';
3
+ import { tryAbsoluteURL } from '@crawlee/utils/internal';
3
4
  import * as cheerio from 'cheerio';
4
5
  import { DOMParser } from 'linkedom/cached';
5
6
  /**
@@ -21,38 +22,40 @@ import { DOMParser } from 'linkedom/cached';
21
22
  * and then invokes the user-provided {@link LinkeDOMCrawlerOptions.requestHandler} to extract page data
22
23
  * using the `window` object.
23
24
  *
24
- * The source URLs are represented using {@link Request} objects that are fed from
25
- * {@link RequestList} or {@link RequestQueue} instances provided by the {@link LinkeDOMCrawlerOptions.requestList}
26
- * or {@link LinkeDOMCrawlerOptions.requestQueue} constructor options, respectively.
25
+ * The source URLs are represented using {@link Request} objects that are fed from the
26
+ * {@link IRequestManager|request manager} provided via the {@link LinkeDOMCrawlerOptions.requestManager|`requestManager`}
27
+ * constructor option (a {@link RequestQueue} is itself a request manager). To read from a read-only source such
28
+ * as a {@link RequestList} while still being able to enqueue new requests, combine it with a queue into a
29
+ * {@link RequestManagerTandem} via {@link IRequestLoader.toTandem|`requestLoader.toTandem()`} and pass the
30
+ * result as `requestManager`.
27
31
  *
28
- * If both {@link LinkeDOMCrawlerOptions.requestList} and {@link LinkeDOMCrawlerOptions.requestQueue} are used,
29
- * the instance first processes URLs from the {@link RequestList} and automatically enqueues all of them
30
- * to {@link RequestQueue} before it starts their processing. This ensures that a single URL is not crawled multiple times.
32
+ * > The {@link LinkeDOMCrawlerOptions.requestList|`requestList`} and {@link LinkeDOMCrawlerOptions.requestQueue|`requestQueue`}
33
+ * > options are deprecated; they are still accepted and folded into a single `requestManager` for back-compat.
31
34
  *
32
35
  * The crawler finishes when there are no more {@link Request} objects to crawl.
33
36
  *
34
- * We can use the `preNavigationHooks` to adjust `gotOptions`:
37
+ * We can use the `preNavigationHooks` to adjust the crawling context before the request is made:
35
38
  *
36
39
  * ```
37
40
  * preNavigationHooks: [
38
- * (crawlingContext, gotOptions) => {
41
+ * (crawlingContext) => {
39
42
  * // ...
40
43
  * },
41
44
  * ]
42
45
  * ```
43
46
  *
44
- * By default, `LinkeDOMCrawler` only processes web pages with the `text/html`
45
- * and `application/xhtml+xml` MIME content types (as reported by the `Content-Type` HTTP header),
47
+ * By default, `LinkeDOMCrawler` only processes web pages with the `text/html`, `application/xhtml+xml`, `text/xml`, `application/xml`,
48
+ * and `application/json` MIME content types (as reported by the `Content-Type` HTTP header),
46
49
  * and skips pages with other content types. If you want the crawler to process other content types,
47
50
  * use the {@link LinkeDOMCrawlerOptions.additionalMimeTypes} constructor option.
48
51
  * Beware that the parsing behavior differs for HTML, XML, JSON and other types of content.
49
52
  * For more details, see {@link LinkeDOMCrawlerOptions.requestHandler}.
50
53
  *
51
- * New requests are only dispatched when there is enough free CPU and memory available,
52
- * using the functionality provided by the {@link AutoscaledPool} class.
53
- * All {@link AutoscaledPool} configuration options can be passed to the `autoscaledPoolOptions`
54
- * parameter of the `CheerioCrawler` constructor. For user convenience, the `minConcurrency` and `maxConcurrency`
55
- * {@link AutoscaledPool} options are available directly in the `CheerioCrawler` constructor.
54
+ * New requests are only dispatched when there is enough free CPU and memory available, as judged by the crawler's
55
+ * {@link ConcurrencySystem}.
56
+ * Concurrency is tuned via the `minConcurrency`, `maxConcurrency` and `maxRequestsPerMinute` options of the
57
+ * `LinkeDOMCrawler` constructor, or, for finer control, by injecting a pre-configured
58
+ * {@link ConcurrencySystem|`concurrencySystem`}.
56
59
  *
57
60
  * **Example usage:**
58
61
  *
@@ -73,42 +76,76 @@ import { DOMParser } from 'linkedom/cached';
73
76
  * @category Crawlers
74
77
  */
75
78
  export class LinkeDOMCrawler extends HttpCrawler {
76
- static parser = new DOMParser();
77
- constructor(options) {
79
+ static #parser = new DOMParser();
80
+ constructor(options = {}) {
81
+ const { contextPipelineBuilder, ...rest } = options;
78
82
  super({
79
- ...options,
80
- contextPipelineBuilder: () => this.buildContextPipeline()
81
- .compose({
82
- action: async (context) => this.parseContent(context),
83
- })
84
- .compose({ action: async (context) => this.addHelpers(context) }),
83
+ ...rest,
84
+ contextPipelineBuilder: contextPipelineBuilder ?? (() => this.buildContextPipeline()),
85
85
  });
86
86
  }
87
+ buildContextPipeline() {
88
+ return super
89
+ .buildContextPipeline()
90
+ .compose({
91
+ action: async (context) => this.parseContent(context),
92
+ })
93
+ .compose({ action: async (context) => this.addHelpers(context) });
94
+ }
87
95
  async parseContent(crawlingContext) {
88
- const isXml = crawlingContext.contentType.type.includes('xml');
89
- const document = LinkeDOMCrawler.parser.parseFromString(crawlingContext.body.toString(), isXml ? 'text/xml' : 'text/html');
90
- return {
91
- window: document.defaultView,
92
- get body() {
93
- return document.documentElement.outerHTML;
94
- },
95
- get document() {
96
- // See comment about typing in LinkeDOMCrawlingContext definition
97
- return document;
98
- },
99
- };
96
+ try {
97
+ const isXml = crawlingContext.contentType.type.includes('xml');
98
+ const document = LinkeDOMCrawler.#parser.parseFromString(crawlingContext.body.toString(), isXml ? 'text/xml' : 'text/html');
99
+ return {
100
+ window: document.defaultView,
101
+ get body() {
102
+ return document.documentElement.outerHTML;
103
+ },
104
+ get document() {
105
+ // See comment about typing in LinkeDOMCrawlingContext definition
106
+ return document;
107
+ },
108
+ };
109
+ }
110
+ catch (err) {
111
+ if (err instanceof NavigationSkippedError) {
112
+ return {
113
+ get window() {
114
+ throw new NavigationSkippedError('The `window` property is not available - `skipNavigation` was used', { cause: err });
115
+ },
116
+ get body() {
117
+ throw new NavigationSkippedError('The `body` property is not available - `skipNavigation` was used', { cause: err });
118
+ },
119
+ get document() {
120
+ throw new NavigationSkippedError('The `document` property is not available - `skipNavigation` was used', { cause: err });
121
+ },
122
+ };
123
+ }
124
+ throw err;
125
+ }
100
126
  }
101
127
  async addHelpers(crawlingContext) {
128
+ const addRequests = crawlingContext.addRequests;
129
+ const extractLinks = async (options) => {
130
+ if (!crawlingContext.window) {
131
+ throw new Error('Cannot extract links because the DOM is not available.');
132
+ }
133
+ return extractUrlsFromWindow(crawlingContext.window, options?.selector ?? 'a', options?.baseUrl ?? crawlingContext.request.loadedUrl ?? crawlingContext.request.url);
134
+ };
102
135
  return {
103
- enqueueLinks: async (enqueueOptions) => {
104
- return linkedomCrawlerEnqueueLinks({
105
- options: { ...enqueueOptions, limit: this.calculateEnqueuedRequestLimit(enqueueOptions?.limit) },
106
- window: document.defaultView,
107
- requestQueue: await this.getRequestQueue(),
108
- robotsTxtFile: await this.getRobotsTxtFileForUrl(crawlingContext.request.url),
109
- onSkippedRequest: this.handleSkippedRequest,
110
- originalRequestUrl: crawlingContext.request.url,
136
+ extractLinks,
137
+ enqueueLinks: async (options = {}) => {
138
+ const baseUrl = resolveBaseUrlForEnqueueLinksFiltering({
139
+ enqueueStrategy: options.strategy,
111
140
  finalRequestUrl: crawlingContext.request.loadedUrl,
141
+ originalRequestUrl: crawlingContext.request.url,
142
+ userProvidedBaseUrl: options.baseUrl,
143
+ });
144
+ const urls = await extractLinks(options);
145
+ return addRequests(urls, {
146
+ ...options,
147
+ baseUrl,
148
+ strategy: options.strategy ?? EnqueueStrategy.SameHostname,
112
149
  });
113
150
  },
114
151
  async waitForSelector(selector, timeoutMs = 5_000) {
@@ -132,39 +169,6 @@ export class LinkeDOMCrawler extends HttpCrawler {
132
169
  };
133
170
  }
134
171
  }
135
- /** @internal */
136
- function containsEnqueueLinks(options) {
137
- return !!options.enqueueLinks;
138
- }
139
- /** @internal */
140
- export async function linkedomCrawlerEnqueueLinks(options) {
141
- const { options: enqueueLinksOptions, window, originalRequestUrl, finalRequestUrl } = options;
142
- if (!window) {
143
- throw new Error('Cannot enqueue links because the DOM is not available.');
144
- }
145
- const baseUrl = resolveBaseUrlForEnqueueLinksFiltering({
146
- enqueueStrategy: enqueueLinksOptions?.strategy,
147
- finalRequestUrl,
148
- originalRequestUrl,
149
- userProvidedBaseUrl: enqueueLinksOptions?.baseUrl,
150
- });
151
- const urls = extractUrlsFromWindow(window, enqueueLinksOptions?.selector ?? 'a', enqueueLinksOptions?.baseUrl ?? finalRequestUrl ?? originalRequestUrl);
152
- if (containsEnqueueLinks(options)) {
153
- return options.enqueueLinks({
154
- urls,
155
- baseUrl,
156
- ...enqueueLinksOptions,
157
- });
158
- }
159
- return enqueueLinks({
160
- requestQueue: options.requestQueue,
161
- robotsTxtFile: options.robotsTxtFile,
162
- onSkippedRequest: options.onSkippedRequest,
163
- urls,
164
- baseUrl,
165
- ...enqueueLinksOptions,
166
- });
167
- }
168
172
  /**
169
173
  * Extracts URLs from a given Window object.
170
174
  * @ignore
@@ -181,31 +185,6 @@ function extractUrlsFromWindow(window, selector, baseUrl) {
181
185
  })
182
186
  .filter((href) => href !== undefined && href !== '');
183
187
  }
184
- /**
185
- * Creates new {@link Router} instance that works based on request labels.
186
- * This instance can then serve as a `requestHandler` of your {@link LinkeDOMCrawler}.
187
- * Defaults to the {@link LinkeDOMCrawlingContext}.
188
- *
189
- * > Serves as a shortcut for using `Router.create<LinkeDOMCrawlingContext>()`.
190
- *
191
- * ```ts
192
- * import { LinkeDOMCrawler, createLinkeDOMRouter } from 'crawlee';
193
- *
194
- * const router = createLinkeDOMRouter();
195
- * router.addHandler('label-a', async (ctx) => {
196
- * ctx.log.info('...');
197
- * });
198
- * router.addDefaultHandler(async (ctx) => {
199
- * ctx.log.info('...');
200
- * });
201
- *
202
- * const crawler = new LinkeDOMCrawler({
203
- * requestHandler: router,
204
- * });
205
- * await crawler.run();
206
- * ```
207
- */
208
- export function createLinkeDOMRouter(routes) {
209
- return Router.create(routes);
188
+ export function createLinkeDOMRouter(routesOrSchemas) {
189
+ return Router.create(routesOrSchemas);
210
190
  }
211
- //# sourceMappingURL=linkedom-crawler.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@crawlee/linkedom",
3
- "version": "4.0.0-beta.16",
3
+ "version": "4.0.0-beta.161",
4
4
  "description": "The scalable web crawling and scraping library for JavaScript/Node.js. Enables development of data extraction and web automation jobs (not only) with headless Chrome and Puppeteer.",
5
5
  "engines": {
6
6
  "node": ">=22.0.0"
@@ -38,7 +38,7 @@
38
38
  },
39
39
  "homepage": "https://crawlee.dev",
40
40
  "scripts": {
41
- "build": "yarn clean && yarn compile && yarn copy",
41
+ "build": "pnpm clean && pnpm compile && pnpm copy",
42
42
  "clean": "rimraf ./dist",
43
43
  "compile": "tsc -p tsconfig.build.json",
44
44
  "copy": "tsx ../../scripts/copy.ts"
@@ -47,12 +47,13 @@
47
47
  "access": "public"
48
48
  },
49
49
  "dependencies": {
50
- "@apify/timeout": "^0.3.2",
50
+ "@apify/timeout": "^0.4.4",
51
51
  "@apify/utilities": "^2.15.5",
52
- "@crawlee/http": "4.0.0-beta.16",
53
- "@crawlee/types": "4.0.0-beta.16",
52
+ "@crawlee/http": "4.0.0-beta.161",
53
+ "@crawlee/types": "4.0.0-beta.161",
54
+ "@crawlee/utils": "4.0.0-beta.161",
55
+ "cheerio": "^1.0.0",
54
56
  "linkedom": "^0.18.10",
55
- "ow": "^2.0.0",
56
57
  "tslib": "^2.8.1"
57
58
  },
58
59
  "lerna": {
@@ -62,5 +63,5 @@
62
63
  }
63
64
  }
64
65
  },
65
- "gitHead": "65b235c9bdcf0521e0fbae05c77f4adaa89c45e0"
66
+ "gitHead": "dc353e294d5f4d2ee468325ef11dd7af44443be2"
66
67
  }
package/index.d.ts.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,eAAe,CAAC;AAC9B,cAAc,iCAAiC,CAAC"}
package/index.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,eAAe,CAAC;AAC9B,cAAc,iCAAiC,CAAC"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"linkedom-crawler.d.ts","sourceRoot":"","sources":["../../src/internals/linkedom-crawler.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACR,oBAAoB,EACpB,mBAAmB,EACnB,YAAY,EACZ,sBAAsB,EACtB,kBAAkB,EAClB,2BAA2B,EAC3B,gBAAgB,EAChB,cAAc,EACd,eAAe,EACf,YAAY,EACZ,sBAAsB,EACzB,MAAM,eAAe,CAAC;AACvB,OAAO,EAEH,WAAW,EAId,MAAM,eAAe,CAAC;AACvB,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AACjD,OAAO,EAAE,KAAK,WAAW,EAAE,KAAK,aAAa,EAAS,MAAM,gBAAgB,CAAC;AAI7E,MAAM,MAAM,oBAAoB,CAC5B,QAAQ,SAAS,UAAU,GAAG,GAAG,EAAE,2EAA2E;AAC9G,QAAQ,SAAS,UAAU,GAAG,GAAG,IACjC,YAAY,CAAC,uBAAuB,CAAC,QAAQ,EAAE,QAAQ,CAAC,CAAC,CAAC;AAE9D,MAAM,WAAW,sBAAsB,CACnC,gBAAgB,GAAG,UAAU,CAAC,KAAK,CAAC,EACpC,eAAe,SAAS,uBAAuB,GAAG,uBAAuB,GAAG,gBAAgB,EAC5F,QAAQ,SAAS,UAAU,GAAG,GAAG,EAAE,2EAA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