Elffuss BraidHub

kikocis/continue public

main · 3.6 KiBRawPermalink
1import { URL } from "node:url";
2
3import * as cheerio from "cheerio";
4
5import { PageData } from "./DocsCrawler";
6
7export default class CheerioCrawler {
8 private readonly IGNORE_PATHS_ENDING_IN = [
9 "favicon.ico",
10 "robots.txt",
11 ".rst.txt",
12 "genindex",
13 "py-modindex",
14 "search.html",
15 "search",
16 "genindex.html",
17 "changelog",
18 "changelog.html",
19 ];
20
21 constructor(
22 private readonly startUrl: URL,
23 private readonly maxRequestsPerCrawl: number,
24 private readonly maxDepth: number,
25 ) {}
26
27 async *crawl(): AsyncGenerator<PageData> {
28 let currentPageCount = 0;
29 console.log(
30 `[${
31 (this.constructor as any).name
32 }] Starting crawl from: ${this.startUrl} - Max Depth: ${this.maxDepth}`,
33 );
34
35 const { baseUrl, basePath } = this.splitUrl(this.startUrl);
36
37 let paths: { path: string; depth: number }[] = [
38 { path: basePath, depth: 0 },
39 ];
40
41 let index = 0;
42
43 while (index < paths.length) {
44 const batch = paths.slice(index, index + 50);
45
46 try {
47 const promises = batch.map(({ path, depth }) =>
48 this.getLinksFromUrl(baseUrl, path).then((links) => ({
49 links,
50 path,
51 depth,
52 })),
53 );
54
55 const results = await Promise.all(promises);
56 for (const {
57 links: { html, links: linksArray },
58 path,
59 depth,
60 } of results) {
61 if (html !== "" && depth <= this.maxDepth) {
62 yield { url: this.startUrl.toString(), path, content: html };
63 currentPageCount++;
64 if (currentPageCount >= this.maxRequestsPerCrawl) {
65 console.log("Crawl completed - max requests reached");
66 return;
67 }
68 }
69
70 if (depth < this.maxDepth) {
71 for (let link of linksArray) {
72 if (!paths.some((p) => p.path === link)) {
73 paths.push({ path: link, depth: depth + 1 });
74 }
75 }
76 }
77 }
78 } catch (e) {
79 console.debug("Error while crawling page: ", e);
80 }
81
82 index += batch.length;
83 }
84
85 console.log("Crawl completed");
86 }
87
88 private async getLinksFromUrl(url: string, path: string) {
89 const baseUrl = new URL(url);
90 const location = new URL(path, url);
91 let response;
92
93 try {
94 response = await fetch(location.toString());
95 } catch (error: unknown) {
96 if (
97 error instanceof Error &&
98 error.message.includes("maximum redirect")
99 ) {
100 console.error(
101 `[${
102 (this.constructor as any).name
103 }] Maximum redirect reached for: ${location.toString()}`,
104 );
105 return { html: "", links: [] };
106 }
107 console.error(error);
108 return { html: "", links: [] };
109 }
110 if (!response.ok) {
111 return { html: "", links: [] };
112 }
113 const html = await response.text();
114 let links: string[] = [];
115
116 if (url.includes("github.com")) {
117 return { html, links };
118 }
119
120 const $ = cheerio.load(html);
121
122 $("a").each((_: any, element: any) => {
123 const href = $(element).attr("href");
124 if (!href) {
125 return;
126 }
127
128 const parsedUrl = new URL(href, location);
129 if (parsedUrl.hostname === baseUrl.hostname) {
130 links.push(parsedUrl.pathname);
131 }
132 });
133
134 links = [...new Set(links)].filter((link) => {
135 return (
136 !link.includes("#") &&
137 !this.IGNORE_PATHS_ENDING_IN.some((ending) => link.endsWith(ending))
138 );
139 });
140 return { html, links };
141 }
142
143 private splitUrl(url: URL) {
144 const baseUrl = new URL("/", url).href;
145 const basePath = url.pathname;
146 return { baseUrl, basePath };
147 }
148}