/** * Copyright 2026 aphrody-code * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { type CommonOptions, logger, EXIT } from "./shared.ts"; import { MassiveCrawler } from "../crawler/MassiveCrawler.ts"; import { AutonomousCrawler } from "../crawler/AutonomousCrawler.ts"; function printUsage(): void { Bun.stdout.write( `bxc crawl — High-throughput web crawler & continuous indexer. Usage: bxc crawl [options] [initial_urls...] Modes: --massive Continuous 24/7 multi-tiered web indexer with FTS5 and politeness --workers Use persistent multi-worker thread pool for browser crawling --daemon Continuous 24/7 daemon mode (never stops, polls for new URLs) Tuning & Limits: --concurrency Set fixed or maximum concurrency (default: 10 in standard, 50 in massive) --min-concurrency Adaptive pool minimum (default: 2) --max-concurrency Adaptive pool maximum (default: 20 or 100 in massive) --max-depth Recursion depth limit (default: 5) --max-requests Maximum total pages to crawl (default: Infinity) --max-retries Maximum retries before dead-lettering (default: 3) --profile Profile: static | http | fast | stealth | max (default: stealth) --allowed-domains Comma-separated allowed domains --exclude Exclude URL pattern regex (repeatable) --proxy-pool Comma-separated proxy list for rotation --obey-robots Respect robots.txt and crawl-delay Massive indexer (--massive): --ladder Tier ladder, cheapest first (default: http,render,stealth) --goal Focused crawl: prioritise links whose anchor text matches --per-host-delay Minimum delay between requests to one domain (default: learned) --max-per-host Maximum concurrent requests per domain (default: 8) --revisit Re-crawl pages according to their estimated change rate --vectors Embed chunks for semantic search (local model when installed) --no-dedup Index canonical variants and near-duplicates too Database & Export: --sqlite Direct SQLite database output path with FTS5 indexing --postgres Direct PostgreSQL database connection URL --queue Custom RequestQueue persistent frontier name Examples: bxc crawl https://example.com --profile fast bxc crawl --massive --daemon --sqlite ./web-index.sqlite https://news.ycombinator.com bxc crawl --workers --concurrency 16 https://example.org `, ); } export async function main( argv: string[], baseOpts: CommonOptions, cliOptions?: { exitProcess?: boolean }, ): Promise { const exitProcess = cliOptions?.exitProcess ?? process.env.NODE_ENV !== "test"; let massive = false; let useWorkers = false; let daemon = false; let concurrency: number | undefined; let minConcurrency: number | undefined; let maxConcurrency: number | undefined; let maxDepth = 5; let maxRequests = Infinity; let maxRetries = 3; let profile: "static" | "http" | "fast" | "stealth" | "max" = "stealth"; let allowedDomains: string[] | undefined; const excludePatterns: string[] = []; let proxyPool: string[] | undefined; let obeyRobots = false; let sqlitePath: string | undefined; let postgresUrl: string | undefined; let queueName = "bxc-crawl"; let ladder: Array<"http" | "render" | "fast" | "stealth" | "max"> | undefined; let goal: string | undefined; let perHostDelayMs: number | undefined; let maxInFlightPerHost: number | undefined; let enableRevisits = false; let enableVectors = false; let dedup = true; const initialUrls: string[] = []; for (let i = 0; i < argv.length; i++) { const arg = argv[i]; if (arg === "--massive") { massive = true; } else if (arg === "--workers") { useWorkers = true; } else if (arg === "--daemon") { daemon = true; } else if (arg === "--concurrency") { concurrency = parseInt(argv[++i], 10); } else if (arg === "--min-concurrency") { minConcurrency = parseInt(argv[++i], 10); } else if (arg === "--max-concurrency") { maxConcurrency = parseInt(argv[++i], 10); } else if (arg === "--max-depth") { maxDepth = parseInt(argv[++i], 10); } else if (arg === "--max-requests") { maxRequests = parseInt(argv[++i], 10); } else if (arg === "--max-retries") { maxRetries = parseInt(argv[++i], 10); } else if (arg === "--profile") { const val = argv[++i]; if (val === "static" || val === "http" || val === "fast" || val === "stealth" || val === "max") { profile = val; } } else if (arg === "--allowed-domains") { allowedDomains = argv[++i].split(",").map((s) => s.trim()); } else if (arg === "--exclude") { excludePatterns.push(argv[++i]); } else if (arg === "--proxy-pool") { proxyPool = argv[++i].split(",").map((s) => s.trim()); } else if (arg === "--obey-robots") { obeyRobots = true; } else if (arg === "--sqlite") { sqlitePath = argv[++i]; } else if (arg === "--postgres") { postgresUrl = argv[++i]; } else if (arg === "--queue") { queueName = argv[++i]; } else if (arg === "--ladder") { ladder = argv[++i] .split(",") .map((t) => t.trim()) .filter((t): t is "http" | "render" | "fast" | "stealth" | "max" => ["http", "render", "fast", "stealth", "max"].includes(t), ); } else if (arg === "--goal") { goal = argv[++i]; } else if (arg === "--per-host-delay") { perHostDelayMs = parseInt(argv[++i], 10); } else if (arg === "--max-per-host") { maxInFlightPerHost = parseInt(argv[++i], 10); } else if (arg === "--revisit") { enableRevisits = true; } else if (arg === "--vectors") { enableVectors = true; } else if (arg === "--no-dedup") { dedup = false; } else if (arg === "--help" || arg === "-h") { printUsage(); return; } else if (arg.startsWith("-")) { logger.error(`Unknown option: ${arg}`); printUsage(); if (exitProcess) process.exit(EXIT.MISUSE); return; } else { initialUrls.push(arg); } } if (concurrency !== undefined) { minConcurrency = concurrency; maxConcurrency = concurrency; } logger.log(`[crawl] Starting crawler: massive=${massive} workers=${useWorkers} profile=${profile} daemon=${daemon}`); if (massive) { const crawler = new MassiveCrawler({ requestQueueName: queueName, allowedDomains, excludePatterns, maxDepth, maxRequests, minConcurrency: minConcurrency ?? 5, maxConcurrency: maxConcurrency ?? 50, maxRetries, daemon, proxyPool, sqliteDbPath: sqlitePath, postgresUrl, obeyRobots, ladder, goal, perHostDelayMs, maxInFlightPerHost, enableRevisits, enableVectors, dedup, }); const stopHandler = () => { logger.log("\n[crawl] Graceful shutdown triggered..."); crawler.stop(); }; process.on("SIGINT", stopHandler); process.on("SIGTERM", stopHandler); try { await crawler.run(initialUrls); logger.log("[crawl] Massive crawl run completed."); } finally { (process as NodeJS.EventEmitter).removeListener("SIGINT", stopHandler); (process as NodeJS.EventEmitter).removeListener("SIGTERM", stopHandler); } return; } // Standard or autonomous crawler mode const crawler = new AutonomousCrawler({ requestQueueName: queueName, allowedDomains, excludePatterns, maxDepth, maxRequests, minConcurrency: minConcurrency ?? 2, maxConcurrency: maxConcurrency ?? 20, maxRetries, profile, daemon, proxyPool, }); const stopHandler = () => { logger.log("\n[crawl] Graceful shutdown triggered..."); crawler.stop(); }; process.on("SIGINT", stopHandler); process.on("SIGTERM", stopHandler); try { await crawler.run(initialUrls); logger.log("[crawl] Crawl run completed."); } finally { (process as NodeJS.EventEmitter).removeListener("SIGINT", stopHandler); (process as NodeJS.EventEmitter).removeListener("SIGTERM", stopHandler); } }