280 lines
7.0 KiB
TypeScript
Raw Normal View History

2024-08-16 17:57:11 -03:00
import { Response } from "express";
import { v4 as uuidv4 } from "uuid";
2024-12-11 19:46:11 -03:00
import {
MapDocument,
mapRequestSchema,
RequestWithAuth,
2024-12-11 19:51:08 -03:00
scrapeOptions,
2024-12-11 19:46:11 -03:00
} from "./types";
2024-08-16 17:57:11 -03:00
import { crawlToCrawler, StoredCrawl } from "../../lib/crawl-redis";
2024-08-16 19:33:57 -04:00
import { MapResponse, MapRequest } from "./types";
2024-08-16 17:57:11 -03:00
import { configDotenv } from "dotenv";
2024-08-16 19:33:57 -04:00
import {
checkAndUpdateURLForMap,
isSameDomain,
isSameSubdomain,
2024-12-11 19:51:08 -03:00
removeDuplicateUrls,
2024-08-16 19:33:57 -04:00
} from "../../lib/validateUrl";
import { fireEngineMap } from "../../search/fireEngine";
2024-10-28 16:02:07 -03:00
import { billTeam } from "../../services/billing/credit_billing";
import { logJob } from "../../services/logging/log_job";
2024-08-28 15:40:30 -03:00
import { performCosineSimilarity } from "../../lib/map-cosine";
`WebScraper` refactor into `scrapeURL` (#714) * feat: use strictNullChecking * feat: switch logger to Winston * feat(scrapeURL): first batch * fix(scrapeURL): error swallow * fix(scrapeURL): add timeout to EngineResultsTracker * fix(scrapeURL): report unexpected error to sentry * chore: remove unused modules * feat(transfomers/coerce): warn when a format's response is missing * feat(scrapeURL): feature flag priorities, engine quality sorting, PDF and DOCX support * (add note) * feat(scrapeURL): wip readme * feat(scrapeURL): LLM extract * feat(scrapeURL): better warnings * fix(scrapeURL/engines/fire-engine;playwright): fix screenshot * feat(scrapeURL): add forceEngine internal option * feat(scrapeURL/engines): scrapingbee * feat(scrapeURL/transformars): uploadScreenshot * feat(scrapeURL): more intense tests * bunch of stuff * get rid of WebScraper (mostly) * adapt batch scrape * add staging deploy workflow * fix yaml * fix logger issues * fix v1 test schema * feat(scrapeURL/fire-engine/chrome-cdp): remove wait inserts on actions * scrapeURL: v0 backwards compat * logger fixes * feat(scrapeurl): v0 returnOnlyUrls support * fix(scrapeURL/v0): URL leniency * fix(batch-scrape): ts non-nullable * fix(scrapeURL/fire-engine/chromecdp): fix wait action * fix(logger): remove error debug key * feat(requests.http): use dotenv expression * fix(scrapeURL/extractMetadata): extract custom metadata * fix crawl option conversion * feat(scrapeURL): Add retry logic to robustFetch * fix(scrapeURL): crawl stuff * fix(scrapeURL): LLM extract * fix(scrapeURL/v0): search fix * fix(tests/v0): grant larger response size to v0 crawl status * feat(scrapeURL): basic fetch engine * feat(scrapeURL): playwright engine * feat(scrapeURL): add url-specific parameters * Update readme and examples * added e2e tests for most parameters. Still a few actions, location and iframes to be done. * fixed type * Nick: * Update scrape.ts * Update index.ts * added actions and base64 check * Nick: skipTls feature flag? * 403 * todo * todo * fixes * yeet headers from url specific params * add warning when final engine has feature deficit * expose engine results tracker for ScrapeEvents implementation * ingest scrape events * fixed some tests * comment * Update index.test.ts * fixed rawHtml * Update index.test.ts * update comments * move geolocation to global f-e option, fix removeBase64Images * Nick: * trim url-specific params * Update index.ts --------- Co-authored-by: Eric Ciarla <ericciarla@yahoo.com> Co-authored-by: rafaelmmiller <8574157+rafaelmmiller@users.noreply.github.com> Co-authored-by: Nicolas <nicolascamara29@gmail.com>
2024-11-07 20:57:33 +01:00
import { logger } from "../../lib/logger";
2024-09-16 12:03:14 -04:00
import Redis from "ioredis";
2024-08-16 17:57:11 -03:00
configDotenv();
`WebScraper` refactor into `scrapeURL` (#714) * feat: use strictNullChecking * feat: switch logger to Winston * feat(scrapeURL): first batch * fix(scrapeURL): error swallow * fix(scrapeURL): add timeout to EngineResultsTracker * fix(scrapeURL): report unexpected error to sentry * chore: remove unused modules * feat(transfomers/coerce): warn when a format's response is missing * feat(scrapeURL): feature flag priorities, engine quality sorting, PDF and DOCX support * (add note) * feat(scrapeURL): wip readme * feat(scrapeURL): LLM extract * feat(scrapeURL): better warnings * fix(scrapeURL/engines/fire-engine;playwright): fix screenshot * feat(scrapeURL): add forceEngine internal option * feat(scrapeURL/engines): scrapingbee * feat(scrapeURL/transformars): uploadScreenshot * feat(scrapeURL): more intense tests * bunch of stuff * get rid of WebScraper (mostly) * adapt batch scrape * add staging deploy workflow * fix yaml * fix logger issues * fix v1 test schema * feat(scrapeURL/fire-engine/chrome-cdp): remove wait inserts on actions * scrapeURL: v0 backwards compat * logger fixes * feat(scrapeurl): v0 returnOnlyUrls support * fix(scrapeURL/v0): URL leniency * fix(batch-scrape): ts non-nullable * fix(scrapeURL/fire-engine/chromecdp): fix wait action * fix(logger): remove error debug key * feat(requests.http): use dotenv expression * fix(scrapeURL/extractMetadata): extract custom metadata * fix crawl option conversion * feat(scrapeURL): Add retry logic to robustFetch * fix(scrapeURL): crawl stuff * fix(scrapeURL): LLM extract * fix(scrapeURL/v0): search fix * fix(tests/v0): grant larger response size to v0 crawl status * feat(scrapeURL): basic fetch engine * feat(scrapeURL): playwright engine * feat(scrapeURL): add url-specific parameters * Update readme and examples * added e2e tests for most parameters. Still a few actions, location and iframes to be done. * fixed type * Nick: * Update scrape.ts * Update index.ts * added actions and base64 check * Nick: skipTls feature flag? * 403 * todo * todo * fixes * yeet headers from url specific params * add warning when final engine has feature deficit * expose engine results tracker for ScrapeEvents implementation * ingest scrape events * fixed some tests * comment * Update index.test.ts * fixed rawHtml * Update index.test.ts * update comments * move geolocation to global f-e option, fix removeBase64Images * Nick: * trim url-specific params * Update index.ts --------- Co-authored-by: Eric Ciarla <ericciarla@yahoo.com> Co-authored-by: rafaelmmiller <8574157+rafaelmmiller@users.noreply.github.com> Co-authored-by: Nicolas <nicolascamara29@gmail.com>
2024-11-07 20:57:33 +01:00
const redis = new Redis(process.env.REDIS_URL!);
2024-09-16 12:03:14 -04:00
// Max Links that /map can return
const MAX_MAP_LIMIT = 5000;
// Max Links that "Smart /map" can return
2024-12-17 15:19:52 -03:00
const MAX_FIRE_ENGINE_RESULTS = 500;
2024-08-06 15:24:45 -03:00
interface MapResult {
success: boolean;
links: string[];
scrape_id?: string;
job_id: string;
time_taken: number;
mapResults: MapDocument[];
}
2024-10-28 16:02:07 -03:00
export async function getMapResults({
url,
search,
limit = MAX_MAP_LIMIT,
ignoreSitemap = false,
2024-11-12 12:10:18 -05:00
includeSubdomains = true,
2024-10-28 16:02:07 -03:00
crawlerOptions = {},
teamId,
plan,
origin,
includeMetadata = false,
2024-12-11 19:51:08 -03:00
allowExternalLinks,
2024-11-12 12:10:18 -05:00
}: {
url: string;
search?: string;
limit?: number;
ignoreSitemap?: boolean;
includeSubdomains?: boolean;
crawlerOptions?: any;
teamId: string;
plan?: string;
origin?: string;
includeMetadata?: boolean;
allowExternalLinks?: boolean;
}): Promise<MapResult> {
2024-08-16 17:57:11 -03:00
const id = uuidv4();
2024-11-12 12:10:18 -05:00
let links: string[] = [url];
let mapResults: MapDocument[] = [];
2024-08-16 17:57:11 -03:00
const sc: StoredCrawl = {
2024-10-28 16:02:07 -03:00
originUrl: url,
`WebScraper` refactor into `scrapeURL` (#714) * feat: use strictNullChecking * feat: switch logger to Winston * feat(scrapeURL): first batch * fix(scrapeURL): error swallow * fix(scrapeURL): add timeout to EngineResultsTracker * fix(scrapeURL): report unexpected error to sentry * chore: remove unused modules * feat(transfomers/coerce): warn when a format's response is missing * feat(scrapeURL): feature flag priorities, engine quality sorting, PDF and DOCX support * (add note) * feat(scrapeURL): wip readme * feat(scrapeURL): LLM extract * feat(scrapeURL): better warnings * fix(scrapeURL/engines/fire-engine;playwright): fix screenshot * feat(scrapeURL): add forceEngine internal option * feat(scrapeURL/engines): scrapingbee * feat(scrapeURL/transformars): uploadScreenshot * feat(scrapeURL): more intense tests * bunch of stuff * get rid of WebScraper (mostly) * adapt batch scrape * add staging deploy workflow * fix yaml * fix logger issues * fix v1 test schema * feat(scrapeURL/fire-engine/chrome-cdp): remove wait inserts on actions * scrapeURL: v0 backwards compat * logger fixes * feat(scrapeurl): v0 returnOnlyUrls support * fix(scrapeURL/v0): URL leniency * fix(batch-scrape): ts non-nullable * fix(scrapeURL/fire-engine/chromecdp): fix wait action * fix(logger): remove error debug key * feat(requests.http): use dotenv expression * fix(scrapeURL/extractMetadata): extract custom metadata * fix crawl option conversion * feat(scrapeURL): Add retry logic to robustFetch * fix(scrapeURL): crawl stuff * fix(scrapeURL): LLM extract * fix(scrapeURL/v0): search fix * fix(tests/v0): grant larger response size to v0 crawl status * feat(scrapeURL): basic fetch engine * feat(scrapeURL): playwright engine * feat(scrapeURL): add url-specific parameters * Update readme and examples * added e2e tests for most parameters. Still a few actions, location and iframes to be done. * fixed type * Nick: * Update scrape.ts * Update index.ts * added actions and base64 check * Nick: skipTls feature flag? * 403 * todo * todo * fixes * yeet headers from url specific params * add warning when final engine has feature deficit * expose engine results tracker for ScrapeEvents implementation * ingest scrape events * fixed some tests * comment * Update index.test.ts * fixed rawHtml * Update index.test.ts * update comments * move geolocation to global f-e option, fix removeBase64Images * Nick: * trim url-specific params * Update index.ts --------- Co-authored-by: Eric Ciarla <ericciarla@yahoo.com> Co-authored-by: rafaelmmiller <8574157+rafaelmmiller@users.noreply.github.com> Co-authored-by: Nicolas <nicolascamara29@gmail.com>
2024-11-07 20:57:33 +01:00
crawlerOptions: {
2024-11-12 12:10:18 -05:00
...crawlerOptions,
limit: crawlerOptions.sitemapOnly ? 10000000 : limit,
2024-12-11 19:51:08 -03:00
scrapeOptions: undefined,
`WebScraper` refactor into `scrapeURL` (#714) * feat: use strictNullChecking * feat: switch logger to Winston * feat(scrapeURL): first batch * fix(scrapeURL): error swallow * fix(scrapeURL): add timeout to EngineResultsTracker * fix(scrapeURL): report unexpected error to sentry * chore: remove unused modules * feat(transfomers/coerce): warn when a format's response is missing * feat(scrapeURL): feature flag priorities, engine quality sorting, PDF and DOCX support * (add note) * feat(scrapeURL): wip readme * feat(scrapeURL): LLM extract * feat(scrapeURL): better warnings * fix(scrapeURL/engines/fire-engine;playwright): fix screenshot * feat(scrapeURL): add forceEngine internal option * feat(scrapeURL/engines): scrapingbee * feat(scrapeURL/transformars): uploadScreenshot * feat(scrapeURL): more intense tests * bunch of stuff * get rid of WebScraper (mostly) * adapt batch scrape * add staging deploy workflow * fix yaml * fix logger issues * fix v1 test schema * feat(scrapeURL/fire-engine/chrome-cdp): remove wait inserts on actions * scrapeURL: v0 backwards compat * logger fixes * feat(scrapeurl): v0 returnOnlyUrls support * fix(scrapeURL/v0): URL leniency * fix(batch-scrape): ts non-nullable * fix(scrapeURL/fire-engine/chromecdp): fix wait action * fix(logger): remove error debug key * feat(requests.http): use dotenv expression * fix(scrapeURL/extractMetadata): extract custom metadata * fix crawl option conversion * feat(scrapeURL): Add retry logic to robustFetch * fix(scrapeURL): crawl stuff * fix(scrapeURL): LLM extract * fix(scrapeURL/v0): search fix * fix(tests/v0): grant larger response size to v0 crawl status * feat(scrapeURL): basic fetch engine * feat(scrapeURL): playwright engine * feat(scrapeURL): add url-specific parameters * Update readme and examples * added e2e tests for most parameters. Still a few actions, location and iframes to be done. * fixed type * Nick: * Update scrape.ts * Update index.ts * added actions and base64 check * Nick: skipTls feature flag? * 403 * todo * todo * fixes * yeet headers from url specific params * add warning when final engine has feature deficit * expose engine results tracker for ScrapeEvents implementation * ingest scrape events * fixed some tests * comment * Update index.test.ts * fixed rawHtml * Update index.test.ts * update comments * move geolocation to global f-e option, fix removeBase64Images * Nick: * trim url-specific params * Update index.ts --------- Co-authored-by: Eric Ciarla <ericciarla@yahoo.com> Co-authored-by: rafaelmmiller <8574157+rafaelmmiller@users.noreply.github.com> Co-authored-by: Nicolas <nicolascamara29@gmail.com>
2024-11-07 20:57:33 +01:00
},
scrapeOptions: scrapeOptions.parse({}),
internalOptions: {},
2024-10-28 16:02:07 -03:00
team_id: teamId,
2024-08-16 17:57:11 -03:00
createdAt: Date.now(),
2024-12-11 19:51:08 -03:00
plan: plan,
2024-08-16 17:57:11 -03:00
};
const crawler = crawlToCrawler(id, sc);
2024-11-14 17:29:53 -05:00
// If sitemapOnly is true, only get links from sitemap
if (crawlerOptions.sitemapOnly) {
2025-01-10 18:35:10 -03:00
const sitemap = await crawler.tryGetSitemap(
(urls) => {
urls.forEach((x) => {
links.push(x);
});
},
true,
true,
);
if (sitemap > 0) {
2024-12-11 19:46:11 -03:00
links = links
.slice(1)
2024-11-15 21:14:32 +01:00
.map((x) => {
try {
return checkAndUpdateURLForMap(x).url.trim();
} catch (_) {
return null;
}
})
.filter((x) => x !== null) as string[];
// links = links.slice(1, limit); // don't slice, unnecessary
2024-11-14 17:29:53 -05:00
}
} else {
let urlWithoutWww = url.replace("www.", "");
2024-09-16 12:03:14 -04:00
2024-12-11 19:46:11 -03:00
let mapUrl =
search && allowExternalLinks
? `${search} ${urlWithoutWww}`
: search
? `${search} site:${urlWithoutWww}`
: `site:${url}`;
2024-09-16 12:03:14 -04:00
2024-11-14 17:29:53 -05:00
const resultsPerPage = 100;
2024-12-11 19:46:11 -03:00
const maxPages = Math.ceil(
2024-12-11 19:51:08 -03:00
Math.min(MAX_FIRE_ENGINE_RESULTS, limit) / resultsPerPage,
2024-12-11 19:46:11 -03:00
);
2024-09-06 20:14:47 -03:00
2024-11-14 17:29:53 -05:00
const cacheKey = `fireEngineMap:${mapUrl}`;
2024-11-20 13:01:36 -08:00
const cachedResult = await redis.get(cacheKey);
2024-08-16 17:57:11 -03:00
2024-11-14 17:29:53 -05:00
let allResults: any[] = [];
let pagePromises: Promise<any>[] = [];
2024-09-16 12:03:14 -04:00
2024-11-14 17:29:53 -05:00
if (cachedResult) {
allResults = JSON.parse(cachedResult);
} else {
const fetchPage = async (page: number) => {
return fireEngineMap(mapUrl, {
numResults: resultsPerPage,
2024-12-11 19:51:08 -03:00
page: page,
2024-11-14 17:29:53 -05:00
});
};
pagePromises = Array.from({ length: maxPages }, (_, i) =>
2024-12-11 19:51:08 -03:00
fetchPage(i + 1),
2024-11-14 17:29:53 -05:00
);
allResults = await Promise.all(pagePromises);
await redis.set(cacheKey, JSON.stringify(allResults), "EX", 24 * 60 * 60); // Cache for 24 hours
}
2024-08-16 17:57:11 -03:00
2024-11-14 17:29:53 -05:00
// Parallelize sitemap fetch with serper search
const [_, ...searchResults] = await Promise.all([
2025-01-10 18:35:10 -03:00
ignoreSitemap
? null
: crawler.tryGetSitemap((urls) => {
links.push(...urls);
}, true),
2024-12-11 19:51:08 -03:00
...(cachedResult ? [] : pagePromises),
2024-11-14 17:29:53 -05:00
]);
2024-08-26 16:56:27 -03:00
2024-11-14 17:29:53 -05:00
if (!cachedResult) {
allResults = searchResults;
}
2024-08-16 19:33:57 -04:00
mapResults = allResults
2024-11-14 17:29:53 -05:00
.flat()
.filter((result) => result !== null && result !== undefined);
const minumumCutoff = Math.min(MAX_MAP_LIMIT, limit);
if (mapResults.length > minumumCutoff) {
mapResults = mapResults.slice(0, minumumCutoff);
}
2024-08-28 15:40:30 -03:00
2024-11-14 17:29:53 -05:00
if (mapResults.length > 0) {
if (search) {
2024-11-14 17:29:53 -05:00
// Ensure all map results are first, maintaining their order
links = [
mapResults[0].url,
...mapResults.slice(1).map((x) => x.url),
2024-12-11 19:51:08 -03:00
...links,
2024-11-14 17:29:53 -05:00
];
} else {
mapResults.map((x) => {
links.push(x.url);
});
2024-09-16 12:03:14 -04:00
}
2024-11-14 17:29:53 -05:00
}
2024-08-20 12:17:53 -03:00
2024-11-15 21:14:32 +01:00
// Perform cosine similarity between the search query and the list of links
if (search) {
const searchQuery = search.toLowerCase();
2024-11-15 21:14:32 +01:00
links = performCosineSimilarity(links, searchQuery);
}
2024-08-16 19:33:57 -04:00
2024-11-15 21:14:32 +01:00
links = links
.map((x) => {
try {
return checkAndUpdateURLForMap(x).url.trim();
} catch (_) {
return null;
}
})
.filter((x) => x !== null) as string[];
// allows for subdomains to be included
links = links.filter((x) => isSameDomain(x, url));
2024-11-15 21:14:32 +01:00
// if includeSubdomains is false, filter out subdomains
if (!includeSubdomains) {
links = links.filter((x) => isSameSubdomain(x, url));
2024-11-15 21:14:32 +01:00
}
2024-08-16 19:33:57 -04:00
2024-11-15 21:14:32 +01:00
// remove duplicates that could be due to http/https or www
links = removeDuplicateUrls(links);
2024-08-16 19:33:57 -04:00
}
2024-08-20 16:43:46 -03:00
2024-12-11 19:46:11 -03:00
const linksToReturn = crawlerOptions.sitemapOnly
? links
: links.slice(0, limit);
2024-09-16 12:03:14 -04:00
2024-10-28 16:02:07 -03:00
return {
2024-08-16 17:57:11 -03:00
success: true,
links: linksToReturn,
mapResults: mapResults,
2024-11-12 12:10:18 -05:00
scrape_id: origin?.includes("website") ? id : undefined,
job_id: id,
2024-12-11 19:51:08 -03:00
time_taken: (new Date().getTime() - Date.now()) / 1000,
2024-10-28 16:02:07 -03:00
};
}
export async function mapController(
req: RequestWithAuth<{}, MapResponse, MapRequest>,
2024-12-11 19:51:08 -03:00
res: Response<MapResponse>,
2024-10-28 16:02:07 -03:00
) {
req.body = mapRequestSchema.parse(req.body);
2024-11-12 12:10:18 -05:00
const result = await getMapResults({
2024-10-28 16:02:07 -03:00
url: req.body.url,
search: req.body.search,
limit: req.body.limit,
ignoreSitemap: req.body.ignoreSitemap,
includeSubdomains: req.body.includeSubdomains,
2024-11-12 12:10:18 -05:00
crawlerOptions: req.body,
origin: req.body.origin,
2024-10-28 16:02:07 -03:00
teamId: req.auth.team_id,
2024-12-11 19:51:08 -03:00
plan: req.auth.plan,
});
// Bill the team
billTeam(req.auth.team_id, req.acuc?.sub_id, 1).catch((error) => {
logger.error(
2024-12-11 19:51:08 -03:00
`Failed to bill team ${req.auth.team_id} for 1 credit: ${error}`,
);
});
// Log the job
logJob({
job_id: result.job_id,
success: result.links.length > 0,
message: "Map completed",
num_docs: result.links.length,
docs: result.links,
time_taken: result.time_taken,
team_id: req.auth.team_id,
2024-12-11 19:46:11 -03:00
mode: "map",
url: req.body.url,
crawlerOptions: {},
scrapeOptions: {},
origin: req.body.origin ?? "api",
2024-12-11 19:51:08 -03:00
num_tokens: 0,
2024-10-28 16:02:07 -03:00
});
2024-11-12 12:10:18 -05:00
const response = {
success: true as const,
links: result.links,
2024-12-11 19:51:08 -03:00
scrape_id: result.scrape_id,
2024-11-12 12:10:18 -05:00
};
2024-08-26 16:56:27 -03:00
2024-11-12 12:10:18 -05:00
return res.status(200).json(response);
2024-12-11 19:46:11 -03:00
}