Elffuss BraidHub

kikocis/continue public

main · 6.8 KiBRawPermalink
1import * as fs from "fs";
2import { URL } from "node:url";
3
4import { Handler, HTTPResponse, Page } from "puppeteer";
5
6// @ts-ignore
7// @prettier-ignore
8import PCR from "puppeteer-chromium-resolver";
9
10import { ContinueConfig, IDE } from "../../..";
11import {
12 editConfigFile,
13 getChromiumPath,
14 getContinueUtilsPath,
15} from "../../../util/paths";
16import { PageData } from "./DocsCrawler";
17
18export class ChromiumCrawler {
19 private readonly LINK_GROUP_SIZE = 2;
20 private curCrawlCount = 0;
21
22 constructor(
23 private readonly startUrl: URL,
24 private readonly maxRequestsPerCrawl: number,
25 private readonly maxDepth: number,
26 ) {}
27
28 static setUseChromiumForDocsCrawling(useChromiumForDocsCrawling: boolean) {
29 editConfigFile(
30 (config) => ({
31 ...config,
32 experimental: {
33 ...config.experimental,
34 useChromiumForDocsCrawling,
35 },
36 }),
37 (config) => config, // Not used in config.yaml
38 );
39 }
40
41 async *crawl(): AsyncGenerator<PageData> {
42 console.debug(
43 `[${(this.constructor as any).name}] Crawling site: ${this.startUrl}`,
44 );
45
46 const stats = await PCR(ChromiumInstaller.PCR_CONFIG);
47 const browser = await stats.puppeteer.launch({
48 args: [
49 "--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36",
50 ],
51 executablePath: stats.executablePath,
52 });
53 const page = await browser.newPage();
54
55 try {
56 yield* this.crawlSitePages(page, this.startUrl, 0);
57 } catch (e) {
58 console.debug("Error getting links: ", e);
59 console.debug(
60 "Setting 'useChromiumForDocsCrawling' to 'false' in config.json",
61 );
62
63 ChromiumCrawler.setUseChromiumForDocsCrawling(false);
64 } finally {
65 await browser.close();
66 }
67 }
68
69 /**
70 * We need to handle redirects manually, otherwise there are race conditions.
71 *
72 * https://github.com/puppeteer/puppeteer/issues/3323#issuecomment-2332333573
73 */
74 private async gotoPageAndHandleRedirects(page: Page, url: string) {
75 const MAX_PAGE_WAIT_MS = 5000;
76
77 await page.goto(url, {
78 timeout: 0,
79 waitUntil: "networkidle2",
80 });
81
82 let responseEventOccurred = false;
83 const responseHandler: Handler<HTTPResponse> = (event) =>
84 (responseEventOccurred = true);
85
86 const responseWatcher = new Promise<void>(function (resolve, reject) {
87 setTimeout(() => {
88 if (!responseEventOccurred) {
89 resolve();
90 } else {
91 setTimeout(() => resolve(), MAX_PAGE_WAIT_MS);
92 }
93 }, 500);
94 });
95
96 page.on("response", responseHandler);
97
98 await Promise.race([responseWatcher, page.waitForNavigation()]);
99 }
100
101 private async *crawlSitePages(
102 page: Page,
103 curUrl: URL,
104 depth: number,
105 visitedLinks: Set<string> = new Set(),
106 ): AsyncGenerator<PageData> {
107 const urlStr = curUrl.toString();
108
109 if (visitedLinks.has(urlStr)) {
110 return;
111 }
112
113 await this.gotoPageAndHandleRedirects(page, urlStr);
114
115 const htmlContent = await page.content();
116 const linkGroups = await this.getLinkGroupsFromPage(page, curUrl);
117 this.curCrawlCount++;
118
119 visitedLinks.add(urlStr);
120
121 yield {
122 path: curUrl.pathname,
123 url: urlStr,
124 content: htmlContent,
125 };
126
127 for (const linkGroup of linkGroups) {
128 let enqueuedLinkCount = this.curCrawlCount;
129
130 for (const link of linkGroup) {
131 enqueuedLinkCount++;
132 // console.log({ enqueuedLinkCount, url: this.startUrl.toString() });
133 if (
134 enqueuedLinkCount <= this.maxRequestsPerCrawl &&
135 depth <= this.maxDepth
136 ) {
137 yield* this.crawlSitePages(
138 page,
139 new URL(link),
140 depth + 1,
141 visitedLinks,
142 );
143 }
144 }
145 }
146 }
147
148 private stripHashFromUrl(urlStr: string) {
149 try {
150 let url = new URL(urlStr);
151 url.hash = "";
152 return url;
153 } catch (err) {
154 return null;
155 }
156 }
157
158 private isValidHostAndPath(newUrl: URL, curUrl: URL) {
159 return (
160 newUrl.pathname.startsWith(curUrl.pathname) && newUrl.host === curUrl.host
161 );
162 }
163
164 private async getLinksFromPage(page: Page, curUrl: URL) {
165 const links = await page.$$eval("a", (links) => links.map((a) => a.href));
166
167 const cleanedLinks = links
168 .map(this.stripHashFromUrl)
169 .filter(
170 (newUrl) =>
171 newUrl !== null &&
172 this.isValidHostAndPath(newUrl, curUrl) &&
173 newUrl !== curUrl,
174 )
175 .map((newUrl) => (newUrl as URL).href);
176
177 const dedupedLinks = Array.from(new Set(cleanedLinks));
178
179 return dedupedLinks;
180 }
181
182 private async getLinkGroupsFromPage(page: Page, curUrl: URL) {
183 const links = await this.getLinksFromPage(page, curUrl);
184
185 const groups = links.reduce((acc, link, i) => {
186 const groupIndex = Math.floor(i / this.LINK_GROUP_SIZE);
187
188 if (!acc[groupIndex]) {
189 acc.push([]);
190 }
191
192 acc[groupIndex].push(link);
193
194 return acc;
195 }, [] as string[][]);
196
197 return groups;
198 }
199}
200
201export class ChromiumInstaller {
202 static PCR_CONFIG = { downloadPath: getContinueUtilsPath() };
203
204 constructor(
205 private readonly ide: IDE,
206 private readonly config: ContinueConfig,
207 ) {
208 if (this.shouldInstallOnStartup()) {
209 console.log("Installing Chromium");
210 void this.install();
211 }
212 }
213
214 isInstalled() {
215 return fs.existsSync(getChromiumPath());
216 }
217
218 shouldInstallOnStartup() {
219 return (
220 !this.isInstalled() &&
221 this.config.experimental?.useChromiumForDocsCrawling
222 );
223 }
224
225 shouldProposeUseChromiumOnCrawlFailure() {
226 const { experimental } = this.config;
227
228 return (
229 experimental?.useChromiumForDocsCrawling === undefined ||
230 experimental.useChromiumForDocsCrawling
231 );
232 }
233
234 async proposeAndAttemptInstall(site: string) {
235 const userAcceptedInstall = await this.proposeInstall(site);
236
237 if (userAcceptedInstall) {
238 const didInstall = await this.install();
239 return didInstall;
240 }
241 }
242
243 async install() {
244 try {
245 await PCR(ChromiumInstaller.PCR_CONFIG);
246
247 ChromiumCrawler.setUseChromiumForDocsCrawling(true);
248
249 return true;
250 } catch (error) {
251 console.debug("Error installing Chromium : ", error);
252 console.debug(
253 "Setting 'useChromiumForDocsCrawling' to 'false' in config.json",
254 );
255
256 ChromiumCrawler.setUseChromiumForDocsCrawling(false);
257
258 void this.ide.showToast("error", "Failed to install Chromium");
259
260 return false;
261 }
262 }
263
264 private async proposeInstall(site: string) {
265 const msg =
266 `Unable to crawl documentation site: "${site}".` +
267 "We recommend installing Chromium. " +
268 "Download progress can be viewed in the developer console.";
269
270 const actionMsg = "Install Chromium";
271
272 const res = await this.ide.showToast("warning", msg, actionMsg);
273
274 return res === actionMsg;
275 }
276}