-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.js
More file actions
1808 lines (1586 loc) · 52.9 KB
/
index.js
File metadata and controls
1808 lines (1586 loc) · 52.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { spawn, execSync } from 'child_process';
import fs from 'fs/promises';
import { existsSync, statSync } from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import { promises as fsPromises } from 'fs';
let PDFParse = null;
import browserPool from './browser-pool.js';
let puppeteer = null;
try {
puppeteer = await import('puppeteer');
puppeteer = puppeteer.default || puppeteer;
} catch (e) {
// Puppeteer is optional
}
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
/**
* BNCA Smart Scraper - Intelligent Web Scraping with Multi-level Fallback
*
* This class implements a sophisticated fallback system:
* 1. Direct Fetch - Fast HTML retrieval for simple sites
* 2. Lightpanda - Lightning-fast browser for static/SSR sites
* 3. Puppeteer - Full Chromium browser for complex JavaScript sites
*
* Performance: 10x+ faster than Firecrawl on average
*/
export class BNCASmartScraper {
constructor(options = {}) {
this.options = {
timeout: options.timeout || 10000,
userAgent: options.userAgent || 'Mozilla/5.0 (compatible; BNCA/1.0; +https://github.com/your-org/bnca)',
lightpandaPath: options.lightpandaPath || this.findLightpandaBinary(),
retries: options.retries || 2,
verbose: options.verbose || false,
...options
};
this.browser = null;
this.stats = {
directFetch: { attempts: 0, successes: 0 },
lightpanda: { attempts: 0, successes: 0 },
puppeteer: { attempts: 0, successes: 0 },
pdf: { attempts: 0, successes: 0 }
};
}
/**
* Ask AI a question about a URL
* Scrapes the URL and uses AI to answer the question
*
* @param {string} url - URL to analyze
* @param {string} question - Question to answer
* @param {object} options - Additional options
* @returns {Promise<object>} AI response with answer
*/
async askAI(url, question, options = {}) {
try {
// First scrape the content
const scrapeResult = await this.scrape(url, options);
if (!scrapeResult.success) {
return {
success: false,
error: `Failed to scrape URL: ${scrapeResult.error}`,
method: scrapeResult.method
};
}
// Check for OpenRouter/OpenAI API key
const openRouterKey = options.openRouterApiKey || this.options.openRouterApiKey || process.env.OPENROUTER_API_KEY;
const openAIKey = options.openAIApiKey || this.options.openAIApiKey || process.env.OPENAI_API_KEY;
// Priority: OpenRouter > OpenAI > Backend API > Local
if (openRouterKey) {
try {
const answer = await this.processWithOpenRouter(question, scrapeResult.content, openRouterKey, options);
return {
success: true,
answer,
method: scrapeResult.method,
scrapeTime: scrapeResult.stats.totalTime,
processing: 'openrouter'
};
} catch (error) {
this.log(' ⚠️ OpenRouter API call failed, falling back...');
}
}
if (openAIKey) {
try {
const answer = await this.processWithOpenAI(question, scrapeResult.content, openAIKey, options);
return {
success: true,
answer,
method: scrapeResult.method,
scrapeTime: scrapeResult.stats.totalTime,
processing: 'openai'
};
} catch (error) {
this.log(' ⚠️ OpenAI API call failed, falling back...');
}
}
// If BNCA API key is provided, use the backend API
if (this.options.apiKey) {
try {
const response = await fetch(`${this.options.apiUrl || 'https://bnca-api.fly.dev'}/aireply`, {
method: 'POST',
headers: {
'x-api-key': this.options.apiKey,
'Content-Type': 'application/json'
},
body: JSON.stringify({ url, question })
});
if (response.ok) {
const data = await response.json();
return {
success: true,
answer: data.answer,
method: scrapeResult.method,
scrapeTime: scrapeResult.stats.totalTime,
processing: 'backend'
};
}
} catch (error) {
this.log(' ⚠️ Backend API call failed, using local AI processing');
}
}
// Local AI processing fallback
const answer = this.processLocally(question, scrapeResult.content);
return {
success: true,
answer,
method: scrapeResult.method,
scrapeTime: scrapeResult.stats.totalTime,
processing: 'local'
};
} catch (error) {
return {
success: false,
error: error.message || 'AI processing failed'
};
}
}
/**
* Process with OpenRouter API
* @private
*/
async processWithOpenRouter(question, content, apiKey, options = {}) {
const parsedContent = typeof content === 'string' ? JSON.parse(content) : content;
const contentText = `
Title: ${parsedContent.title || 'Unknown'}
Content: ${parsedContent.content || parsedContent.bodyText || 'No content available'}
Meta Description: ${parsedContent.metaDescription || 'None'}
${parsedContent.headings?.length ? `\nHeadings:\n${parsedContent.headings.map(h => `- ${h.text || h}`).join('\n')}` : ''}
`.trim();
const response = await fetch('https://openrouter.ai/api/v1/chat/completions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${apiKey}`,
'HTTP-Referer': options.referer || 'https://github.com/monostate/node-scraper',
'X-Title': 'BNCA Node Scraper',
},
body: JSON.stringify({
model: options.model || 'meta-llama/llama-4-scout:free',
messages: [
{
role: 'system',
content: 'You are a helpful assistant that answers questions based on website content. Provide accurate, concise answers based only on the provided content.'
},
{
role: 'user',
content: `Based on the following website content, please answer this question: ${question}\n\nWebsite content:\n${contentText}`
}
],
temperature: options.temperature || 0.3,
max_tokens: options.maxTokens || 500,
}),
});
if (!response.ok) {
throw new Error(`OpenRouter API error: ${response.status}`);
}
const data = await response.json();
return data.choices[0]?.message?.content || 'No response from AI';
}
/**
* Process with OpenAI API
* @private
*/
async processWithOpenAI(question, content, apiKey, options = {}) {
const parsedContent = typeof content === 'string' ? JSON.parse(content) : content;
const contentText = `
Title: ${parsedContent.title || 'Unknown'}
Content: ${parsedContent.content || parsedContent.bodyText || 'No content available'}
Meta Description: ${parsedContent.metaDescription || 'None'}
${parsedContent.headings?.length ? `\nHeadings:\n${parsedContent.headings.map(h => `- ${h.text || h}`).join('\n')}` : ''}
`.trim();
const baseUrl = options.openAIBaseUrl || 'https://api.openai.com';
const response = await fetch(`${baseUrl}/v1/chat/completions`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${apiKey}`,
},
body: JSON.stringify({
model: options.model || 'gpt-3.5-turbo',
messages: [
{
role: 'system',
content: 'You are a helpful assistant that answers questions based on website content. Provide accurate, concise answers based only on the provided content.'
},
{
role: 'user',
content: `Based on the following website content, please answer this question: ${question}\n\nWebsite content:\n${contentText}`
}
],
temperature: options.temperature || 0.3,
max_tokens: options.maxTokens || 500,
}),
});
if (!response.ok) {
throw new Error(`OpenAI API error: ${response.status}`);
}
const data = await response.json();
return data.choices[0]?.message?.content || 'No response from AI';
}
/**
* Local AI processing (simple pattern matching)
* @private
*/
processLocally(question, content) {
const parsedContent = typeof content === 'string' ?
JSON.parse(content) : content;
const title = parsedContent.title || 'Unknown';
const text = parsedContent.content || parsedContent.bodyText || '';
const lowerQuestion = question.toLowerCase();
if (lowerQuestion.includes('title')) {
return `The page title is "${title}".`;
}
if (lowerQuestion.includes('about') || lowerQuestion.includes('what')) {
return `This page titled "${title}" contains: ${text.substring(0, 200)}...`;
}
if (lowerQuestion.includes('contact') || lowerQuestion.includes('email')) {
const emailMatch = text.match(/[\w.-]+@[\w.-]+\.\w+/);
return emailMatch ?
`Found contact: ${emailMatch[0]}` :
'No contact information found.';
}
return `Based on "${title}": ${text.substring(0, 150)}...`;
}
/**
* Main scraping method with intelligent fallback
*/
async scrape(url, options = {}) {
const startTime = Date.now();
const config = { ...this.options, ...options };
this.log(`🚀 Starting smart scrape for: ${url}`);
let result = null;
let method = 'unknown';
let lastError = null;
const fallbackChain = [];
// Check if a specific method is requested
const requestedMethod = config.method;
const isForced = requestedMethod && requestedMethod !== 'auto';
try {
// Check if URL is a PDF (by extension or content-type check)
const isPdfUrl = url.toLowerCase().endsWith('.pdf') ||
url.toLowerCase().includes('.pdf?') ||
url.toLowerCase().includes('/pdf/');
if (isPdfUrl) {
this.log(' 📄 PDF detected, using PDF parser...');
result = await this.tryPDFParse(url, config);
if (result.success) {
method = 'pdf';
this.log(' ✅ PDF parsing successful');
const totalTime = Date.now() - startTime;
return {
...result,
method,
performance: {
totalTime,
method
},
stats: this.getStats()
};
} else {
this.log(' ❌ PDF parsing failed');
lastError = result.error;
}
}
// Handle forced method requests
if (isForced) {
this.log(` 🎯 Method forced to: ${requestedMethod}`);
switch (requestedMethod) {
case 'direct':
this.log(' 🔄 Attempting direct fetch...');
result = await this.tryDirectFetch(url, config);
method = 'direct-fetch';
break;
case 'lightpanda':
this.log(' 🐼 Attempting Lightpanda...');
result = await this.tryLightpanda(url, config);
method = 'lightpanda';
break;
case 'puppeteer':
this.log(' 🔵 Attempting Puppeteer...');
result = await this.tryPuppeteer(url, config);
method = 'puppeteer';
break;
default:
return {
success: false,
error: `Invalid method: ${requestedMethod}. Valid methods are: auto, direct, lightpanda, puppeteer`,
method: 'error',
errorType: 'service_unavailable',
performance: {
totalTime: Date.now() - startTime
}
};
}
// For forced methods, return immediately with no fallback
if (!result.success) {
this.log(` ❌ ${requestedMethod} failed`);
return {
success: false,
error: result.error || `${requestedMethod} scraping failed`,
method,
errorType: this.categorizeError(result.error),
details: result.error,
performance: {
totalTime: Date.now() - startTime,
method
},
stats: this.getStats()
};
}
this.log(` ✅ ${requestedMethod} successful`);
const totalTime = Date.now() - startTime;
return {
...result,
method,
performance: {
totalTime,
method
},
stats: this.getStats()
};
}
// Step 1: Try direct fetch first (fastest)
this.log(' 🔄 Attempting direct fetch...');
fallbackChain.push('direct-fetch');
result = await this.tryDirectFetch(url, config);
if (result.success && !result.needsBrowser) {
method = 'direct-fetch';
this.log(' ✅ Direct fetch successful');
} else if (result.isPdf) {
// Direct fetch detected a PDF, try PDF parser
this.log(' 📄 Direct fetch detected PDF content, using PDF parser...');
result = await this.tryPDFParse(url, config);
if (result.success) {
method = 'pdf';
this.log(' ✅ PDF parsing successful');
const totalTime = Date.now() - startTime;
return {
...result,
method,
performance: {
totalTime,
method
},
stats: this.getStats()
};
} else {
this.log(' ❌ PDF parsing failed');
lastError = result.error;
}
} else {
this.log(result.needsBrowser ? ' ⚠️ Browser rendering required' : ' ❌ Direct fetch failed');
lastError = result.error;
// Step 2: Try Lightpanda (fast browser)
this.log(' 🐼 Attempting Lightpanda...');
fallbackChain.push('lightpanda');
result = await this.tryLightpanda(url, config);
if (result.success) {
method = 'lightpanda';
this.log(' ✅ Lightpanda successful');
} else {
this.log(' ❌ Lightpanda failed, falling back to Puppeteer');
lastError = result.error;
// Step 3: Fallback to Puppeteer (full browser)
this.log(' 🔵 Attempting Puppeteer...');
fallbackChain.push('puppeteer');
result = await this.tryPuppeteer(url, config);
if (result.success) {
method = 'puppeteer';
this.log(' ✅ Puppeteer successful');
} else {
method = 'failed';
this.log(' ❌ All methods failed');
lastError = result.error;
}
}
}
const totalTime = Date.now() - startTime;
return {
...result,
method,
performance: {
totalTime,
method
},
stats: this.getStats(),
// Only include fallbackChain in auto mode
...((!requestedMethod || requestedMethod === 'auto') && { fallbackChain })
};
} catch (error) {
return {
success: false,
method: 'error',
error: error.message,
performance: {
totalTime: Date.now() - startTime
}
};
}
}
/**
* Direct HTTP fetch - fastest method for simple sites
*/
async tryDirectFetch(url, config) {
this.stats.directFetch.attempts++;
try {
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), config.timeout);
const response = await fetch(url, {
headers: {
'User-Agent': config.userAgent,
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Language': 'en-US,en;q=0.5',
'Accept-Encoding': 'gzip, deflate',
'Connection': 'keep-alive',
'Upgrade-Insecure-Requests': '1'
},
signal: controller.signal
});
clearTimeout(timeoutId);
if (!response.ok) {
return {
success: false,
error: `Direct fetch failed: HTTP ${response.status}: ${response.statusText}`,
errorType: response.status === 404 ? 'service_unavailable' : 'network'
};
}
// Check if the response is actually a PDF
const contentType = response.headers.get('content-type') || '';
if (contentType.includes('application/pdf')) {
return {
success: false,
error: 'Content is PDF, should use PDF parser',
isPdf: true
};
}
// Get response as array buffer to check magic bytes
const buffer = await response.arrayBuffer();
const firstBytes = new Uint8Array(buffer.slice(0, 5));
const signature = Array.from(firstBytes).map(b => String.fromCharCode(b)).join('');
// Check for PDF magic bytes
if (signature.startsWith('%PDF')) {
return {
success: false,
error: 'Content is PDF (detected by magic bytes), should use PDF parser',
isPdf: true
};
}
// Convert buffer back to text for HTML processing
const html = new TextDecoder().decode(buffer);
// Intelligent browser detection
const needsBrowser = this.detectBrowserRequirement(html, url);
if (!needsBrowser) {
const content = this.extractContentFromHTML(html);
this.stats.directFetch.successes++;
return {
success: true,
needsBrowser: false,
content,
html,
size: html.length,
contentType: response.headers.get('content-type') || 'text/html'
};
} else {
return {
success: true,
needsBrowser: true,
html,
size: html.length,
browserIndicators: this.getBrowserIndicators(html)
};
}
} catch (error) {
const errorMsg = error.message || 'Unknown error';
return {
success: false,
error: `Direct fetch failed: ${errorMsg}`,
errorType: this.categorizeError(errorMsg)
};
}
}
/**
* Lightpanda browser - fast browser engine for static/SSR sites
*/
async tryLightpanda(url, config) {
this.stats.lightpanda.attempts++;
if (!this.options.lightpandaPath) {
return {
success: false,
error: 'Lightpanda scraping failed: Lightpanda binary not found. Please install Lightpanda or provide path.',
errorType: 'service_unavailable'
};
}
try {
// Check if binary exists
const stats = statSync(this.options.lightpandaPath);
if (!stats.isFile()) {
return {
success: false,
error: 'Lightpanda scraping failed: Lightpanda binary is not a file',
errorType: 'service_unavailable'
};
}
} catch {
return {
success: false,
error: 'Lightpanda scraping failed: Lightpanda binary not accessible',
errorType: 'service_unavailable'
};
}
return new Promise((resolve) => {
const format = config.lightpandaFormat || 'html';
const args = [
'fetch',
'--dump', format,
'--with_frames',
'--http_timeout', String(config.timeout),
url
];
const process = spawn(this.options.lightpandaPath, args, {
timeout: config.timeout + 2000 // Buffer above http_timeout
});
let output = '';
let errorOutput = '';
process.stdout.on('data', (data) => {
output += data.toString();
});
process.stderr.on('data', (data) => {
errorOutput += data.toString();
});
process.on('close', (code) => {
if (code === 0 && output.length > 0) {
// Markdown output is already clean text, no HTML extraction needed
const content = format === 'markdown'
? JSON.stringify({
title: output.match(/^#\s+(.+)$/m)?.[1] || '',
content: output,
extractedAt: new Date().toISOString()
}, null, 2)
: this.extractContentFromHTML(output);
this.stats.lightpanda.successes++;
resolve({
success: true,
content,
html: output,
size: output.length,
exitCode: code
});
} else {
const errorMsg = errorOutput || `Lightpanda exited with code ${code}`;
resolve({
success: false,
error: `Lightpanda scraping failed: ${errorMsg}`,
errorType: this.categorizeError(errorMsg),
exitCode: code
});
}
});
process.on('error', (error) => {
resolve({
success: false,
error: `Lightpanda scraping failed: ${error.message}`,
errorType: this.categorizeError(error.message)
});
});
});
}
/**
* Puppeteer browser - full Chromium for complex JavaScript sites
*/
async tryPuppeteer(url, config) {
this.stats.puppeteer.attempts++;
if (!puppeteer) {
return {
success: false,
error: 'Puppeteer scraping failed: Puppeteer is not installed. Please install puppeteer package.',
errorType: 'service_unavailable'
};
}
let browser = null;
let page = null;
try {
// Get browser from pool
browser = await browserPool.getBrowser();
page = await browser.newPage();
// Set user agent and viewport
await page.setUserAgent(config.userAgent);
await page.setViewport({ width: 1280, height: 720 });
// Block unnecessary resources for faster loading
await page.setRequestInterception(true);
page.on('request', (req) => {
const resourceType = req.resourceType();
if (['image', 'stylesheet', 'font', 'media'].includes(resourceType)) {
req.abort();
} else {
req.continue();
}
});
// Navigate with timeout
await page.goto(url, {
waitUntil: 'networkidle0',
timeout: config.timeout
});
// Extract content using browser APIs
const content = await page.evaluate(() => {
// Get basic page info
const title = document.title;
const metaDescription = document.querySelector('meta[name="description"]')?.content || '';
const canonical = document.querySelector('link[rel="canonical"]')?.href || '';
// Extract headings
const headings = Array.from(document.querySelectorAll('h1, h2, h3, h4, h5, h6'))
.map(h => ({
level: h.tagName.toLowerCase(),
text: h.textContent.trim()
}))
.filter(h => h.text.length > 0)
.slice(0, 20);
// Extract paragraphs
const paragraphs = Array.from(document.querySelectorAll('p'))
.map(p => p.textContent.trim())
.filter(text => text.length > 20)
.slice(0, 10);
// Extract links
const links = Array.from(document.querySelectorAll('a[href]'))
.map(a => ({
text: a.textContent.trim(),
href: a.href
}))
.filter(link => link.text.length > 0)
.slice(0, 15);
// Extract JSON-LD structured data
const structuredData = Array.from(document.querySelectorAll('script[type=\"application/ld+json\"]'))
.map(script => {
try {
return JSON.parse(script.textContent);
} catch {
return null;
}
})
.filter(data => data !== null);
// Get page text content (truncated)
const bodyText = document.body.textContent
.replace(/\\s+/g, ' ')
.trim()
.substring(0, 3000);
return {
title,
metaDescription,
canonical,
headings,
paragraphs,
links,
structuredData,
bodyText,
url: window.location.href
};
});
this.stats.puppeteer.successes++;
return {
success: true,
content: JSON.stringify(content, null, 2),
size: JSON.stringify(content).length
};
} catch (error) {
const errorMsg = error.message || 'Unknown error';
return {
success: false,
error: `Puppeteer scraping failed: ${errorMsg}`,
errorType: this.categorizeError(errorMsg)
};
} finally {
// Always clean up page
if (page) {
try {
// Check if page is still connected before closing
if (!page.isClosed()) {
await page.close();
}
} catch (e) {
// Silently ignore protocol errors when page is already closed
if (!e.message.includes('Protocol error') && !e.message.includes('Target closed')) {
console.warn('Error closing page:', e.message);
}
}
}
// Release browser back to pool
if (browser) {
browserPool.releaseBrowser(browser);
}
}
}
/**
* PDF parsing method - handles PDF documents
*/
async tryPDFParse(url, config) {
this.stats.pdf.attempts++;
try {
// Download PDF with timeout
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), config.timeout);
const response = await fetch(url, {
headers: {
'User-Agent': config.userAgent,
'Accept': 'application/pdf,*/*'
},
signal: controller.signal
});
clearTimeout(timeoutId);
if (!response.ok) {
return {
success: false,
error: `HTTP ${response.status}: ${response.statusText}`
};
}
// Check content type (be lenient - accept various content types)
const contentType = response.headers.get('content-type') || '';
const acceptableTypes = ['pdf', 'octet-stream', 'binary', 'download'];
const isAcceptableType = acceptableTypes.some(type => contentType.includes(type));
if (!isAcceptableType && !url.toLowerCase().includes('.pdf')) {
return {
success: false,
error: `Not a PDF document: ${contentType}`
};
}
// Get PDF buffer
const arrayBuffer = await response.arrayBuffer();
const buffer = Buffer.from(arrayBuffer);
// Check size limit (20MB)
if (buffer.length > 20 * 1024 * 1024) {
return {
success: false,
error: 'PDF too large (max 20MB)'
};
}
// Lazy-load pdf-parse (pdfjs-dist requires DOMMatrix, only available in Node 22+)
if (!PDFParse) {
const mod = await import('pdf-parse');
PDFParse = mod.PDFParse;
}
const parser = new PDFParse({ data: new Uint8Array(buffer) });
await parser.load();
const textResult = await parser.getText();
const infoResult = await parser.getInfo();
parser.destroy();
// Extract structured content
const pdfInfo = infoResult.info || {};
const content = {
title: pdfInfo.Title || infoResult.outline?.[0]?.title || 'Untitled PDF',
author: pdfInfo.Author || '',
subject: pdfInfo.Subject || '',
keywords: pdfInfo.Keywords || '',
creator: pdfInfo.Creator || '',
producer: pdfInfo.Producer || '',
creationDate: pdfInfo.CreationDate || '',
modificationDate: pdfInfo.ModDate || '',
pages: textResult.total || 0,
text: textResult.text || '',
metadata: infoResult.metadata || null,
url: url
};
this.stats.pdf.successes++;
return {
success: true,
content: JSON.stringify(content, null, 2),
size: buffer.length,
contentType: 'application/pdf',
pages: content.pages
};
} catch (error) {
return {
success: false,
error: `PDF parsing error: ${error.message}`
};
}
}
/**
* Intelligent detection of browser requirement
*/
detectBrowserRequirement(html, url) {
// Whitelist simple sites that should always use direct fetch
const simpleSites = [
'example.com',
'httpbin.org',
'wikipedia.org',
'github.io',
'netlify.app',
'vercel.app'
];
if (simpleSites.some(site => url.includes(site))) {
return false; // Always use direct fetch for these
}
// Check for common SPA patterns (be more specific)
const spaIndicators = [
/<div[^>]*id=['"]?root['"]?[^>]*>\s*<\/div>/i,
/<div[^>]*id=['"]?app['"]?[^>]*>\s*<\/div>/i,
/<div[^>]*data-reactroot/i,
/window\.__NEXT_DATA__/i,
/window\.__NUXT__/i,
/_next\/static/i,
/__webpack_require__/i
];
// Check for protection systems (more specific patterns)
const protectionIndicators = [
/cloudflare.*challenge/i,
/cloudflare.*protection/i,
/ray id.*cloudflare/i,
/please enable javascript/i,
/you need to enable javascript/i,
/this site requires javascript/i,
/jscript.*required/i,
/security check.*cloudflare/i,
/attention required.*cloudflare/i
];
// Domain-based checks for known SPA sites
const domainIndicators = [
/instagram\.com/i,
/twitter\.com/i,
/facebook\.com/i,
/linkedin\.com/i,
/maps\.google/i,
/gmail\.com/i,
/youtube\.com/i
];
// Check if it's clearly a SPA or protected site
const hasSpaIndicators = spaIndicators.some(pattern => pattern.test(html));
const hasProtection = protectionIndicators.some(pattern => pattern.test(html));
const isKnownSpa = domainIndicators.some(pattern => pattern.test(url));
// Check for minimal content BUT only if we also have SPA indicators
const bodyContent = html.match(/<body[^>]*>([\s\S]*)<\/body>/i)?.[1] || '';
const textContent = bodyContent
.replace(/<script[\s\S]*?<\/script>/gi, '')
.replace(/<style[\s\S]*?<\/style>/gi, '')
.replace(/<[^>]+>/g, ' ')
.replace(/\s+/g, ' ')
.trim();
const hasMinimalContent = textContent.length < 200; // More conservative threshold
const isLikelySpa = hasMinimalContent && hasSpaIndicators;
// Only require browser if we have strong indicators
const needsBrowser = hasProtection || isKnownSpa || isLikelySpa;
return needsBrowser;
}
/**
* Get browser requirement indicators for debugging
*/
getBrowserIndicators(html) {
const indicators = [];
if (/<div[^>]*id=['"]?root['"]?[^>]*>\s*<\/div>/i.test(html)) {
indicators.push('React root div detected');
}
if (/window\.__NEXT_DATA__/i.test(html)) {
indicators.push('Next.js data detected');
}
if (/cloudflare.*challenge/i.test(html)) {
indicators.push('Cloudflare challenge detected');
}
if (/cloudflare.*protection/i.test(html)) {