Files
firecrawl/apps/api/src/controllers/v1/map.ts
T

280 lines
7.2 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-08-16 19:33:57 -04:00
import {
mapRequestSchema,
RequestWithAuth,
2024-11-07 20:57:33 +01:00
scrapeOptions,
2024-08-16 19:33:57 -04: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-08-26 16:56:27 -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";
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();
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
const MAX_FIRE_ENGINE_RESULTS = 1000;
2024-08-06 15:24:45 -03:00
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,
subId,
2024-11-12 12:10:18 -05:00
includeMetadata = false
}: {
url: string;
search?: string;
limit?: number;
ignoreSitemap?: boolean;
includeSubdomains?: boolean;
crawlerOptions?: any;
teamId: string;
plan?: string;
origin?: string;
subId: string | null;
includeMetadata?: boolean;
}) {
2024-08-16 17:57:11 -03:00
const id = uuidv4();
2024-11-12 12:10:18 -05:00
let links: string[] = [url];
2024-08-16 17:57:11 -03:00
const sc: StoredCrawl = {
2024-10-28 16:02:07 -03:00
originUrl: url,
2024-11-07 20:57:33 +01:00
crawlerOptions: {
2024-11-12 12:10:18 -05:00
...crawlerOptions,
2024-11-07 20:57:33 +01:00
scrapeOptions: undefined,
},
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-11-12 12:10:18 -05:00
plan: plan,
2024-08-16 17:57:11 -03:00
};
const crawler = crawlToCrawler(id, sc);
2024-10-28 16:02:07 -03:00
let urlWithoutWww = url.replace("www.", "");
2024-09-06 20:14:47 -03:00
2024-11-12 12:10:18 -05:00
let mapUrl = search
? `"${search}" site:${urlWithoutWww}`
: `site:${url}`;
2024-09-06 20:14:47 -03:00
const resultsPerPage = 100;
2024-09-16 12:03:14 -04:00
const maxPages = Math.ceil(Math.min(MAX_FIRE_ENGINE_RESULTS, limit) / resultsPerPage);
2024-09-06 20:14:47 -03:00
2024-09-16 12:03:14 -04:00
const cacheKey = `fireEngineMap:${mapUrl}`;
2024-10-12 17:48:37 -03:00
const cachedResult = null;
2024-09-16 12:03:14 -04:00
2024-11-07 20:57:33 +01:00
let allResults: any[] = [];
let pagePromises: Promise<any>[] = [];
2024-09-16 12:03:14 -04:00
if (cachedResult) {
allResults = JSON.parse(cachedResult);
} else {
const fetchPage = async (page: number) => {
return fireEngineMap(mapUrl, {
numResults: resultsPerPage,
page: page,
});
};
pagePromises = Array.from({ length: maxPages }, (_, i) => fetchPage(i + 1));
allResults = await Promise.all(pagePromises);
await redis.set(cacheKey, JSON.stringify(allResults), "EX", 24 * 60 * 60); // Cache for 24 hours
}
2024-09-06 20:14:47 -03:00
2024-11-12 12:10:18 -05:00
console.log("allResults", allResults);
2024-09-06 20:14:47 -03:00
// Parallelize sitemap fetch with serper search
2024-09-16 12:03:14 -04:00
const [sitemap, ...searchResults] = await Promise.all([
2024-10-28 16:02:07 -03:00
ignoreSitemap ? null : crawler.tryGetSitemap(),
2024-09-16 12:03:14 -04:00
...(cachedResult ? [] : pagePromises),
2024-09-06 20:14:47 -03:00
]);
2024-08-16 17:57:11 -03:00
2024-09-16 12:03:14 -04:00
if (!cachedResult) {
allResults = searchResults;
}
2024-08-16 17:57:11 -03:00
if (sitemap !== null) {
2024-09-06 20:14:47 -03:00
sitemap.forEach((x) => {
2024-08-16 19:33:57 -04:00
links.push(x.url);
});
2024-08-16 17:57:11 -03:00
}
2024-09-16 12:03:14 -04:00
let mapResults = allResults
.flat()
.filter((result) => result !== null && result !== undefined);
2024-08-26 16:56:27 -03:00
2024-09-16 12:03:14 -04:00
const minumumCutoff = Math.min(MAX_MAP_LIMIT, limit);
if (mapResults.length > minumumCutoff) {
mapResults = mapResults.slice(0, minumumCutoff);
2024-09-06 20:14:47 -03:00
}
2024-08-16 19:33:57 -04:00
if (mapResults.length > 0) {
2024-10-28 16:02:07 -03:00
if (search) {
2024-08-20 12:17:53 -03:00
// Ensure all map results are first, maintaining their order
2024-08-26 16:56:27 -03:00
links = [
mapResults[0].url,
...mapResults.slice(1).map((x) => x.url),
...links,
];
2024-08-20 12:17:53 -03:00
} else {
mapResults.map((x) => {
2024-08-16 19:55:44 -04:00
links.push(x.url);
2024-08-20 12:17:53 -03:00
});
}
2024-08-16 17:57:11 -03:00
}
2024-08-28 15:40:30 -03:00
// Perform cosine similarity between the search query and the list of links
2024-10-28 16:02:07 -03:00
if (search) {
2024-11-12 12:10:18 -05:00
const searchQuery = search.toLowerCase();
links = performCosineSimilarity(links, searchQuery);
2024-08-28 15:40:30 -03:00
}
2024-09-16 12:03:14 -04:00
links = links
.map((x) => {
try {
return checkAndUpdateURLForMap(x).url.trim();
} catch (_) {
return null;
}
})
2024-11-07 20:57:33 +01:00
.filter((x) => x !== null) as string[];
2024-08-20 12:17:53 -03:00
2024-08-16 19:33:57 -04:00
// allows for subdomains to be included
2024-11-12 12:10:18 -05:00
links = links.filter((x) => isSameDomain(x, url));
2024-08-16 19:33:57 -04:00
// if includeSubdomains is false, filter out subdomains
2024-10-28 16:02:07 -03:00
if (!includeSubdomains) {
2024-11-12 12:10:18 -05:00
links = links.filter((x) => isSameSubdomain(x, url));
2024-08-16 19:33:57 -04:00
}
// remove duplicates that could be due to http/https or www
2024-08-26 16:56:27 -03:00
links = removeDuplicateUrls(links);
2024-08-20 16:43:46 -03:00
2024-11-12 12:10:18 -05:00
billTeam(teamId, subId, 1).catch((error) => {
2024-11-07 20:57:33 +01:00
logger.error(
2024-11-12 12:10:18 -05:00
`Failed to bill team ${teamId} for 1 credit: ${error}`
2024-09-16 12:03:14 -04:00
);
2024-09-03 21:09:32 -03:00
});
2024-08-26 16:56:27 -03:00
2024-08-27 11:11:59 -03:00
const linksToReturn = links.slice(0, limit);
2024-09-16 12:03:14 -04:00
2024-08-26 16:56:27 -03:00
logJob({
job_id: id,
2024-08-26 18:48:00 -03:00
success: links.length > 0,
2024-11-12 12:10:18 -05:00
message: "Map completed",
2024-09-01 19:52:21 -03:00
num_docs: linksToReturn.length,
2024-08-27 11:11:59 -03:00
docs: linksToReturn,
2024-11-12 12:10:18 -05:00
time_taken: (new Date().getTime() - Date.now()) / 1000,
team_id: teamId,
2024-08-26 16:56:27 -03:00
mode: "map",
2024-11-12 12:10:18 -05:00
url: url,
2024-08-26 16:56:27 -03:00
crawlerOptions: {},
2024-11-07 20:57:33 +01:00
scrapeOptions: {},
2024-11-12 12:10:18 -05:00
origin: origin ?? "api",
2024-08-26 16:56:27 -03:00
num_tokens: 0,
});
2024-10-28 16:02:07 -03:00
return {
2024-08-16 17:57:11 -03:00
success: true,
2024-11-12 12:10:18 -05:00
links: includeMetadata ? mapResults : linksToReturn,
scrape_id: origin?.includes("website") ? id : undefined,
2024-10-28 16:02:07 -03:00
};
}
export async function mapController(
req: RequestWithAuth<{}, MapResponse, MapRequest>,
res: Response<MapResponse>
) {
req.body = mapRequestSchema.parse(req.body);
2024-11-12 12:10:18 -05:00
console.log("req.body", req.body);
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,
2024-10-28 16:02:07 -03:00
teamId: req.auth.team_id,
plan: req.auth.plan,
origin: req.body.origin,
2024-11-12 12:10:18 -05:00
subId: req.acuc?.sub_id
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,
scrape_id: result.scrape_id
};
2024-08-26 16:56:27 -03:00
2024-11-12 12:10:18 -05:00
return res.status(200).json(response);
2024-08-06 15:24:45 -03:00
}
2024-09-16 12:03:14 -04:00
// Subdomain sitemap url checking
// // For each result, check for subdomains, get their sitemaps and add them to the links
// const processedUrls = new Set();
// const processedSubdomains = new Set();
// for (const result of links) {
// let url;
// let hostParts;
// try {
// url = new URL(result);
// hostParts = url.hostname.split('.');
// } catch (e) {
// continue;
// }
// console.log("hostParts", hostParts);
// // Check if it's a subdomain (more than 2 parts, and not 'www')
// if (hostParts.length > 2 && hostParts[0] !== 'www') {
// const subdomain = hostParts[0];
// console.log("subdomain", subdomain);
// const subdomainUrl = `${url.protocol}//${subdomain}.${hostParts.slice(-2).join('.')}`;
// console.log("subdomainUrl", subdomainUrl);
// if (!processedSubdomains.has(subdomainUrl)) {
// processedSubdomains.add(subdomainUrl);
// const subdomainCrawl = crawlToCrawler(id, {
// originUrl: subdomainUrl,
// crawlerOptions: legacyCrawlerOptions(req.body),
// pageOptions: {},
// team_id: req.auth.team_id,
// createdAt: Date.now(),
// plan: req.auth.plan,
// });
// const subdomainSitemap = await subdomainCrawl.tryGetSitemap();
// if (subdomainSitemap) {
// subdomainSitemap.forEach((x) => {
// if (!processedUrls.has(x.url)) {
// processedUrls.add(x.url);
// links.push(x.url);
// }
// });
// }
// }
// }
2024-11-12 12:10:18 -05:00
// }