@vakra-dev/reader 0.0.3 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -13,196 +13,6 @@ import { ConnectionToHeroCore } from "@ulixee/hero";
13
13
  // src/scraper.ts
14
14
  import pLimit from "p-limit";
15
15
 
16
- // src/cloudflare/detector.ts
17
- var CLOUDFLARE_CHALLENGE_SELECTORS = [
18
- "#challenge-running",
19
- "#challenge-stage",
20
- "#challenge-form",
21
- ".cf-browser-verification",
22
- "#cf-wrapper",
23
- "#cf-hcaptcha-container",
24
- "#turnstile-wrapper"
25
- ];
26
- var CLOUDFLARE_TEXT_PATTERNS = [
27
- "checking if the site connection is secure",
28
- "this process is automatic. your browser will redirect",
29
- "ray id:",
30
- "performance & security by cloudflare"
31
- ];
32
- var CLOUDFLARE_INFRA_PATTERNS = [
33
- "/cdn-cgi/",
34
- "cloudflare",
35
- "__cf_bm",
36
- "cf-ray"
37
- ];
38
- var CLOUDFLARE_BLOCKED_PATTERNS = [
39
- "sorry, you have been blocked",
40
- "ray id:"
41
- ];
42
- async function detectChallenge(hero) {
43
- const signals = [];
44
- let type = "none";
45
- let hasCloudflareInfra = false;
46
- let hasChallengeIndicator = false;
47
- try {
48
- if (!hero.document) {
49
- return {
50
- isChallenge: false,
51
- type: "none",
52
- confidence: 0,
53
- signals: ["No document available"]
54
- };
55
- }
56
- const html = await hero.document.documentElement.outerHTML;
57
- const htmlLower = html.toLowerCase();
58
- for (const pattern of CLOUDFLARE_INFRA_PATTERNS) {
59
- if (htmlLower.includes(pattern)) {
60
- hasCloudflareInfra = true;
61
- signals.push(`Cloudflare infra: "${pattern}"`);
62
- break;
63
- }
64
- }
65
- if (!hasCloudflareInfra) {
66
- return {
67
- isChallenge: false,
68
- type: "none",
69
- confidence: 0,
70
- signals: ["No Cloudflare infrastructure detected"]
71
- };
72
- }
73
- for (const selector of CLOUDFLARE_CHALLENGE_SELECTORS) {
74
- try {
75
- const element = await hero.document.querySelector(selector);
76
- if (element) {
77
- hasChallengeIndicator = true;
78
- signals.push(`Challenge element: ${selector}`);
79
- type = "js_challenge";
80
- }
81
- } catch {
82
- }
83
- }
84
- for (const pattern of CLOUDFLARE_TEXT_PATTERNS) {
85
- if (htmlLower.includes(pattern)) {
86
- hasChallengeIndicator = true;
87
- signals.push(`Challenge text: "${pattern}"`);
88
- type = type === "none" ? "js_challenge" : type;
89
- }
90
- }
91
- if (htmlLower.includes("waiting for") && htmlLower.includes("to respond")) {
92
- hasChallengeIndicator = true;
93
- signals.push('Challenge text: "waiting for...to respond"');
94
- type = type === "none" ? "js_challenge" : type;
95
- }
96
- const hasBlocked = CLOUDFLARE_BLOCKED_PATTERNS.every((p) => htmlLower.includes(p));
97
- if (hasBlocked) {
98
- hasChallengeIndicator = true;
99
- signals.push("Cloudflare block page detected");
100
- type = "blocked";
101
- }
102
- const isChallenge = hasCloudflareInfra && hasChallengeIndicator;
103
- const confidence = isChallenge ? 100 : 0;
104
- return {
105
- isChallenge,
106
- type: isChallenge ? type : "none",
107
- confidence,
108
- signals
109
- };
110
- } catch (error) {
111
- return {
112
- isChallenge: false,
113
- type: "none",
114
- confidence: 0,
115
- signals: [`Error during detection: ${error.message}`]
116
- };
117
- }
118
- }
119
- async function isChallengePage(hero) {
120
- const detection = await detectChallenge(hero);
121
- return detection.isChallenge;
122
- }
123
-
124
- // src/cloudflare/handler.ts
125
- async function waitForChallengeResolution(hero, options) {
126
- const { maxWaitMs = 45e3, pollIntervalMs = 500, verbose = false, initialUrl } = options;
127
- const startTime = Date.now();
128
- const log = (msg) => verbose && console.log(` ${msg}`);
129
- while (Date.now() - startTime < maxWaitMs) {
130
- const elapsed = Date.now() - startTime;
131
- try {
132
- const currentUrl = await hero.url;
133
- if (currentUrl !== initialUrl) {
134
- log(`\u2713 URL changed: ${initialUrl} \u2192 ${currentUrl}`);
135
- log(` Waiting for new page to load...`);
136
- try {
137
- await hero.waitForLoad("DomContentLoaded", { timeoutMs: 3e4 });
138
- log(` DOMContentLoaded`);
139
- } catch {
140
- log(` DOMContentLoaded timeout, continuing...`);
141
- }
142
- await hero.waitForPaintingStable().catch(() => {
143
- });
144
- log(` Page stabilized`);
145
- return { resolved: true, method: "url_redirect", waitedMs: elapsed };
146
- }
147
- } catch {
148
- }
149
- const detection = await detectChallenge(hero);
150
- if (!detection.isChallenge) {
151
- log(`\u2713 Challenge signals cleared (confidence dropped to ${detection.confidence})`);
152
- log(` Waiting for page to load...`);
153
- try {
154
- await hero.waitForLoad("DomContentLoaded", { timeoutMs: 3e4 });
155
- log(` DOMContentLoaded`);
156
- } catch {
157
- log(` DOMContentLoaded timeout, continuing...`);
158
- }
159
- await hero.waitForPaintingStable().catch(() => {
160
- });
161
- log(` Page stabilized`);
162
- return { resolved: true, method: "signals_cleared", waitedMs: elapsed };
163
- }
164
- log(
165
- `\u23F3 ${(elapsed / 1e3).toFixed(1)}s - Still challenge (confidence: ${detection.confidence})`
166
- );
167
- await new Promise((resolve) => setTimeout(resolve, pollIntervalMs));
168
- }
169
- return {
170
- resolved: false,
171
- method: "timeout",
172
- waitedMs: Date.now() - startTime
173
- };
174
- }
175
- async function waitForSelector(hero, selector, maxWaitMs, verbose = false) {
176
- const startTime = Date.now();
177
- const log = (msg) => verbose && console.log(` ${msg}`);
178
- log(`Waiting for selector: "${selector}"`);
179
- while (Date.now() - startTime < maxWaitMs) {
180
- try {
181
- const element = await hero.document.querySelector(selector);
182
- if (element) {
183
- const elapsed = Date.now() - startTime;
184
- log(`\u2713 Selector found after ${(elapsed / 1e3).toFixed(1)}s`);
185
- return { found: true, waitedMs: elapsed };
186
- }
187
- } catch {
188
- }
189
- await new Promise((resolve) => setTimeout(resolve, 300));
190
- }
191
- log(`\u2717 Selector not found within timeout`);
192
- return { found: false, waitedMs: Date.now() - startTime };
193
- }
194
- async function handleChallenge(hero, options = {}) {
195
- const initialUrl = await hero.url;
196
- const detection = await detectChallenge(hero);
197
- if (!detection.isChallenge) {
198
- return { resolved: true, method: "signals_cleared", waitedMs: 0 };
199
- }
200
- return waitForChallengeResolution(hero, {
201
- ...options,
202
- initialUrl
203
- });
204
- }
205
-
206
16
  // src/formatters/markdown.ts
207
17
  import TurndownService from "turndown";
208
18
  var turndownService = new TurndownService({
@@ -1259,96 +1069,701 @@ function shouldCrawlUrl2(url, baseDomain) {
1259
1069
  return url.hostname === baseDomain || url.hostname.endsWith(`.${baseDomain}`);
1260
1070
  }
1261
1071
 
1262
- // src/scraper.ts
1263
- var Scraper = class {
1264
- options;
1265
- pool;
1266
- logger = createLogger("scraper");
1267
- robotsCache = /* @__PURE__ */ new Map();
1268
- constructor(options) {
1269
- this.options = {
1270
- ...DEFAULT_OPTIONS,
1271
- ...options
1272
- };
1273
- if (!options.pool) {
1274
- throw new Error("Browser pool must be provided. Use ReaderClient for automatic pool management.");
1072
+ // src/engines/types.ts
1073
+ var ENGINE_CONFIGS = {
1074
+ http: {
1075
+ name: "http",
1076
+ timeout: 3e3,
1077
+ maxTimeout: 1e4,
1078
+ quality: 100,
1079
+ features: {
1080
+ javascript: false,
1081
+ cloudflare: false,
1082
+ tlsFingerprint: false,
1083
+ waitFor: false,
1084
+ screenshots: false
1085
+ }
1086
+ },
1087
+ tlsclient: {
1088
+ name: "tlsclient",
1089
+ timeout: 5e3,
1090
+ maxTimeout: 15e3,
1091
+ quality: 80,
1092
+ features: {
1093
+ javascript: false,
1094
+ cloudflare: false,
1095
+ tlsFingerprint: true,
1096
+ waitFor: false,
1097
+ screenshots: false
1098
+ }
1099
+ },
1100
+ hero: {
1101
+ name: "hero",
1102
+ timeout: 3e4,
1103
+ maxTimeout: 6e4,
1104
+ quality: 50,
1105
+ features: {
1106
+ javascript: true,
1107
+ cloudflare: true,
1108
+ tlsFingerprint: true,
1109
+ waitFor: true,
1110
+ screenshots: true
1275
1111
  }
1276
- this.pool = options.pool;
1277
1112
  }
1278
- /**
1279
- * Get robots.txt rules for a URL, cached per domain
1280
- */
1281
- async getRobotsRules(url) {
1282
- const origin = new URL(url).origin;
1283
- if (!this.robotsCache.has(origin)) {
1284
- const rules = await fetchRobotsTxt(origin);
1285
- this.robotsCache.set(origin, rules);
1113
+ };
1114
+ var DEFAULT_ENGINE_ORDER = ["http", "tlsclient", "hero"];
1115
+
1116
+ // src/engines/errors.ts
1117
+ var EngineError = class extends Error {
1118
+ engine;
1119
+ retryable;
1120
+ constructor(engine, message, options) {
1121
+ super(`[${engine}] ${message}`);
1122
+ this.name = "EngineError";
1123
+ this.engine = engine;
1124
+ this.retryable = options?.retryable ?? true;
1125
+ this.cause = options?.cause;
1126
+ if (Error.captureStackTrace) {
1127
+ Error.captureStackTrace(this, this.constructor);
1286
1128
  }
1287
- return this.robotsCache.get(origin) ?? null;
1288
1129
  }
1289
- /**
1290
- * Scrape all URLs
1291
- *
1292
- * @returns Scrape result with pages and metadata
1293
- */
1294
- async scrape() {
1295
- const startTime = Date.now();
1296
- const results = await this.scrapeWithConcurrency();
1297
- return this.buildScrapeResult(results, startTime);
1130
+ };
1131
+ var ChallengeDetectedError = class extends EngineError {
1132
+ challengeType;
1133
+ constructor(engine, challengeType) {
1134
+ super(engine, `Challenge detected: ${challengeType || "unknown"}`, { retryable: true });
1135
+ this.name = "ChallengeDetectedError";
1136
+ this.challengeType = challengeType || "unknown";
1298
1137
  }
1299
- /**
1300
- * Scrape URLs with concurrency control
1301
- */
1302
- async scrapeWithConcurrency() {
1303
- const limit = pLimit(this.options.batchConcurrency || 1);
1304
- const tasks = this.options.urls.map(
1305
- (url, index) => limit(() => this.scrapeSingleUrlWithRetry(url, index))
1306
- );
1307
- const batchPromise = Promise.all(tasks);
1308
- if (this.options.batchTimeoutMs && this.options.batchTimeoutMs > 0) {
1309
- const timeoutPromise = new Promise((_, reject) => {
1310
- setTimeout(() => {
1311
- reject(new Error(`Batch operation timed out after ${this.options.batchTimeoutMs}ms`));
1312
- }, this.options.batchTimeoutMs);
1313
- });
1314
- return Promise.race([batchPromise, timeoutPromise]);
1315
- }
1316
- return batchPromise;
1138
+ };
1139
+ var InsufficientContentError = class extends EngineError {
1140
+ contentLength;
1141
+ threshold;
1142
+ constructor(engine, contentLength, threshold = 100) {
1143
+ super(engine, `Insufficient content: ${contentLength} chars (threshold: ${threshold})`, { retryable: true });
1144
+ this.name = "InsufficientContentError";
1145
+ this.contentLength = contentLength;
1146
+ this.threshold = threshold;
1317
1147
  }
1318
- /**
1319
- * Scrape a single URL with retry logic
1320
- */
1321
- async scrapeSingleUrlWithRetry(url, index) {
1322
- const maxRetries = this.options.maxRetries || 2;
1323
- let lastError;
1324
- for (let attempt = 0; attempt <= maxRetries; attempt++) {
1148
+ };
1149
+ var HttpError = class extends EngineError {
1150
+ statusCode;
1151
+ constructor(engine, statusCode, statusText) {
1152
+ const retryable = statusCode >= 500 || statusCode === 429;
1153
+ super(engine, `HTTP ${statusCode}${statusText ? `: ${statusText}` : ""}`, { retryable });
1154
+ this.name = "HttpError";
1155
+ this.statusCode = statusCode;
1156
+ }
1157
+ };
1158
+ var EngineTimeoutError = class extends EngineError {
1159
+ timeoutMs;
1160
+ constructor(engine, timeoutMs) {
1161
+ super(engine, `Timeout after ${timeoutMs}ms`, { retryable: true });
1162
+ this.name = "EngineTimeoutError";
1163
+ this.timeoutMs = timeoutMs;
1164
+ }
1165
+ };
1166
+ var EngineUnavailableError = class extends EngineError {
1167
+ constructor(engine, reason) {
1168
+ super(engine, reason || "Engine not available", { retryable: false });
1169
+ this.name = "EngineUnavailableError";
1170
+ }
1171
+ };
1172
+ var AllEnginesFailedError = class extends Error {
1173
+ attemptedEngines;
1174
+ errors;
1175
+ constructor(attemptedEngines, errors) {
1176
+ const summary = attemptedEngines.map((e) => `${e}: ${errors.get(e)?.message || "unknown"}`).join("; ");
1177
+ super(`All engines failed: ${summary}`);
1178
+ this.name = "AllEnginesFailedError";
1179
+ this.attemptedEngines = attemptedEngines;
1180
+ this.errors = errors;
1181
+ }
1182
+ };
1183
+
1184
+ // src/engines/http/index.ts
1185
+ var DEFAULT_HEADERS = {
1186
+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
1187
+ Accept: "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8",
1188
+ "Accept-Language": "en-US,en;q=0.9",
1189
+ "Accept-Encoding": "gzip, deflate, br",
1190
+ "Cache-Control": "no-cache",
1191
+ Pragma: "no-cache",
1192
+ "Sec-Fetch-Dest": "document",
1193
+ "Sec-Fetch-Mode": "navigate",
1194
+ "Sec-Fetch-Site": "none",
1195
+ "Sec-Fetch-User": "?1",
1196
+ "Upgrade-Insecure-Requests": "1"
1197
+ };
1198
+ var CHALLENGE_PATTERNS = [
1199
+ // Cloudflare
1200
+ "cf-browser-verification",
1201
+ "cf_chl_opt",
1202
+ "challenge-platform",
1203
+ "cf-spinner",
1204
+ "Just a moment",
1205
+ "Checking your browser",
1206
+ "checking if the site connection is secure",
1207
+ "Enable JavaScript and cookies",
1208
+ "Attention Required",
1209
+ "_cf_chl_tk",
1210
+ "Verifying you are human",
1211
+ "cf-turnstile",
1212
+ "/cdn-cgi/challenge-platform/",
1213
+ // Generic bot detection
1214
+ "Please Wait...",
1215
+ "DDoS protection by",
1216
+ "Access denied",
1217
+ "bot detection",
1218
+ "are you a robot",
1219
+ "complete the security check"
1220
+ ];
1221
+ var CLOUDFLARE_INFRA_PATTERNS = ["/cdn-cgi/", "cloudflare", "__cf_bm", "cf-ray"];
1222
+ var MIN_CONTENT_LENGTH = 100;
1223
+ var HttpEngine = class {
1224
+ config = ENGINE_CONFIGS.http;
1225
+ async scrape(meta) {
1226
+ const startTime = Date.now();
1227
+ const { url, options, logger: logger4, abortSignal } = meta;
1228
+ try {
1229
+ const controller = new AbortController();
1230
+ const timeoutId = setTimeout(() => controller.abort(), this.config.maxTimeout);
1231
+ if (abortSignal) {
1232
+ abortSignal.addEventListener("abort", () => controller.abort(), { once: true });
1233
+ }
1234
+ logger4?.debug(`[http] Fetching ${url}`);
1235
+ const response = await fetch(url, {
1236
+ method: "GET",
1237
+ headers: {
1238
+ ...DEFAULT_HEADERS,
1239
+ ...options.headers || {}
1240
+ },
1241
+ redirect: "follow",
1242
+ signal: controller.signal
1243
+ });
1244
+ clearTimeout(timeoutId);
1245
+ const duration = Date.now() - startTime;
1246
+ const html = await response.text();
1247
+ logger4?.debug(`[http] Got response: ${response.status} (${html.length} chars) in ${duration}ms`);
1248
+ if (response.status >= 400) {
1249
+ throw new HttpError("http", response.status, response.statusText);
1250
+ }
1251
+ const challengeType = this.detectChallenge(html);
1252
+ if (challengeType) {
1253
+ logger4?.debug(`[http] Challenge detected: ${challengeType}`);
1254
+ throw new ChallengeDetectedError("http", challengeType);
1255
+ }
1256
+ const textContent = this.extractText(html);
1257
+ if (textContent.length < MIN_CONTENT_LENGTH) {
1258
+ logger4?.debug(`[http] Insufficient content: ${textContent.length} chars`);
1259
+ throw new InsufficientContentError("http", textContent.length, MIN_CONTENT_LENGTH);
1260
+ }
1261
+ return {
1262
+ html,
1263
+ url: response.url,
1264
+ statusCode: response.status,
1265
+ contentType: response.headers.get("content-type") || void 0,
1266
+ headers: this.headersToRecord(response.headers),
1267
+ engine: "http",
1268
+ duration
1269
+ };
1270
+ } catch (error) {
1271
+ if (error instanceof ChallengeDetectedError || error instanceof InsufficientContentError || error instanceof HttpError) {
1272
+ throw error;
1273
+ }
1274
+ if (error instanceof Error) {
1275
+ if (error.name === "AbortError") {
1276
+ throw new EngineTimeoutError("http", this.config.maxTimeout);
1277
+ }
1278
+ throw new EngineError("http", error.message, { cause: error });
1279
+ }
1280
+ throw new EngineError("http", String(error));
1281
+ }
1282
+ }
1283
+ /**
1284
+ * Detect challenge patterns in HTML
1285
+ * @returns Challenge type or null if no challenge detected
1286
+ */
1287
+ detectChallenge(html) {
1288
+ const htmlLower = html.toLowerCase();
1289
+ const hasCloudflare = CLOUDFLARE_INFRA_PATTERNS.some((p) => htmlLower.includes(p.toLowerCase()));
1290
+ for (const pattern of CHALLENGE_PATTERNS) {
1291
+ if (htmlLower.includes(pattern.toLowerCase())) {
1292
+ if (hasCloudflare || pattern.includes("cf")) {
1293
+ return "cloudflare";
1294
+ }
1295
+ return "bot-detection";
1296
+ }
1297
+ }
1298
+ return null;
1299
+ }
1300
+ /**
1301
+ * Convert Headers to Record<string, string>
1302
+ */
1303
+ headersToRecord(headers) {
1304
+ const record = {};
1305
+ headers.forEach((value, key) => {
1306
+ record[key] = value;
1307
+ });
1308
+ return record;
1309
+ }
1310
+ /**
1311
+ * Extract visible text from HTML (rough extraction)
1312
+ */
1313
+ extractText(html) {
1314
+ return html.replace(/<script[^>]*>[\s\S]*?<\/script>/gi, "").replace(/<style[^>]*>[\s\S]*?<\/style>/gi, "").replace(/<[^>]+>/g, " ").replace(/\s+/g, " ").trim();
1315
+ }
1316
+ isAvailable() {
1317
+ return true;
1318
+ }
1319
+ };
1320
+ var httpEngine = new HttpEngine();
1321
+
1322
+ // src/engines/tlsclient/index.ts
1323
+ import { gotScraping } from "got-scraping";
1324
+ var JS_REQUIRED_PATTERNS = [
1325
+ // Cloudflare JS challenge
1326
+ "cf-browser-verification",
1327
+ "challenge-platform",
1328
+ "_cf_chl_tk",
1329
+ "/cdn-cgi/challenge-platform/",
1330
+ // Generic JS requirements
1331
+ "Enable JavaScript",
1332
+ "JavaScript is required",
1333
+ "Please enable JavaScript",
1334
+ "requires JavaScript",
1335
+ "noscript"
1336
+ ];
1337
+ var BLOCKED_PATTERNS = [
1338
+ "Access denied",
1339
+ "Sorry, you have been blocked",
1340
+ "bot detected",
1341
+ "suspicious activity",
1342
+ "too many requests"
1343
+ ];
1344
+ var MIN_CONTENT_LENGTH2 = 100;
1345
+ var TlsClientEngine = class {
1346
+ config = ENGINE_CONFIGS.tlsclient;
1347
+ available = true;
1348
+ constructor() {
1349
+ try {
1350
+ if (!gotScraping) {
1351
+ this.available = false;
1352
+ }
1353
+ } catch {
1354
+ this.available = false;
1355
+ }
1356
+ }
1357
+ async scrape(meta) {
1358
+ if (!this.available) {
1359
+ throw new EngineUnavailableError("tlsclient", "got-scraping not available");
1360
+ }
1361
+ const startTime = Date.now();
1362
+ const { url, options, logger: logger4, abortSignal } = meta;
1363
+ try {
1364
+ const controller = new AbortController();
1365
+ const timeoutId = setTimeout(() => controller.abort(), this.config.maxTimeout);
1366
+ if (abortSignal) {
1367
+ abortSignal.addEventListener("abort", () => controller.abort(), { once: true });
1368
+ }
1369
+ logger4?.debug(`[tlsclient] Fetching ${url}`);
1370
+ const response = await gotScraping({
1371
+ url,
1372
+ timeout: {
1373
+ request: this.config.maxTimeout
1374
+ },
1375
+ headers: options.headers,
1376
+ followRedirect: true
1377
+ // got-scraping handles browser fingerprinting automatically
1378
+ // It uses header generators and proper TLS settings
1379
+ });
1380
+ clearTimeout(timeoutId);
1381
+ const duration = Date.now() - startTime;
1382
+ const html = response.body;
1383
+ logger4?.debug(`[tlsclient] Got response: ${response.statusCode} (${html.length} chars) in ${duration}ms`);
1384
+ if (response.statusCode >= 400) {
1385
+ throw new HttpError("tlsclient", response.statusCode, response.statusMessage);
1386
+ }
1387
+ const challengeType = this.detectJsRequired(html);
1388
+ if (challengeType) {
1389
+ logger4?.debug(`[tlsclient] JS required: ${challengeType}`);
1390
+ throw new ChallengeDetectedError("tlsclient", challengeType);
1391
+ }
1392
+ const blockedReason = this.detectBlocked(html);
1393
+ if (blockedReason) {
1394
+ logger4?.debug(`[tlsclient] Blocked: ${blockedReason}`);
1395
+ throw new ChallengeDetectedError("tlsclient", `blocked: ${blockedReason}`);
1396
+ }
1397
+ const textContent = this.extractText(html);
1398
+ if (textContent.length < MIN_CONTENT_LENGTH2) {
1399
+ logger4?.debug(`[tlsclient] Insufficient content: ${textContent.length} chars`);
1400
+ throw new InsufficientContentError("tlsclient", textContent.length, MIN_CONTENT_LENGTH2);
1401
+ }
1402
+ return {
1403
+ html,
1404
+ url: response.url,
1405
+ statusCode: response.statusCode,
1406
+ contentType: response.headers["content-type"],
1407
+ headers: response.headers,
1408
+ engine: "tlsclient",
1409
+ duration
1410
+ };
1411
+ } catch (error) {
1412
+ if (error instanceof ChallengeDetectedError || error instanceof InsufficientContentError || error instanceof HttpError || error instanceof EngineUnavailableError) {
1413
+ throw error;
1414
+ }
1415
+ if (error instanceof Error) {
1416
+ if (error.name === "TimeoutError" || error.message.includes("timeout")) {
1417
+ throw new EngineTimeoutError("tlsclient", this.config.maxTimeout);
1418
+ }
1419
+ if (error.name === "AbortError") {
1420
+ throw new EngineTimeoutError("tlsclient", this.config.maxTimeout);
1421
+ }
1422
+ throw new EngineError("tlsclient", error.message, { cause: error });
1423
+ }
1424
+ throw new EngineError("tlsclient", String(error));
1425
+ }
1426
+ }
1427
+ /**
1428
+ * Detect patterns that require JS execution
1429
+ */
1430
+ detectJsRequired(html) {
1431
+ const htmlLower = html.toLowerCase();
1432
+ for (const pattern of JS_REQUIRED_PATTERNS) {
1433
+ if (htmlLower.includes(pattern.toLowerCase())) {
1434
+ if (pattern.includes("cf") || pattern.includes("cloudflare")) {
1435
+ return "cloudflare-js";
1436
+ }
1437
+ return "js-required";
1438
+ }
1439
+ }
1440
+ return null;
1441
+ }
1442
+ /**
1443
+ * Detect blocked/denied patterns
1444
+ */
1445
+ detectBlocked(html) {
1446
+ const htmlLower = html.toLowerCase();
1447
+ for (const pattern of BLOCKED_PATTERNS) {
1448
+ if (htmlLower.includes(pattern.toLowerCase())) {
1449
+ return pattern;
1450
+ }
1451
+ }
1452
+ return null;
1453
+ }
1454
+ /**
1455
+ * Extract visible text from HTML
1456
+ */
1457
+ extractText(html) {
1458
+ return html.replace(/<script[^>]*>[\s\S]*?<\/script>/gi, "").replace(/<style[^>]*>[\s\S]*?<\/style>/gi, "").replace(/<[^>]+>/g, " ").replace(/\s+/g, " ").trim();
1459
+ }
1460
+ isAvailable() {
1461
+ return this.available;
1462
+ }
1463
+ };
1464
+ var tlsClientEngine = new TlsClientEngine();
1465
+
1466
+ // src/cloudflare/detector.ts
1467
+ var CLOUDFLARE_CHALLENGE_SELECTORS = [
1468
+ "#challenge-running",
1469
+ "#challenge-stage",
1470
+ "#challenge-form",
1471
+ ".cf-browser-verification",
1472
+ "#cf-wrapper",
1473
+ "#cf-hcaptcha-container",
1474
+ "#turnstile-wrapper"
1475
+ ];
1476
+ var CLOUDFLARE_TEXT_PATTERNS = [
1477
+ "checking if the site connection is secure",
1478
+ "this process is automatic. your browser will redirect",
1479
+ "ray id:",
1480
+ "performance & security by cloudflare"
1481
+ ];
1482
+ var CLOUDFLARE_INFRA_PATTERNS2 = [
1483
+ "/cdn-cgi/",
1484
+ "cloudflare",
1485
+ "__cf_bm",
1486
+ "cf-ray"
1487
+ ];
1488
+ var CLOUDFLARE_BLOCKED_PATTERNS = [
1489
+ "sorry, you have been blocked",
1490
+ "ray id:"
1491
+ ];
1492
+ async function detectChallenge(hero) {
1493
+ const signals = [];
1494
+ let type = "none";
1495
+ let hasCloudflareInfra = false;
1496
+ let hasChallengeIndicator = false;
1497
+ try {
1498
+ if (!hero.document) {
1499
+ return {
1500
+ isChallenge: false,
1501
+ type: "none",
1502
+ confidence: 0,
1503
+ signals: ["No document available"]
1504
+ };
1505
+ }
1506
+ const html = await hero.document.documentElement.outerHTML;
1507
+ const htmlLower = html.toLowerCase();
1508
+ for (const pattern of CLOUDFLARE_INFRA_PATTERNS2) {
1509
+ if (htmlLower.includes(pattern)) {
1510
+ hasCloudflareInfra = true;
1511
+ signals.push(`Cloudflare infra: "${pattern}"`);
1512
+ break;
1513
+ }
1514
+ }
1515
+ if (!hasCloudflareInfra) {
1516
+ return {
1517
+ isChallenge: false,
1518
+ type: "none",
1519
+ confidence: 0,
1520
+ signals: ["No Cloudflare infrastructure detected"]
1521
+ };
1522
+ }
1523
+ for (const selector of CLOUDFLARE_CHALLENGE_SELECTORS) {
1325
1524
  try {
1326
- const result = await this.scrapeSingleUrl(url, index);
1327
- if (result) {
1328
- return { result };
1525
+ const element = await hero.document.querySelector(selector);
1526
+ if (element) {
1527
+ hasChallengeIndicator = true;
1528
+ signals.push(`Challenge element: ${selector}`);
1529
+ type = "js_challenge";
1530
+ }
1531
+ } catch {
1532
+ }
1533
+ }
1534
+ for (const pattern of CLOUDFLARE_TEXT_PATTERNS) {
1535
+ if (htmlLower.includes(pattern)) {
1536
+ hasChallengeIndicator = true;
1537
+ signals.push(`Challenge text: "${pattern}"`);
1538
+ type = type === "none" ? "js_challenge" : type;
1539
+ }
1540
+ }
1541
+ if (htmlLower.includes("waiting for") && htmlLower.includes("to respond")) {
1542
+ hasChallengeIndicator = true;
1543
+ signals.push('Challenge text: "waiting for...to respond"');
1544
+ type = type === "none" ? "js_challenge" : type;
1545
+ }
1546
+ const hasBlocked = CLOUDFLARE_BLOCKED_PATTERNS.every((p) => htmlLower.includes(p));
1547
+ if (hasBlocked) {
1548
+ hasChallengeIndicator = true;
1549
+ signals.push("Cloudflare block page detected");
1550
+ type = "blocked";
1551
+ }
1552
+ const isChallenge = hasCloudflareInfra && hasChallengeIndicator;
1553
+ const confidence = isChallenge ? 100 : 0;
1554
+ return {
1555
+ isChallenge,
1556
+ type: isChallenge ? type : "none",
1557
+ confidence,
1558
+ signals
1559
+ };
1560
+ } catch (error) {
1561
+ return {
1562
+ isChallenge: false,
1563
+ type: "none",
1564
+ confidence: 0,
1565
+ signals: [`Error during detection: ${error.message}`]
1566
+ };
1567
+ }
1568
+ }
1569
+ async function isChallengePage(hero) {
1570
+ const detection = await detectChallenge(hero);
1571
+ return detection.isChallenge;
1572
+ }
1573
+
1574
+ // src/cloudflare/handler.ts
1575
+ async function waitForChallengeResolution(hero, options) {
1576
+ const { maxWaitMs = 45e3, pollIntervalMs = 500, verbose = false, initialUrl } = options;
1577
+ const startTime = Date.now();
1578
+ const log = (msg) => verbose && console.log(` ${msg}`);
1579
+ while (Date.now() - startTime < maxWaitMs) {
1580
+ const elapsed = Date.now() - startTime;
1581
+ try {
1582
+ const currentUrl = await hero.url;
1583
+ if (currentUrl !== initialUrl) {
1584
+ log(`\u2713 URL changed: ${initialUrl} \u2192 ${currentUrl}`);
1585
+ log(` Waiting for new page to load...`);
1586
+ try {
1587
+ await hero.waitForLoad("DomContentLoaded", { timeoutMs: 3e4 });
1588
+ log(` DOMContentLoaded`);
1589
+ } catch {
1590
+ log(` DOMContentLoaded timeout, continuing...`);
1591
+ }
1592
+ await hero.waitForPaintingStable().catch(() => {
1593
+ });
1594
+ log(` Page stabilized`);
1595
+ return { resolved: true, method: "url_redirect", waitedMs: elapsed };
1596
+ }
1597
+ } catch {
1598
+ }
1599
+ const detection = await detectChallenge(hero);
1600
+ if (!detection.isChallenge) {
1601
+ log(`\u2713 Challenge signals cleared (confidence dropped to ${detection.confidence})`);
1602
+ log(` Waiting for page to load...`);
1603
+ try {
1604
+ await hero.waitForLoad("DomContentLoaded", { timeoutMs: 3e4 });
1605
+ log(` DOMContentLoaded`);
1606
+ } catch {
1607
+ log(` DOMContentLoaded timeout, continuing...`);
1608
+ }
1609
+ await hero.waitForPaintingStable().catch(() => {
1610
+ });
1611
+ log(` Page stabilized`);
1612
+ return { resolved: true, method: "signals_cleared", waitedMs: elapsed };
1613
+ }
1614
+ log(
1615
+ `\u23F3 ${(elapsed / 1e3).toFixed(1)}s - Still challenge (confidence: ${detection.confidence})`
1616
+ );
1617
+ await new Promise((resolve) => setTimeout(resolve, pollIntervalMs));
1618
+ }
1619
+ return {
1620
+ resolved: false,
1621
+ method: "timeout",
1622
+ waitedMs: Date.now() - startTime
1623
+ };
1624
+ }
1625
+ async function waitForSelector(hero, selector, maxWaitMs, verbose = false) {
1626
+ const startTime = Date.now();
1627
+ const log = (msg) => verbose && console.log(` ${msg}`);
1628
+ log(`Waiting for selector: "${selector}"`);
1629
+ while (Date.now() - startTime < maxWaitMs) {
1630
+ try {
1631
+ const element = await hero.document.querySelector(selector);
1632
+ if (element) {
1633
+ const elapsed = Date.now() - startTime;
1634
+ log(`\u2713 Selector found after ${(elapsed / 1e3).toFixed(1)}s`);
1635
+ return { found: true, waitedMs: elapsed };
1636
+ }
1637
+ } catch {
1638
+ }
1639
+ await new Promise((resolve) => setTimeout(resolve, 300));
1640
+ }
1641
+ log(`\u2717 Selector not found within timeout`);
1642
+ return { found: false, waitedMs: Date.now() - startTime };
1643
+ }
1644
+ async function handleChallenge(hero, options = {}) {
1645
+ const initialUrl = await hero.url;
1646
+ const detection = await detectChallenge(hero);
1647
+ if (!detection.isChallenge) {
1648
+ return { resolved: true, method: "signals_cleared", waitedMs: 0 };
1649
+ }
1650
+ return waitForChallengeResolution(hero, {
1651
+ ...options,
1652
+ initialUrl
1653
+ });
1654
+ }
1655
+
1656
+ // src/engines/hero/index.ts
1657
+ var MIN_CONTENT_LENGTH3 = 100;
1658
+ var HeroEngine = class {
1659
+ config = ENGINE_CONFIGS.hero;
1660
+ async scrape(meta) {
1661
+ const startTime = Date.now();
1662
+ const { url, options, logger: logger4, abortSignal } = meta;
1663
+ const pool = options.pool;
1664
+ if (!pool) {
1665
+ throw new EngineUnavailableError("hero", "Browser pool not available");
1666
+ }
1667
+ if (abortSignal?.aborted) {
1668
+ throw new EngineTimeoutError("hero", 0);
1669
+ }
1670
+ logger4?.debug(`[hero] Starting browser scrape of ${url}`);
1671
+ try {
1672
+ const result = await pool.withBrowser(async (hero) => {
1673
+ let aborted = false;
1674
+ if (abortSignal) {
1675
+ abortSignal.addEventListener("abort", () => {
1676
+ aborted = true;
1677
+ }, { once: true });
1329
1678
  }
1330
- lastError = `Failed to scrape ${url}: No content returned`;
1331
- } catch (error) {
1332
- lastError = error.message;
1333
- if (attempt < maxRetries) {
1334
- const delay = Math.pow(2, attempt) * 1e3;
1335
- this.logger.warn(`Retry ${attempt + 1}/${maxRetries} for ${url} in ${delay}ms`);
1336
- await new Promise((resolve) => setTimeout(resolve, delay));
1679
+ const timeoutMs = options.timeoutMs || this.config.maxTimeout;
1680
+ await hero.goto(url, { timeoutMs });
1681
+ if (aborted) {
1682
+ throw new EngineTimeoutError("hero", Date.now() - startTime);
1683
+ }
1684
+ try {
1685
+ await hero.waitForLoad("DomContentLoaded", { timeoutMs });
1686
+ } catch {
1687
+ }
1688
+ await hero.waitForPaintingStable();
1689
+ if (aborted) {
1690
+ throw new EngineTimeoutError("hero", Date.now() - startTime);
1691
+ }
1692
+ const initialUrl = await hero.url;
1693
+ const detection = await detectChallenge(hero);
1694
+ if (detection.isChallenge) {
1695
+ logger4?.debug(`[hero] Challenge detected: ${detection.type}`);
1696
+ if (detection.type === "blocked") {
1697
+ throw new ChallengeDetectedError("hero", "blocked");
1698
+ }
1699
+ const resolution = await waitForChallengeResolution(hero, {
1700
+ maxWaitMs: 45e3,
1701
+ pollIntervalMs: 500,
1702
+ verbose: options.verbose,
1703
+ initialUrl
1704
+ });
1705
+ if (!resolution.resolved) {
1706
+ throw new ChallengeDetectedError("hero", `unresolved: ${detection.type}`);
1707
+ }
1708
+ logger4?.debug(`[hero] Challenge resolved via ${resolution.method} in ${resolution.waitedMs}ms`);
1709
+ }
1710
+ if (aborted) {
1711
+ throw new EngineTimeoutError("hero", Date.now() - startTime);
1712
+ }
1713
+ await this.waitForFinalPage(hero, url, logger4);
1714
+ if (aborted) {
1715
+ throw new EngineTimeoutError("hero", Date.now() - startTime);
1716
+ }
1717
+ if (options.waitForSelector) {
1718
+ try {
1719
+ await hero.waitForElement(hero.document.querySelector(options.waitForSelector), {
1720
+ timeoutMs
1721
+ });
1722
+ } catch {
1723
+ logger4?.debug(`[hero] Selector not found: ${options.waitForSelector}`);
1724
+ }
1337
1725
  }
1726
+ const html = await hero.document.documentElement.outerHTML;
1727
+ const finalUrl = await hero.url;
1728
+ const textContent = this.extractText(html);
1729
+ if (textContent.length < MIN_CONTENT_LENGTH3) {
1730
+ logger4?.debug(`[hero] Insufficient content: ${textContent.length} chars`);
1731
+ throw new InsufficientContentError("hero", textContent.length, MIN_CONTENT_LENGTH3);
1732
+ }
1733
+ const duration = Date.now() - startTime;
1734
+ logger4?.debug(`[hero] Success: ${html.length} chars in ${duration}ms`);
1735
+ return {
1736
+ html,
1737
+ url: finalUrl,
1738
+ statusCode: 200,
1739
+ // Hero doesn't expose status code directly
1740
+ engine: "hero",
1741
+ duration
1742
+ };
1743
+ });
1744
+ return result;
1745
+ } catch (error) {
1746
+ if (error instanceof ChallengeDetectedError || error instanceof InsufficientContentError || error instanceof EngineTimeoutError || error instanceof EngineUnavailableError) {
1747
+ throw error;
1338
1748
  }
1749
+ if (error instanceof Error) {
1750
+ if (error.name === "TimeoutError" || error.message.includes("timeout")) {
1751
+ throw new EngineTimeoutError("hero", this.config.maxTimeout);
1752
+ }
1753
+ if (error.message.includes("Navigation") || error.message.includes("ERR_")) {
1754
+ throw new EngineError("hero", `Navigation failed: ${error.message}`, { cause: error });
1755
+ }
1756
+ throw new EngineError("hero", error.message, { cause: error });
1757
+ }
1758
+ throw new EngineError("hero", String(error));
1339
1759
  }
1340
- this.logger.error(`Failed to scrape ${url} after ${maxRetries + 1} attempts: ${lastError}`);
1341
- return { result: null, error: lastError };
1342
1760
  }
1343
1761
  /**
1344
1762
  * Wait for the final page to load after any Cloudflare redirects
1345
- * Cloudflare often does silent redirects even when bypassed, we need to ensure
1346
- * we're on the actual content page before scraping.
1347
1763
  */
1348
- async waitForFinalPage(hero, originalUrl, verbose) {
1764
+ async waitForFinalPage(hero, originalUrl, logger4) {
1349
1765
  const maxWaitMs = 15e3;
1350
1766
  const startTime = Date.now();
1351
- const log = (msg) => verbose && this.logger.info(msg);
1352
1767
  try {
1353
1768
  await hero.waitForLoad("AllContentLoaded", { timeoutMs: maxWaitMs });
1354
1769
  } catch {
@@ -1357,7 +1772,7 @@ var Scraper = class {
1357
1772
  const normalizeUrl2 = (url) => url.replace(/\/+$/, "");
1358
1773
  const urlChanged = normalizeUrl2(currentUrl) !== normalizeUrl2(originalUrl);
1359
1774
  if (urlChanged || currentUrl.includes("__cf_chl")) {
1360
- log(`Cloudflare redirect detected: ${originalUrl} \u2192 ${currentUrl}`);
1775
+ logger4?.debug(`[hero] Cloudflare redirect detected: ${originalUrl} \u2192 ${currentUrl}`);
1361
1776
  let lastUrl = currentUrl;
1362
1777
  let stableCount = 0;
1363
1778
  while (Date.now() - startTime < maxWaitMs) {
@@ -1372,7 +1787,7 @@ var Scraper = class {
1372
1787
  } else {
1373
1788
  stableCount = 0;
1374
1789
  lastUrl = currentUrl;
1375
- log(`URL changed to: ${currentUrl}`);
1790
+ logger4?.debug(`[hero] URL changed to: ${currentUrl}`);
1376
1791
  }
1377
1792
  } catch {
1378
1793
  }
@@ -1386,7 +1801,223 @@ var Scraper = class {
1386
1801
  await new Promise((resolve) => setTimeout(resolve, 2e3));
1387
1802
  }
1388
1803
  /**
1389
- * Scrape a single URL
1804
+ * Extract visible text from HTML
1805
+ */
1806
+ extractText(html) {
1807
+ return html.replace(/<script[^>]*>[\s\S]*?<\/script>/gi, "").replace(/<style[^>]*>[\s\S]*?<\/style>/gi, "").replace(/<[^>]+>/g, " ").replace(/\s+/g, " ").trim();
1808
+ }
1809
+ isAvailable() {
1810
+ return true;
1811
+ }
1812
+ };
1813
+ var heroEngine = new HeroEngine();
1814
+
1815
+ // src/engines/orchestrator.ts
1816
+ var ENGINE_REGISTRY = {
1817
+ http: httpEngine,
1818
+ tlsclient: tlsClientEngine,
1819
+ hero: heroEngine
1820
+ };
1821
+ var EngineOrchestrator = class {
1822
+ options;
1823
+ engines;
1824
+ engineOrder;
1825
+ constructor(options = {}) {
1826
+ this.options = options;
1827
+ this.engineOrder = this.resolveEngineOrder();
1828
+ this.engines = this.engineOrder.map((name) => ENGINE_REGISTRY[name]).filter((engine) => engine.isAvailable());
1829
+ }
1830
+ /**
1831
+ * Resolve the engine order based on options
1832
+ */
1833
+ resolveEngineOrder() {
1834
+ if (this.options.forceEngine) {
1835
+ return [this.options.forceEngine];
1836
+ }
1837
+ let order = this.options.engines || [...DEFAULT_ENGINE_ORDER];
1838
+ if (this.options.skipEngines) {
1839
+ order = order.filter((e) => !this.options.skipEngines.includes(e));
1840
+ }
1841
+ return order;
1842
+ }
1843
+ /**
1844
+ * Get available engines
1845
+ */
1846
+ getAvailableEngines() {
1847
+ return this.engines.map((e) => e.config.name);
1848
+ }
1849
+ /**
1850
+ * Scrape a URL using the engine cascade
1851
+ *
1852
+ * @param meta - Engine metadata (url, options, logger, abortSignal)
1853
+ * @returns Scrape result with engine metadata
1854
+ * @throws AllEnginesFailedError if all engines fail
1855
+ */
1856
+ async scrape(meta) {
1857
+ const attemptedEngines = [];
1858
+ const engineErrors = /* @__PURE__ */ new Map();
1859
+ const logger4 = meta.logger || this.options.logger;
1860
+ const verbose = this.options.verbose || meta.options.verbose;
1861
+ if (this.engines.length === 0) {
1862
+ throw new AllEnginesFailedError([], engineErrors);
1863
+ }
1864
+ const log = (msg) => {
1865
+ if (verbose) {
1866
+ logger4?.info(msg);
1867
+ } else {
1868
+ logger4?.debug(msg);
1869
+ }
1870
+ };
1871
+ log(`[orchestrator] Starting scrape of ${meta.url} with engines: ${this.engineOrder.join(" \u2192 ")}`);
1872
+ for (const engine of this.engines) {
1873
+ const engineName = engine.config.name;
1874
+ attemptedEngines.push(engineName);
1875
+ try {
1876
+ log(`[orchestrator] Trying ${engineName} engine...`);
1877
+ const controller = new AbortController();
1878
+ const timeoutId = setTimeout(() => controller.abort(), engine.config.maxTimeout);
1879
+ if (meta.abortSignal) {
1880
+ meta.abortSignal.addEventListener("abort", () => controller.abort(), { once: true });
1881
+ }
1882
+ try {
1883
+ const result = await engine.scrape({
1884
+ ...meta,
1885
+ abortSignal: controller.signal
1886
+ });
1887
+ clearTimeout(timeoutId);
1888
+ log(`[orchestrator] \u2713 ${engineName} succeeded in ${result.duration}ms`);
1889
+ return {
1890
+ ...result,
1891
+ attemptedEngines,
1892
+ engineErrors
1893
+ };
1894
+ } finally {
1895
+ clearTimeout(timeoutId);
1896
+ }
1897
+ } catch (error) {
1898
+ const err = error instanceof Error ? error : new Error(String(error));
1899
+ engineErrors.set(engineName, err);
1900
+ if (error instanceof ChallengeDetectedError) {
1901
+ log(`[orchestrator] ${engineName} detected challenge: ${error.challengeType}`);
1902
+ } else if (error instanceof InsufficientContentError) {
1903
+ log(`[orchestrator] ${engineName} insufficient content: ${error.contentLength} chars`);
1904
+ } else if (error instanceof HttpError) {
1905
+ log(`[orchestrator] ${engineName} HTTP error: ${error.statusCode}`);
1906
+ } else if (error instanceof EngineTimeoutError) {
1907
+ log(`[orchestrator] ${engineName} timed out after ${error.timeoutMs}ms`);
1908
+ } else if (error instanceof EngineUnavailableError) {
1909
+ log(`[orchestrator] ${engineName} unavailable: ${err.message}`);
1910
+ } else {
1911
+ log(`[orchestrator] ${engineName} failed: ${err.message}`);
1912
+ }
1913
+ if (!this.shouldRetry(error)) {
1914
+ log(`[orchestrator] Non-retryable error, stopping cascade`);
1915
+ break;
1916
+ }
1917
+ log(`[orchestrator] Falling back to next engine...`);
1918
+ }
1919
+ }
1920
+ log(`[orchestrator] All engines failed for ${meta.url}`);
1921
+ throw new AllEnginesFailedError(attemptedEngines, engineErrors);
1922
+ }
1923
+ /**
1924
+ * Determine if we should retry with next engine
1925
+ */
1926
+ shouldRetry(error) {
1927
+ if (error instanceof ChallengeDetectedError || error instanceof InsufficientContentError || error instanceof EngineTimeoutError) {
1928
+ return true;
1929
+ }
1930
+ if (error instanceof HttpError) {
1931
+ return error.statusCode === 403 || error.statusCode === 429 || error.statusCode >= 500;
1932
+ }
1933
+ if (error instanceof EngineUnavailableError) {
1934
+ return true;
1935
+ }
1936
+ if (error instanceof EngineError) {
1937
+ return error.retryable;
1938
+ }
1939
+ return true;
1940
+ }
1941
+ };
1942
+
1943
+ // src/scraper.ts
1944
+ var Scraper = class {
1945
+ options;
1946
+ logger = createLogger("scraper");
1947
+ robotsCache = /* @__PURE__ */ new Map();
1948
+ constructor(options) {
1949
+ this.options = {
1950
+ ...DEFAULT_OPTIONS,
1951
+ ...options
1952
+ };
1953
+ }
1954
+ /**
1955
+ * Get robots.txt rules for a URL, cached per domain
1956
+ */
1957
+ async getRobotsRules(url) {
1958
+ const origin = new URL(url).origin;
1959
+ if (!this.robotsCache.has(origin)) {
1960
+ const rules = await fetchRobotsTxt(origin);
1961
+ this.robotsCache.set(origin, rules);
1962
+ }
1963
+ return this.robotsCache.get(origin) ?? null;
1964
+ }
1965
+ /**
1966
+ * Scrape all URLs
1967
+ *
1968
+ * @returns Scrape result with pages and metadata
1969
+ */
1970
+ async scrape() {
1971
+ const startTime = Date.now();
1972
+ const results = await this.scrapeWithConcurrency();
1973
+ return this.buildScrapeResult(results, startTime);
1974
+ }
1975
+ /**
1976
+ * Scrape URLs with concurrency control
1977
+ */
1978
+ async scrapeWithConcurrency() {
1979
+ const limit = pLimit(this.options.batchConcurrency || 1);
1980
+ const tasks = this.options.urls.map(
1981
+ (url, index) => limit(() => this.scrapeSingleUrlWithRetry(url, index))
1982
+ );
1983
+ const batchPromise = Promise.all(tasks);
1984
+ if (this.options.batchTimeoutMs && this.options.batchTimeoutMs > 0) {
1985
+ const timeoutPromise = new Promise((_, reject) => {
1986
+ setTimeout(() => {
1987
+ reject(new Error(`Batch operation timed out after ${this.options.batchTimeoutMs}ms`));
1988
+ }, this.options.batchTimeoutMs);
1989
+ });
1990
+ return Promise.race([batchPromise, timeoutPromise]);
1991
+ }
1992
+ return batchPromise;
1993
+ }
1994
+ /**
1995
+ * Scrape a single URL with retry logic
1996
+ */
1997
+ async scrapeSingleUrlWithRetry(url, index) {
1998
+ const maxRetries = this.options.maxRetries || 2;
1999
+ let lastError;
2000
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
2001
+ try {
2002
+ const result = await this.scrapeSingleUrl(url, index);
2003
+ if (result) {
2004
+ return { result };
2005
+ }
2006
+ lastError = `Failed to scrape ${url}: No content returned`;
2007
+ } catch (error) {
2008
+ lastError = error.message;
2009
+ if (attempt < maxRetries) {
2010
+ const delay = Math.pow(2, attempt) * 1e3;
2011
+ this.logger.warn(`Retry ${attempt + 1}/${maxRetries} for ${url} in ${delay}ms`);
2012
+ await new Promise((resolve) => setTimeout(resolve, delay));
2013
+ }
2014
+ }
2015
+ }
2016
+ this.logger.error(`Failed to scrape ${url} after ${maxRetries + 1} attempts: ${lastError}`);
2017
+ return { result: null, error: lastError };
2018
+ }
2019
+ /**
2020
+ * Scrape a single URL using the engine orchestrator
1390
2021
  */
1391
2022
  async scrapeSingleUrl(url, index) {
1392
2023
  const startTime = Date.now();
@@ -1395,98 +2026,84 @@ var Scraper = class {
1395
2026
  throw new Error(`URL blocked by robots.txt: ${url}`);
1396
2027
  }
1397
2028
  try {
1398
- return await this.pool.withBrowser(async (hero) => {
1399
- await hero.goto(url, { timeoutMs: this.options.timeoutMs });
1400
- try {
1401
- await hero.waitForLoad("DomContentLoaded", { timeoutMs: this.options.timeoutMs });
1402
- } catch {
1403
- }
1404
- await hero.waitForPaintingStable();
1405
- const initialUrl = await hero.url;
1406
- const detection = await detectChallenge(hero);
1407
- if (detection.isChallenge) {
1408
- if (this.options.verbose) {
1409
- this.logger.info(`Challenge detected on ${url}: ${detection.type}`);
1410
- }
1411
- const result2 = await waitForChallengeResolution(hero, {
1412
- maxWaitMs: 45e3,
1413
- pollIntervalMs: 500,
1414
- verbose: this.options.verbose,
1415
- initialUrl
1416
- });
1417
- if (!result2.resolved) {
1418
- throw new Error(`Challenge not resolved: ${detection.type}`);
1419
- }
1420
- if (this.options.verbose) {
1421
- this.logger.info(`Challenge resolved via ${result2.method} in ${result2.waitedMs}ms`);
1422
- }
1423
- }
1424
- await this.waitForFinalPage(hero, url, this.options.verbose);
1425
- if (this.options.waitForSelector) {
1426
- try {
1427
- await hero.waitForElement(hero.document.querySelector(this.options.waitForSelector), {
1428
- timeoutMs: this.options.timeoutMs
1429
- });
1430
- } catch (error) {
1431
- this.logger.warn(`Selector not found: ${this.options.waitForSelector}`);
1432
- }
1433
- }
1434
- const html = await hero.document.documentElement.outerHTML;
1435
- const cleanedHtml = cleanContent(html, url, {
1436
- removeAds: this.options.removeAds,
1437
- removeBase64Images: this.options.removeBase64Images,
1438
- onlyMainContent: this.options.onlyMainContent,
1439
- includeTags: this.options.includeTags,
1440
- excludeTags: this.options.excludeTags
2029
+ const orchestrator = new EngineOrchestrator({
2030
+ engines: this.options.engines,
2031
+ skipEngines: this.options.skipEngines,
2032
+ forceEngine: this.options.forceEngine,
2033
+ logger: this.logger,
2034
+ verbose: this.options.verbose
2035
+ });
2036
+ const engineResult = await orchestrator.scrape({
2037
+ url,
2038
+ options: this.options,
2039
+ logger: this.logger
2040
+ });
2041
+ if (this.options.verbose) {
2042
+ this.logger.info(
2043
+ `[scraper] ${url} scraped with ${engineResult.engine} engine in ${engineResult.duration}ms (attempted: ${engineResult.attemptedEngines.join(" \u2192 ")})`
2044
+ );
2045
+ }
2046
+ const cleanedHtml = cleanContent(engineResult.html, engineResult.url, {
2047
+ removeAds: this.options.removeAds,
2048
+ removeBase64Images: this.options.removeBase64Images,
2049
+ onlyMainContent: this.options.onlyMainContent,
2050
+ includeTags: this.options.includeTags,
2051
+ excludeTags: this.options.excludeTags
2052
+ });
2053
+ const websiteMetadata = extractMetadata(cleanedHtml, engineResult.url);
2054
+ const duration = Date.now() - startTime;
2055
+ const markdown = this.options.formats.includes("markdown") ? htmlToMarkdown(cleanedHtml) : void 0;
2056
+ const htmlOutput = this.options.formats.includes("html") ? cleanedHtml : void 0;
2057
+ if (this.options.onProgress) {
2058
+ this.options.onProgress({
2059
+ completed: index + 1,
2060
+ total: this.options.urls.length,
2061
+ currentUrl: url
1441
2062
  });
1442
- const websiteMetadata = extractMetadata(cleanedHtml, url);
1443
- const duration = Date.now() - startTime;
1444
- const markdown = this.options.formats.includes("markdown") ? htmlToMarkdown(cleanedHtml) : void 0;
1445
- const htmlOutput = this.options.formats.includes("html") ? cleanedHtml : void 0;
1446
- if (this.options.onProgress) {
1447
- this.options.onProgress({
1448
- completed: index + 1,
1449
- total: this.options.urls.length,
1450
- currentUrl: url
1451
- });
1452
- }
1453
- let proxyMetadata;
1454
- if (this.options.proxy) {
1455
- const proxy = this.options.proxy;
1456
- if (proxy.url) {
1457
- try {
1458
- const proxyUrl = new URL(proxy.url);
1459
- proxyMetadata = {
1460
- host: proxyUrl.hostname,
1461
- port: parseInt(proxyUrl.port, 10) || 80,
1462
- country: proxy.country
1463
- };
1464
- } catch {
1465
- }
1466
- } else if (proxy.host && proxy.port) {
2063
+ }
2064
+ let proxyMetadata;
2065
+ if (this.options.proxy) {
2066
+ const proxy = this.options.proxy;
2067
+ if (proxy.url) {
2068
+ try {
2069
+ const proxyUrl = new URL(proxy.url);
1467
2070
  proxyMetadata = {
1468
- host: proxy.host,
1469
- port: proxy.port,
2071
+ host: proxyUrl.hostname,
2072
+ port: parseInt(proxyUrl.port, 10) || 80,
1470
2073
  country: proxy.country
1471
2074
  };
2075
+ } catch {
1472
2076
  }
2077
+ } else if (proxy.host && proxy.port) {
2078
+ proxyMetadata = {
2079
+ host: proxy.host,
2080
+ port: proxy.port,
2081
+ country: proxy.country
2082
+ };
1473
2083
  }
1474
- const result = {
1475
- markdown,
1476
- html: htmlOutput,
1477
- metadata: {
1478
- baseUrl: url,
1479
- totalPages: 1,
1480
- scrapedAt: (/* @__PURE__ */ new Date()).toISOString(),
1481
- duration,
1482
- website: websiteMetadata,
1483
- proxy: proxyMetadata
1484
- }
1485
- };
1486
- return result;
1487
- });
2084
+ }
2085
+ const result = {
2086
+ markdown,
2087
+ html: htmlOutput,
2088
+ metadata: {
2089
+ baseUrl: url,
2090
+ totalPages: 1,
2091
+ scrapedAt: (/* @__PURE__ */ new Date()).toISOString(),
2092
+ duration,
2093
+ website: websiteMetadata,
2094
+ proxy: proxyMetadata
2095
+ }
2096
+ };
2097
+ return result;
1488
2098
  } catch (error) {
1489
- this.logger.error(`Failed to scrape ${url}: ${error.message}`);
2099
+ if (error instanceof AllEnginesFailedError) {
2100
+ const engineSummary = error.attemptedEngines.map((e) => `${e}: ${error.errors.get(e)?.message || "unknown"}`).join("; ");
2101
+ this.logger.error(`Failed to scrape ${url}: All engines failed - ${engineSummary}`);
2102
+ } else if (error instanceof Error) {
2103
+ this.logger.error(`Failed to scrape ${url}: ${error.message}`);
2104
+ } else {
2105
+ this.logger.error(`Failed to scrape ${url}: ${String(error)}`);
2106
+ }
1490
2107
  if (this.options.onProgress) {
1491
2108
  this.options.onProgress({
1492
2109
  completed: index + 1,