feat: use crawlee for docs service
This commit is contained in:
parent
4bb1846676
commit
a51c520dee
17 changed files with 2516 additions and 504 deletions
12
core/core.ts
12
core/core.ts
|
|
@ -27,6 +27,10 @@ import type { IMessenger, Message } from "./util/messenger";
|
|||
import { editConfigJson } from "./util/paths";
|
||||
import { Telemetry } from "./util/posthog";
|
||||
import { streamDiffLines } from "./util/verticalEdit";
|
||||
import {
|
||||
installChromium,
|
||||
isChromiumInstalled,
|
||||
} from "./indexing/docs/installChromium";
|
||||
|
||||
export class Core {
|
||||
// implements IMessenger<ToCoreProtocol, FromCoreProtocol>
|
||||
|
|
@ -167,6 +171,14 @@ export class Core {
|
|||
(..._) => Promise.resolve([]),
|
||||
);
|
||||
|
||||
try {
|
||||
if (!isChromiumInstalled()) {
|
||||
installChromium();
|
||||
}
|
||||
} catch (err) {
|
||||
console.debug(`Failed to install Chromium: ${err}`);
|
||||
}
|
||||
|
||||
const on = this.messenger.on.bind(this.messenger);
|
||||
|
||||
this.messenger.onError((err) => {
|
||||
|
|
|
|||
|
|
@ -22,7 +22,7 @@ import {
|
|||
import { Telemetry } from "../../util/posthog.js";
|
||||
import TransformersJsEmbeddingsProvider from "../embeddings/TransformersJsEmbeddingsProvider.js";
|
||||
import { Article, chunkArticle, pageToArticle } from "./article.js";
|
||||
import { crawlPage } from "./crawl.js";
|
||||
import { crawlSite } from "./crawlSite.js";
|
||||
import { runLanceMigrations, runSqliteMigrations } from "./migrations.js";
|
||||
import {
|
||||
downloadFromS3,
|
||||
|
|
@ -202,11 +202,36 @@ export default class DocsService {
|
|||
let processedPages = 0;
|
||||
let maxKnownPages = 1;
|
||||
|
||||
// crawlSite(
|
||||
// new URL(startUrl),
|
||||
// siteIndexingConfig.maxDepth,
|
||||
// async function* (page) {
|
||||
// processedPages++;
|
||||
|
||||
// const article = pageToArticle(page);
|
||||
|
||||
// if (article) {
|
||||
// articles.push(article);
|
||||
// }
|
||||
|
||||
// // Use a heuristic approach for progress calculation
|
||||
// const progress = Math.min(processedPages / maxKnownPages, 1);
|
||||
|
||||
// yield {
|
||||
// progress, // Yield the heuristic progress
|
||||
// desc: `Finding subpages (${page.path})`,
|
||||
// status: "indexing",
|
||||
// };
|
||||
|
||||
// // Increase maxKnownPages to delay progress reaching 100% too soon
|
||||
// if (processedPages === maxKnownPages) {
|
||||
// maxKnownPages *= 2;
|
||||
// }
|
||||
// },
|
||||
// );
|
||||
|
||||
// Crawl pages and retrieve info as articles
|
||||
for await (const page of crawlPage(
|
||||
new URL(startUrl),
|
||||
siteIndexingConfig.maxDepth,
|
||||
)) {
|
||||
for await (const page of crawlSite(startUrl)) {
|
||||
processedPages++;
|
||||
|
||||
const article = pageToArticle(page);
|
||||
|
|
@ -521,8 +546,9 @@ export default class DocsService {
|
|||
private async getLanceTableNameFromEmbeddingsProvider(
|
||||
isPreIndexedDoc: boolean,
|
||||
) {
|
||||
const embeddingsProvider =
|
||||
await this.getEmbeddingsProvider(isPreIndexedDoc);
|
||||
const embeddingsProvider = await this.getEmbeddingsProvider(
|
||||
isPreIndexedDoc,
|
||||
);
|
||||
const embeddingsProviderId = this.removeInvalidLanceTableNameChars(
|
||||
embeddingsProvider.id,
|
||||
);
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@ import { Readability } from "@mozilla/readability";
|
|||
import { JSDOM } from "jsdom";
|
||||
import { Chunk } from "../../index.js";
|
||||
import { cleanFragment, cleanHeader } from "../chunk/markdown.js";
|
||||
import { PageData } from "./crawl.js";
|
||||
import { PageData } from "./crawlSite.js";
|
||||
|
||||
export type ArticleComponent = {
|
||||
title: string;
|
||||
|
|
@ -148,7 +148,7 @@ export function stringToArticle(
|
|||
|
||||
export function pageToArticle(page: PageData): Article | undefined {
|
||||
try {
|
||||
return stringToArticle(page.url, page.html, page.path);
|
||||
return stringToArticle(page.url, page.content, page.path);
|
||||
} catch (err) {
|
||||
console.error("Error converting URL to article components", err);
|
||||
return undefined;
|
||||
|
|
|
|||
|
|
@ -1,103 +0,0 @@
|
|||
import { crawlPage, PageData } from "../../indexing/docs/crawl";
|
||||
|
||||
describe("crawlPage - GitHub repository", () => {
|
||||
const repoUrl = new URL(
|
||||
"https://github.com/Patrick-Erichsen/test-github-repo-for-crawling",
|
||||
);
|
||||
const maxDepth = 3;
|
||||
let crawlResults: PageData[];
|
||||
|
||||
beforeAll(async () => {
|
||||
crawlResults = [];
|
||||
for await (const page of crawlPage(repoUrl, maxDepth)) {
|
||||
crawlResults.push(page);
|
||||
}
|
||||
}, 30000);
|
||||
|
||||
test("finds expected markdown files", async () => {
|
||||
expect(crawlResults.some((page) => page.path.endsWith("README.md"))).toBe(
|
||||
true,
|
||||
);
|
||||
|
||||
expect(
|
||||
crawlResults.some((page) => page.path.endsWith("docs-depth-1.md")),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
test("html includes the correct content", async () => {
|
||||
const doc = crawlResults.find((page) =>
|
||||
page.path.endsWith("docs-depth-1.md"),
|
||||
);
|
||||
|
||||
expect(doc?.html.includes("Test body")).toBe(true);
|
||||
expect(doc?.html.includes("Test H2 Header")).toBe(true);
|
||||
});
|
||||
|
||||
// This test is currently failing, `maxDepth` does not appear to be followed right now
|
||||
test.todo(
|
||||
"ignores files past the max depth",
|
||||
// , () => {
|
||||
// expect(
|
||||
// crawlResults.some((page) => page.path.includes("docs-depth-3")),
|
||||
// ).toBe(false);
|
||||
// }
|
||||
);
|
||||
|
||||
test("ignores non-markdown files, e.g. `test.js` at the root", async () => {
|
||||
expect(crawlResults.some((page) => page.path.endsWith("test.js"))).toBe(
|
||||
false,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
async function testSite(url: string, expectedPaths: string[]) {
|
||||
test(`crawlPage - ${url}`, async () => {
|
||||
const crawlResults: PageData[] = [];
|
||||
for await (const page of crawlPage(new URL(url))) {
|
||||
crawlResults.push(page);
|
||||
}
|
||||
|
||||
console.log(crawlResults.map((page) => page.path));
|
||||
|
||||
// Check if all expected paths are found
|
||||
for (const expectedPath of expectedPaths) {
|
||||
expect(
|
||||
crawlResults.some((page) => page.path.endsWith(expectedPath)),
|
||||
).toBe(true);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
const SITES: { [rootUrl: string]: string[] } = {
|
||||
"https://docs.continue.dev": [
|
||||
"intro",
|
||||
"quickstart",
|
||||
"features/tab-autocomplete",
|
||||
"reference/Model%20Providers/mistral",
|
||||
],
|
||||
// Failing
|
||||
// "https://docs.nestjs.com/": ["first-steps"],
|
||||
// Taking too much time
|
||||
// "https://go.dev/doc/": ["install", "tutorial/getting-started", "comment"],
|
||||
// Taking too much time
|
||||
// "https://clickhouse.com/docs": [
|
||||
// "intro",
|
||||
// "getting-started/quick-start",
|
||||
// "migrations/bigquery/migrating-to-clickhouse-cloud",
|
||||
// ],
|
||||
// Taking too much time
|
||||
// "https://www.tensorflow.org/api_docs": ["python/tf/Variable"],
|
||||
// "https://www.rust-lang.org/learn": []
|
||||
// Taking too long
|
||||
// "https://docs.anthropic.com/en/docs": [
|
||||
// "welcome",
|
||||
// "quickstart",
|
||||
// "build-with-claude/prompt-engineering/prompt-generator",
|
||||
// ],
|
||||
};
|
||||
|
||||
describe.only("crawlPage should return expected subpages for common sites", () => {
|
||||
for (const [rootUrl, expectedPaths] of Object.entries(SITES)) {
|
||||
testSite(rootUrl, expectedPaths);
|
||||
}
|
||||
});
|
||||
|
|
@ -1,212 +0,0 @@
|
|||
import { Octokit } from "@octokit/rest";
|
||||
import cheerio from "cheerio";
|
||||
import fetch from "node-fetch";
|
||||
import { URL } from "node:url";
|
||||
|
||||
const IGNORE_PATHS_ENDING_IN = [
|
||||
"favicon.ico",
|
||||
"robots.txt",
|
||||
".rst.txt",
|
||||
"genindex",
|
||||
"py-modindex",
|
||||
"search.html",
|
||||
"search",
|
||||
"genindex.html",
|
||||
"changelog",
|
||||
"changelog.html",
|
||||
];
|
||||
|
||||
const markdownRegex = new RegExp(/\.(md|mdx)$/);
|
||||
|
||||
async function getDefaultBranch(owner: string, repo: string): Promise<string> {
|
||||
const octokit = new Octokit({ auth: undefined });
|
||||
|
||||
const repoInfo = await octokit.repos.get({
|
||||
owner,
|
||||
repo,
|
||||
});
|
||||
|
||||
return repoInfo.data.default_branch;
|
||||
}
|
||||
|
||||
async function crawlGithubRepo(baseUrl: URL) {
|
||||
const octokit = new Octokit({
|
||||
auth: undefined,
|
||||
});
|
||||
|
||||
const [_, owner, repo] = baseUrl.pathname.split("/");
|
||||
|
||||
const branch = await getDefaultBranch(owner, repo);
|
||||
console.log("Github repo detected. Crawling", branch, "branch");
|
||||
|
||||
const tree = await octokit.request(
|
||||
"GET /repos/{owner}/{repo}/git/trees/{tree_sha}",
|
||||
{
|
||||
owner,
|
||||
repo,
|
||||
tree_sha: branch,
|
||||
headers: {
|
||||
"X-GitHub-Api-Version": "2022-11-28",
|
||||
},
|
||||
recursive: "true",
|
||||
},
|
||||
);
|
||||
|
||||
const paths = tree.data.tree
|
||||
.filter(
|
||||
(file: any) =>
|
||||
file.type === "blob" && markdownRegex.test(file.path ?? ""),
|
||||
)
|
||||
.map((file: any) => baseUrl.pathname + "/tree/main/" + file.path);
|
||||
|
||||
return paths;
|
||||
}
|
||||
|
||||
async function getLinksFromUrl(url: string, path: string) {
|
||||
const baseUrl = new URL(url);
|
||||
const location = new URL(path, url);
|
||||
let response;
|
||||
|
||||
try {
|
||||
response = await fetch(location.toString());
|
||||
} catch (error: unknown) {
|
||||
if (error instanceof Error && error.message.includes("maximum redirect")) {
|
||||
console.error("Maximum redirect reached for: ", location.toString());
|
||||
return {
|
||||
html: "",
|
||||
links: [],
|
||||
};
|
||||
}
|
||||
console.error(error);
|
||||
return {
|
||||
html: "",
|
||||
links: [],
|
||||
};
|
||||
}
|
||||
|
||||
const html = await response.text();
|
||||
let links: string[] = [];
|
||||
|
||||
if (url.includes("github.com")) {
|
||||
return {
|
||||
html,
|
||||
links,
|
||||
};
|
||||
}
|
||||
|
||||
const $ = cheerio.load(html);
|
||||
|
||||
$("a").each((_, element) => {
|
||||
const href = $(element).attr("href");
|
||||
if (!href) {
|
||||
return;
|
||||
}
|
||||
|
||||
const parsedUrl = new URL(href, url);
|
||||
if (
|
||||
parsedUrl.hostname === baseUrl.hostname
|
||||
// parsedUrl.pathname.startsWith(baseUrl.pathname)
|
||||
) {
|
||||
links.push(parsedUrl.pathname);
|
||||
}
|
||||
});
|
||||
|
||||
links = [...new Set(links)].filter((link) => {
|
||||
return (
|
||||
!link.includes("#") &&
|
||||
!IGNORE_PATHS_ENDING_IN.some((ending) => link.endsWith(ending))
|
||||
);
|
||||
});
|
||||
|
||||
return {
|
||||
html,
|
||||
links,
|
||||
};
|
||||
}
|
||||
|
||||
function splitUrl(url: URL) {
|
||||
const baseUrl = `${url.protocol}//${url.hostname}${
|
||||
url.port ? ":" + url.port : ""
|
||||
}`;
|
||||
const basePath = url.pathname;
|
||||
return {
|
||||
baseUrl,
|
||||
basePath,
|
||||
};
|
||||
}
|
||||
|
||||
export type PageData = {
|
||||
url: string;
|
||||
path: string;
|
||||
html: string;
|
||||
};
|
||||
|
||||
export async function* crawlPage(
|
||||
url: URL,
|
||||
maxDepth: number = 3,
|
||||
): AsyncGenerator<PageData> {
|
||||
console.log(
|
||||
`Starting crawl from: ${url.toString()} - Max Depth: ${maxDepth}`,
|
||||
);
|
||||
|
||||
const { baseUrl, basePath } = splitUrl(url);
|
||||
let paths: { path: string; depth: number }[] = [{ path: basePath, depth: 0 }];
|
||||
|
||||
if (url.hostname === "github.com") {
|
||||
const githubLinks = await crawlGithubRepo(url);
|
||||
const githubLinkObjects = githubLinks.map((link) => ({
|
||||
path: link,
|
||||
depth: 0,
|
||||
}));
|
||||
paths = [...paths, ...githubLinkObjects];
|
||||
}
|
||||
|
||||
let index = 0;
|
||||
while (index < paths.length) {
|
||||
const batch = paths.slice(index, index + 50);
|
||||
|
||||
try {
|
||||
const promises = batch.map(({ path, depth }) =>
|
||||
getLinksFromUrl(baseUrl, path).then((links) => ({
|
||||
links,
|
||||
path,
|
||||
depth,
|
||||
})),
|
||||
); // Adjust for depth tracking
|
||||
|
||||
const results = await Promise.all(promises);
|
||||
for (const {
|
||||
links: { html, links: linksArray },
|
||||
path,
|
||||
depth,
|
||||
} of results) {
|
||||
if (html !== "" && depth <= maxDepth) {
|
||||
// Check depth
|
||||
yield {
|
||||
url: url.toString(),
|
||||
path,
|
||||
html,
|
||||
};
|
||||
}
|
||||
|
||||
// Ensure we only add links if within depth limit
|
||||
if (depth < maxDepth) {
|
||||
for (let link of linksArray) {
|
||||
if (!paths.some((p) => p.path === link)) {
|
||||
paths.push({ path: link, depth: depth + 1 }); // Increment depth for new paths
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
if (e instanceof TypeError) {
|
||||
console.warn("Error while crawling page: ", e); // Likely an invalid url, continue with process
|
||||
} else {
|
||||
console.error("Error while crawling page: ", e);
|
||||
}
|
||||
}
|
||||
|
||||
index += batch.length; // Proceed to next batch
|
||||
}
|
||||
console.log("Crawl completed");
|
||||
}
|
||||
121
core/indexing/docs/crawlSite.test.ts
Normal file
121
core/indexing/docs/crawlSite.test.ts
Normal file
|
|
@ -0,0 +1,121 @@
|
|||
import { crawlSite, PageData } from "./crawlSite";
|
||||
import preIndexedDocs from "./preIndexedDocs";
|
||||
|
||||
// Temporary workaround until we have better caching of Chromium
|
||||
// download between test runs
|
||||
const TIMEOUT = 1_000_000;
|
||||
|
||||
// Skipped until we have a better way to cache Chromium installs
|
||||
// between tests and in CI
|
||||
describe.skip("crawlSite", () => {
|
||||
describe("GitHub repositories", () => {
|
||||
const repoUrl =
|
||||
"https://github.com/Patrick-Erichsen/test-github-repo-for-crawling";
|
||||
|
||||
let crawlResults: PageData[];
|
||||
|
||||
beforeAll(async () => {
|
||||
crawlResults = [];
|
||||
for await (const page of crawlSite(repoUrl)) {
|
||||
crawlResults.push(page);
|
||||
}
|
||||
}, TIMEOUT);
|
||||
|
||||
test("finds expected markdown files", async () => {
|
||||
expect(crawlResults.some((page) => page.path.endsWith("README.md"))).toBe(
|
||||
true,
|
||||
);
|
||||
|
||||
expect(
|
||||
crawlResults.some((page) => page.path.endsWith("docs-depth-1.md")),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
test("html includes the correct content", async () => {
|
||||
const doc = crawlResults.find((page) =>
|
||||
page.path.endsWith("docs-depth-1.md"),
|
||||
);
|
||||
|
||||
expect(doc?.content.includes("Test body")).toBe(true);
|
||||
expect(doc?.content.includes("Test H2 Header")).toBe(true);
|
||||
});
|
||||
|
||||
test("ignores non-markdown files, e.g. `test.js` at the root", async () => {
|
||||
expect(crawlResults.some((page) => page.path.endsWith("test.js"))).toBe(
|
||||
false,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe.only("Non-Github repository sites", () => {
|
||||
it(
|
||||
"succeeds in crawling a list of common sites",
|
||||
async () => {
|
||||
const TEST_SITES = [
|
||||
"https://docs.nestjs.com/",
|
||||
"https://docs.nestjs.com/",
|
||||
"https://go.dev/doc/",
|
||||
"https://clickhouse.com/docs",
|
||||
"https://www.tensorflow.org/api_docs",
|
||||
"https://www.rust-lang.org/learn",
|
||||
"https://docs.anthropic.com/en/docs",
|
||||
];
|
||||
|
||||
const NUM_PAGES_TO_CRAWL = 10;
|
||||
|
||||
for (const site of TEST_SITES) {
|
||||
const crawlResults: PageData[] = [];
|
||||
|
||||
for await (const page of crawlSite(site, NUM_PAGES_TO_CRAWL)) {
|
||||
crawlResults.push(page);
|
||||
}
|
||||
|
||||
// `toBeGreaterThanOrEqual` because Crawlee doesn't guarantee
|
||||
// an exact number of pages to crawl since it runs in parallel
|
||||
expect(crawlResults.length).toBeGreaterThanOrEqual(
|
||||
NUM_PAGES_TO_CRAWL,
|
||||
);
|
||||
}
|
||||
},
|
||||
TIMEOUT,
|
||||
);
|
||||
});
|
||||
|
||||
describe("Pre-indexed Docs", () => {
|
||||
const results: { [url: string]: boolean } = {};
|
||||
let totalTests = 0;
|
||||
let passedTests = 0;
|
||||
|
||||
Object.keys(preIndexedDocs).forEach((url) => {
|
||||
test(
|
||||
`Crawl test for ${url}`,
|
||||
async () => {
|
||||
totalTests++;
|
||||
let pageFound = false;
|
||||
|
||||
try {
|
||||
for await (const page of crawlSite(url, 1)) {
|
||||
if (page.url === url) {
|
||||
pageFound = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(`Error crawling ${url}:`, error);
|
||||
}
|
||||
|
||||
results[url] = pageFound;
|
||||
if (pageFound) {
|
||||
passedTests++;
|
||||
console.log(`✅ ${url}`);
|
||||
} else {
|
||||
console.log(`❌ ${url}`);
|
||||
}
|
||||
|
||||
expect(pageFound).toBe(true);
|
||||
},
|
||||
TIMEOUT,
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
163
core/indexing/docs/crawlSite.ts
Normal file
163
core/indexing/docs/crawlSite.ts
Normal file
|
|
@ -0,0 +1,163 @@
|
|||
import { Octokit } from "@octokit/rest";
|
||||
import { URL } from "node:url";
|
||||
import { PlaywrightCrawler, Configuration, LogLevel } from "crawlee";
|
||||
import { EventEmitter } from "events";
|
||||
import { installChromium, isChromiumInstalled } from "./installChromium";
|
||||
import { getChromiumExecutablePath } from "../../util/paths";
|
||||
import * as os from "os";
|
||||
|
||||
export type PageData = {
|
||||
url: string;
|
||||
path: string;
|
||||
content: string;
|
||||
};
|
||||
|
||||
const IS_DONE_CRAWLING = "IS_DONE_CRAWLING";
|
||||
const MAX_REQUESTS_PER_CRAWL = 1000;
|
||||
const markdownRegex = new RegExp(/\.(md|mdx)$/);
|
||||
const octokit = new Octokit({
|
||||
auth: undefined,
|
||||
});
|
||||
|
||||
class CrawlEmitter extends EventEmitter {
|
||||
emit(event: "data", data: PageData): boolean;
|
||||
emit(event: string | symbol, ...args: any[]): boolean {
|
||||
return super.emit(event, ...args);
|
||||
}
|
||||
}
|
||||
|
||||
async function getGithubRepoDefaultBranch(
|
||||
owner: string,
|
||||
repo: string,
|
||||
): Promise<string> {
|
||||
const repoInfo = await octokit.repos.get({
|
||||
owner,
|
||||
repo,
|
||||
});
|
||||
|
||||
return repoInfo.data.default_branch;
|
||||
}
|
||||
|
||||
async function getGitHubRepoPaths(owner: string, repo: string, branch: string) {
|
||||
const tree = await octokit.request(
|
||||
"GET /repos/{owner}/{repo}/git/trees/{tree_sha}",
|
||||
{
|
||||
owner,
|
||||
repo,
|
||||
tree_sha: branch,
|
||||
headers: {
|
||||
"X-GitHub-Api-Version": "2022-11-28",
|
||||
},
|
||||
recursive: "true",
|
||||
},
|
||||
);
|
||||
|
||||
const paths = tree.data.tree
|
||||
.filter(
|
||||
(file: any) =>
|
||||
file.type === "blob" && markdownRegex.test(file.path ?? ""),
|
||||
)
|
||||
.map((file: any) => file.path);
|
||||
|
||||
return paths;
|
||||
}
|
||||
|
||||
async function getGithubRepoFileContent(
|
||||
path: string,
|
||||
owner: string,
|
||||
repo: string,
|
||||
) {
|
||||
try {
|
||||
const response = await octokit.repos.getContent({
|
||||
owner,
|
||||
repo,
|
||||
path,
|
||||
headers: {
|
||||
Accept: "application/vnd.github.raw+json",
|
||||
},
|
||||
});
|
||||
|
||||
return response.data as unknown as string;
|
||||
} catch (error) {
|
||||
console.debug("Error fetching file contents:", error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function* crawlGithubRepo(url: URL) {
|
||||
const urlStr = url.toString();
|
||||
const [_, owner, repo] = url.pathname.split("/");
|
||||
const branch = await getGithubRepoDefaultBranch(owner, repo);
|
||||
const paths = await getGitHubRepoPaths(owner, repo, branch);
|
||||
|
||||
for await (const path of paths) {
|
||||
const content = await getGithubRepoFileContent(path, owner, repo);
|
||||
|
||||
yield {
|
||||
path,
|
||||
url: urlStr,
|
||||
content: content ?? "",
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export async function* crawlSite(
|
||||
url: string,
|
||||
maxRequestsPerCrawl: number = MAX_REQUESTS_PER_CRAWL,
|
||||
): AsyncGenerator<PageData> {
|
||||
if (url.includes("github.com")) {
|
||||
for await (const pageData of crawlGithubRepo(new URL(url))) {
|
||||
yield pageData;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (!isChromiumInstalled()) {
|
||||
await installChromium();
|
||||
}
|
||||
|
||||
const emitter = new CrawlEmitter();
|
||||
|
||||
const crawler = new PlaywrightCrawler(
|
||||
{
|
||||
async requestHandler({ request, page, enqueueLinks }) {
|
||||
const { pathname: path } = new URL(request.loadedUrl);
|
||||
const content = await page.content();
|
||||
|
||||
emitter.emit("data", { url, content, path });
|
||||
|
||||
await enqueueLinks();
|
||||
},
|
||||
maxRequestsPerCrawl,
|
||||
launchContext: {
|
||||
launchOptions: {
|
||||
executablePath: getChromiumExecutablePath(os.platform())!,
|
||||
},
|
||||
},
|
||||
},
|
||||
new Configuration({
|
||||
persistStorage: false,
|
||||
logLevel: process.env.NODE_ENV === "test" ? LogLevel.DEBUG : LogLevel.OFF,
|
||||
}),
|
||||
);
|
||||
|
||||
const crawlerPromise = new Promise<typeof IS_DONE_CRAWLING>((resolve) => {
|
||||
crawler.run([url]).then(() => {
|
||||
resolve(IS_DONE_CRAWLING);
|
||||
});
|
||||
});
|
||||
|
||||
while (true) {
|
||||
const dataPromise = new Promise<PageData>((resolve) => {
|
||||
emitter.on("data", resolve);
|
||||
});
|
||||
|
||||
const result = await Promise.race([dataPromise, crawlerPromise]);
|
||||
|
||||
if (result === IS_DONE_CRAWLING) {
|
||||
break;
|
||||
}
|
||||
|
||||
yield result as PageData;
|
||||
}
|
||||
}
|
||||
92
core/indexing/docs/installChromium.ts
Normal file
92
core/indexing/docs/installChromium.ts
Normal file
|
|
@ -0,0 +1,92 @@
|
|||
import * as os from "os";
|
||||
import * as fs from "fs";
|
||||
import * as path from "path";
|
||||
import {
|
||||
getChromiumExecutablePath,
|
||||
getContinueUtilsChromiumPath,
|
||||
} from "../../util/paths";
|
||||
import { finished } from "stream/promises";
|
||||
import extract from "extract-zip";
|
||||
|
||||
const PACKAGE_ZIP_FILENAME = "package.zip";
|
||||
|
||||
/**
|
||||
* These Chromium versions are what is installed by default from
|
||||
* "playwright": "^1.46.1"
|
||||
*
|
||||
* Note that if we bump our version of playwright, we will need to install new
|
||||
* Chromium versions as well.
|
||||
*
|
||||
* See Playwright source code for download paths: https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/server/registry/index.ts
|
||||
*/
|
||||
const DOWNLOAD_URLS: { [key: string]: string } = {
|
||||
linux:
|
||||
"https://playwright.azureedge.net/builds/chromium/1129/chromium-linux.zip",
|
||||
darwin:
|
||||
"https://playwright.azureedge.net/builds/chromium/1129/chromium-mac.zip",
|
||||
win32:
|
||||
"https://playwright.azureedge.net/builds/chromium/1129/chromium-win64.zip",
|
||||
};
|
||||
|
||||
async function downloadPackage(): Promise<string> {
|
||||
console.log("Downloading Chromium zip");
|
||||
|
||||
const platform = os.platform();
|
||||
const downloadUrl = DOWNLOAD_URLS[platform];
|
||||
|
||||
if (!downloadUrl) {
|
||||
throw new Error(`Unsupported platform: ${platform}`);
|
||||
}
|
||||
|
||||
const zipPath = path.join(
|
||||
getContinueUtilsChromiumPath(),
|
||||
PACKAGE_ZIP_FILENAME,
|
||||
);
|
||||
const response = await fetch(downloadUrl);
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(
|
||||
`Failed to download Chromium. Status code: ${response.status}`,
|
||||
);
|
||||
}
|
||||
|
||||
if (!response.body) {
|
||||
throw new Error("Response body is null");
|
||||
}
|
||||
|
||||
const file = fs.createWriteStream(zipPath);
|
||||
|
||||
// https://stackoverflow.com/a/74722818
|
||||
// @ts-ignore
|
||||
await finished(response.body.pipe(file));
|
||||
|
||||
return zipPath;
|
||||
}
|
||||
|
||||
async function extractZip(zipPath: string): Promise<void> {
|
||||
try {
|
||||
console.debug(
|
||||
`Extracting Chromium zip to ${getContinueUtilsChromiumPath()}`,
|
||||
);
|
||||
await extract(zipPath, { dir: getContinueUtilsChromiumPath() });
|
||||
await fs.promises.unlink(zipPath);
|
||||
} catch (err) {
|
||||
console.debug(`Error unzipping Chromium: ${err}`);
|
||||
}
|
||||
}
|
||||
|
||||
export function isChromiumInstalled(): boolean {
|
||||
const chromiumBinaryPath = getChromiumExecutablePath(os.platform());
|
||||
return !!chromiumBinaryPath && fs.existsSync(chromiumBinaryPath);
|
||||
}
|
||||
|
||||
export async function installChromium() {
|
||||
try {
|
||||
console.debug("Installing Chromium");
|
||||
const zipPath = await downloadPackage();
|
||||
await extractZip(zipPath);
|
||||
} catch (error) {
|
||||
console.debug("Chromium installation failed:", error);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
import { SiteIndexingConfig } from "../../index.js";
|
||||
import { SiteIndexingConfig } from "../../";
|
||||
|
||||
const preIndexedDocs: Record<
|
||||
SiteIndexingConfig["startUrl"],
|
||||
|
|
|
|||
|
|
@ -16,16 +16,16 @@ globalThis.Response = Response;
|
|||
globalThis.TextEncoder = TextEncoder;
|
||||
globalThis.TextDecoder = TextDecoder;
|
||||
|
||||
globalThis.beforeAll(() => {
|
||||
// We can ignore TS warnings here since we set this explicitly in `./jest.global-setup.ts`
|
||||
if (fs.existsSync(process.env.CONTINUE_GLOBAL_DIR!)) {
|
||||
fs.rmSync(process.env.CONTINUE_GLOBAL_DIR!, { recursive: true });
|
||||
}
|
||||
});
|
||||
// globalThis.beforeAll(() => {
|
||||
// // We can ignore TS warnings here since we set this explicitly in `./jest.global-setup.ts`
|
||||
// if (fs.existsSync(process.env.CONTINUE_GLOBAL_DIR!)) {
|
||||
// fs.rmSync(process.env.CONTINUE_GLOBAL_DIR!, { recursive: true });
|
||||
// }
|
||||
// });
|
||||
|
||||
globalThis.afterAll(() => {
|
||||
// We can ignore TS warnings here since we set this explicitly in `./jest.global-setup.ts`
|
||||
if (fs.existsSync(process.env.CONTINUE_GLOBAL_DIR!)) {
|
||||
fs.rmSync(process.env.CONTINUE_GLOBAL_DIR!, { recursive: true });
|
||||
}
|
||||
});
|
||||
// globalThis.afterAll(() => {
|
||||
// // We can ignore TS warnings here since we set this explicitly in `./jest.global-setup.ts`
|
||||
// if (fs.existsSync(process.env.CONTINUE_GLOBAL_DIR!)) {
|
||||
// fs.rmSync(process.env.CONTINUE_GLOBAL_DIR!, { recursive: true });
|
||||
// }
|
||||
// });
|
||||
|
|
|
|||
2078
core/package-lock.json
generated
2078
core/package-lock.json
generated
File diff suppressed because it is too large
Load diff
|
|
@ -3,7 +3,7 @@
|
|||
"version": "1.0.13",
|
||||
"description": "The Continue Core contains functionality that can be shared across web, VS Code, or Node.js",
|
||||
"scripts": {
|
||||
"test": "cross-env NODE_OPTIONS=--experimental-vm-modules jest --runInBand --silent",
|
||||
"test": "cross-env NODE_OPTIONS=--experimental-vm-modules jest --runInBand",
|
||||
"build:npm": "tsc -p ./tsconfig.npm.json",
|
||||
"lint": "eslint . --ext ts",
|
||||
"lint:fix": "eslint . --ext ts --fix"
|
||||
|
|
@ -51,11 +51,12 @@
|
|||
"adf-to-md": "^1.1.0",
|
||||
"async-mutex": "^0.5.0",
|
||||
"axios": "^1.6.7",
|
||||
"cheerio": "^1.0.0-rc.12",
|
||||
"commander": "^12.0.0",
|
||||
"comment-json": "^4.2.3",
|
||||
"crawlee": "^3.11.1",
|
||||
"dbinfoz": "^0.1.4",
|
||||
"dotenv": "^16.4.5",
|
||||
"extract-zip": "^2.0.1",
|
||||
"fastest-levenshtein": "^1.0.16",
|
||||
"follow-redirects": "^1.15.5",
|
||||
"handlebars": "^4.7.8",
|
||||
|
|
@ -75,6 +76,7 @@
|
|||
"openai": "^4.20.1",
|
||||
"p-limit": "^6.1.0",
|
||||
"pg": "^8.11.3",
|
||||
"playwright": "^1.46.1",
|
||||
"posthog-node": "^3.6.3",
|
||||
"quick-lru": "^7.0.0",
|
||||
"replicate": "^0.26.0",
|
||||
|
|
|
|||
|
|
@ -8,9 +8,52 @@ import Types from "../config/types.js";
|
|||
import { IdeType, SerializedContinueConfig } from "../index.js";
|
||||
|
||||
dotenv.config();
|
||||
|
||||
const CONTINUE_GLOBAL_DIR =
|
||||
process.env.CONTINUE_GLOBAL_DIR ?? path.join(os.homedir(), ".continue");
|
||||
|
||||
// https://github.com/microsoft/playwright/blob/release-1.46/packages/playwright-core/src/server/registry/index.ts#L54-L58
|
||||
const CHROMIUM_EXECUTABLE_PATHS = {
|
||||
linux: ["chrome-linux", "chrome"],
|
||||
darwin: ["chrome-mac", "Chromium.app", "Contents", "MacOS", "Chromium"],
|
||||
win32: ["chrome-win", "chrome.exe"],
|
||||
};
|
||||
|
||||
/**
|
||||
* Note that unlike most of the other methods in this file, this method
|
||||
* does not create the path if it doesn't exist. The intended behavior
|
||||
* is just to get the file path.
|
||||
*/
|
||||
export function getChromiumExecutablePath(
|
||||
platform: NodeJS.Platform,
|
||||
): string | null {
|
||||
if (platform !== "linux" && platform !== "darwin" && platform !== "win32") {
|
||||
console.error(`Unsupported platform for Chromium install: ${platform}`);
|
||||
return null;
|
||||
}
|
||||
|
||||
const chromiumUtilPath = getContinueUtilsChromiumPath();
|
||||
const executablePath = CHROMIUM_EXECUTABLE_PATHS[platform];
|
||||
|
||||
return path.join(chromiumUtilPath, ...executablePath);
|
||||
}
|
||||
|
||||
export function getContinueUtilsChromiumPath(): string {
|
||||
const chromiumPath = path.join(getContinueUtilsPath(), "chromium");
|
||||
if (!fs.existsSync(chromiumPath)) {
|
||||
fs.mkdirSync(chromiumPath);
|
||||
}
|
||||
return chromiumPath;
|
||||
}
|
||||
|
||||
export function getContinueUtilsPath(): string {
|
||||
const utilsPath = path.join(getContinueGlobalPath(), ".utils");
|
||||
if (!fs.existsSync(utilsPath)) {
|
||||
fs.mkdirSync(utilsPath);
|
||||
}
|
||||
return utilsPath;
|
||||
}
|
||||
|
||||
export function getContinueGlobalPath(): string {
|
||||
// This is ~/.continue on mac/linux
|
||||
const continuePath = CONTINUE_GLOBAL_DIR;
|
||||
|
|
|
|||
4
extensions/vscode/package-lock.json
generated
4
extensions/vscode/package-lock.json
generated
|
|
@ -108,11 +108,12 @@
|
|||
"adf-to-md": "^1.1.0",
|
||||
"async-mutex": "^0.5.0",
|
||||
"axios": "^1.6.7",
|
||||
"cheerio": "^1.0.0-rc.12",
|
||||
"commander": "^12.0.0",
|
||||
"comment-json": "^4.2.3",
|
||||
"crawlee": "^3.11.1",
|
||||
"dbinfoz": "^0.1.4",
|
||||
"dotenv": "^16.4.5",
|
||||
"extract-zip": "^2.0.1",
|
||||
"fastest-levenshtein": "^1.0.16",
|
||||
"follow-redirects": "^1.15.5",
|
||||
"handlebars": "^4.7.8",
|
||||
|
|
@ -132,6 +133,7 @@
|
|||
"openai": "^4.20.1",
|
||||
"p-limit": "^6.1.0",
|
||||
"pg": "^8.11.3",
|
||||
"playwright": "^1.46.1",
|
||||
"posthog-node": "^3.6.3",
|
||||
"quick-lru": "^7.0.0",
|
||||
"replicate": "^0.26.0",
|
||||
|
|
|
|||
66
gui/package-lock.json
generated
66
gui/package-lock.json
generated
|
|
@ -101,11 +101,12 @@
|
|||
"adf-to-md": "^1.1.0",
|
||||
"async-mutex": "^0.5.0",
|
||||
"axios": "^1.6.7",
|
||||
"cheerio": "^1.0.0-rc.12",
|
||||
"commander": "^12.0.0",
|
||||
"comment-json": "^4.2.3",
|
||||
"crawlee": "^3.11.1",
|
||||
"dbinfoz": "^0.1.4",
|
||||
"dotenv": "^16.4.5",
|
||||
"extract-zip": "^2.0.1",
|
||||
"fastest-levenshtein": "^1.0.16",
|
||||
"follow-redirects": "^1.15.5",
|
||||
"handlebars": "^4.7.8",
|
||||
|
|
@ -125,6 +126,7 @@
|
|||
"openai": "^4.20.1",
|
||||
"p-limit": "^6.1.0",
|
||||
"pg": "^8.11.3",
|
||||
"playwright": "^1.46.1",
|
||||
"posthog-node": "^3.6.3",
|
||||
"quick-lru": "^7.0.0",
|
||||
"replicate": "^0.26.0",
|
||||
|
|
@ -6312,40 +6314,6 @@
|
|||
"node": ">=10"
|
||||
}
|
||||
},
|
||||
"../core/node_modules/cheerio": {
|
||||
"version": "1.0.0-rc.12",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"cheerio-select": "^2.1.0",
|
||||
"dom-serializer": "^2.0.0",
|
||||
"domhandler": "^5.0.3",
|
||||
"domutils": "^3.0.1",
|
||||
"htmlparser2": "^8.0.1",
|
||||
"parse5": "^7.0.0",
|
||||
"parse5-htmlparser2-tree-adapter": "^7.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 6"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/cheeriojs/cheerio?sponsor=1"
|
||||
}
|
||||
},
|
||||
"../core/node_modules/cheerio-select": {
|
||||
"version": "2.1.0",
|
||||
"license": "BSD-2-Clause",
|
||||
"dependencies": {
|
||||
"boolbase": "^1.0.0",
|
||||
"css-select": "^5.1.0",
|
||||
"css-what": "^6.1.0",
|
||||
"domelementtype": "^2.3.0",
|
||||
"domhandler": "^5.0.3",
|
||||
"domutils": "^3.0.1"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/fb55"
|
||||
}
|
||||
},
|
||||
"../core/node_modules/chownr": {
|
||||
"version": "2.0.0",
|
||||
"license": "ISC",
|
||||
|
|
@ -8312,23 +8280,6 @@
|
|||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"../core/node_modules/htmlparser2": {
|
||||
"version": "8.0.2",
|
||||
"funding": [
|
||||
"https://github.com/fb55/htmlparser2?sponsor=1",
|
||||
{
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/fb55"
|
||||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"domelementtype": "^2.3.0",
|
||||
"domhandler": "^5.0.3",
|
||||
"domutils": "^3.0.1",
|
||||
"entities": "^4.4.0"
|
||||
}
|
||||
},
|
||||
"../core/node_modules/http-cache-semantics": {
|
||||
"version": "4.1.1",
|
||||
"license": "BSD-2-Clause",
|
||||
|
|
@ -10574,17 +10525,6 @@
|
|||
"url": "https://github.com/inikulin/parse5?sponsor=1"
|
||||
}
|
||||
},
|
||||
"../core/node_modules/parse5-htmlparser2-tree-adapter": {
|
||||
"version": "7.0.0",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"domhandler": "^5.0.2",
|
||||
"parse5": "^7.0.0"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/inikulin/parse5?sponsor=1"
|
||||
}
|
||||
},
|
||||
"../core/node_modules/path-exists": {
|
||||
"version": "4.0.0",
|
||||
"license": "MIT",
|
||||
|
|
|
|||
|
|
@ -7,8 +7,6 @@ import { Button, HelperText, Input, lightGray } from "..";
|
|||
import { IdeMessengerContext } from "../../context/IdeMessenger";
|
||||
import { setShowDialog } from "../../redux/slices/uiStateSlice";
|
||||
|
||||
const DEFAULT_MAX_DEPTH = 3;
|
||||
|
||||
function AddDocsDialog() {
|
||||
const posthog = usePostHog();
|
||||
const dispatch = useDispatch();
|
||||
|
|
@ -17,9 +15,7 @@ function AddDocsDialog() {
|
|||
|
||||
const [title, setTitle] = useState("");
|
||||
const [startUrl, setStartUrl] = useState("");
|
||||
const [rootUrl, setRootUrl] = useState("");
|
||||
const [faviconUrl, setFaviconUrl] = useState("");
|
||||
const [maxDepth, setMaxDepth] = useState<number | string>("");
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
|
||||
const ideMessenger = useContext(IdeMessengerContext);
|
||||
|
|
@ -39,18 +35,14 @@ function AddDocsDialog() {
|
|||
|
||||
const siteIndexingConfig: SiteIndexingConfig = {
|
||||
startUrl,
|
||||
rootUrl,
|
||||
title,
|
||||
maxDepth: typeof maxDepth === "string" ? DEFAULT_MAX_DEPTH : maxDepth,
|
||||
faviconUrl: new URL("/favicon.ico", startUrl).toString(),
|
||||
faviconUrl,
|
||||
};
|
||||
|
||||
ideMessenger.post("context/addDocs", siteIndexingConfig);
|
||||
|
||||
setTitle("");
|
||||
setStartUrl("");
|
||||
setRootUrl("");
|
||||
setMaxDepth("");
|
||||
setFaviconUrl("");
|
||||
|
||||
dispatch(setShowDialog(false));
|
||||
|
|
@ -126,22 +118,6 @@ function AddDocsDialog() {
|
|||
|
||||
{isOpen && (
|
||||
<div className="pt-2">
|
||||
<label>
|
||||
Root URL [Optional]
|
||||
<Input
|
||||
type="url"
|
||||
placeholder="Root URL"
|
||||
value={rootUrl}
|
||||
onChange={(e) => {
|
||||
setRootUrl(e.target.value);
|
||||
}}
|
||||
/>
|
||||
<HelperText>
|
||||
Limits the crawler to pages within the same domain and path as
|
||||
the Root URL
|
||||
</HelperText>
|
||||
</label>
|
||||
|
||||
<label>
|
||||
Favicon URL [Optional]
|
||||
<Input
|
||||
|
|
@ -157,29 +133,6 @@ function AddDocsDialog() {
|
|||
`/favicon.ico` path from the Start URL
|
||||
</HelperText>
|
||||
</label>
|
||||
|
||||
<label>
|
||||
Max Depth [Optional]
|
||||
<Input
|
||||
type="text"
|
||||
inputMode="numeric"
|
||||
placeholder={`Default: ${DEFAULT_MAX_DEPTH}`}
|
||||
title="The maximum search tree depth - where your input url is the root node"
|
||||
value={maxDepth}
|
||||
onChange={(e) => {
|
||||
const value = e.target.value;
|
||||
if (value == "") {
|
||||
setMaxDepth("");
|
||||
} else if (!isNaN(+value) && Number(value) > 0) {
|
||||
setMaxDepth(Number(value));
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<HelperText>
|
||||
Limits the maximum search tree depth of the crawler - 3 by
|
||||
default
|
||||
</HelperText>
|
||||
</label>
|
||||
</div>
|
||||
)}
|
||||
|
||||
|
|
|
|||
|
|
@ -124,6 +124,7 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview(
|
|||
// https://github.com/highlightjs/highlight.js/blob/main/SUPPORTED_LANGUAGES.md
|
||||
{
|
||||
// languages: {},
|
||||
aliases: { javascript: "terraform" }, // TODO: test
|
||||
} as Options,
|
||||
],
|
||||
rehypeReactOptions: {
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue