Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 21x 21x 21x 21x 21x 21x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x | /**
* Web Extraction Activities v4.0 - Single Activity Pattern (like File Extractor)
* One activity that handles the complete scraping lifecycle
*/
const { chromium } = require('playwright');
const { S3Client, PutObjectCommand } = require('@aws-sdk/client-s3');
const { JSDOM } = require('jsdom');
const { Readability } = require('@mozilla/readability');
const TurndownService = require('turndown');
// Shared turndown instance for HTML to Markdown conversion
const turndownService = new TurndownService({
headingStyle: 'atx',
bulletListMarker: '-',
linkStyle: 'inlined'
});
/**
* Minimal HTML cleaner: remove scripts, styles, comments only (for crawler use case)
*/
function preprocessHtml(html) {
let cleaned = html;
cleaned = cleaned.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, '');
cleaned = cleaned.replace(/<style\b[^<]*(?:(?!<\/style>)<[^<]*)*<\/style>/gi, '');
cleaned = cleaned.replace(/<noscript\b[^<]*(?:(?!<\/noscript>)<[^<]*)*<\/noscript>/gi, '');
cleaned = cleaned.replace(/<iframe\b[^<]*(?:(?!<\/iframe>)<[^<]*)*<\/iframe>/gi, '');
cleaned = cleaned.replace(/<!--[\s\S]*?-->/g, '');
cleaned = cleaned.replace(/\s(onclick|onload|onerror|onmouse\w+)=["'][^"']*["']/gi, '');
cleaned = cleaned.replace(/\s(data-gtm-[\w-]+)=["'][^"']*["']/gi, '');
return cleaned;
}
/**
* Clean HTML: extract main content and remove noise (nav, ads, sidebar, etc.) while KEEPING links
*/
function cleanHtml(html, url) {
try {
const dom = new JSDOM(html, { url });
const doc = dom.window.document;
// Elements to remove (they contain noise like nav, ads, sidebars, etc.)
const noiseSelectors = [
'script', 'style', 'noscript', 'iframe', 'object', 'embed',
'nav', 'header', 'footer', 'aside',
'[role="navigation"]', '[role="banner"]', '[role="contentinfo"]', '[role="complementary"]',
'.nav', '.navigation', '.menu', '.sidebar', '.advertisement', '.ad', '.ads',
'.social', '.share', '.sharing', '.comments', '.related',
'#nav', '#navigation', '#menu', '#sidebar', '#footer', '#header',
'.header', '.top-bar', '.bottom-bar',
'[aria-hidden="true"]'
];
// Remove noise elements
for (const selector of noiseSelectors) {
try {
doc.querySelectorAll(selector).forEach(el => el.remove());
} catch (e) {
// Ignore invalid selectors
}
}
// Find main content (common patterns used by Readability and other extractors)
let mainContent = null;
const contentSelectors = [
'article',
'[role="main"]',
'main',
'.post', '.article', '.entry', '.content',
'#content', '#main', '#article',
'.post-content', '.article-content', '.entry-content'
];
for (const selector of contentSelectors) {
const el = doc.querySelector(selector);
if (el && el.textContent.trim().length > 200) {
mainContent = el;
break;
}
}
// Fallback: find largest text block
if (!mainContent) {
const body = doc.body;
let maxLen = 0;
body.querySelectorAll('div, section').forEach(el => {
const text = el.textContent.trim();
if (text.length > maxLen) {
maxLen = text.length;
mainContent = el;
}
});
}
if (!mainContent) {
mainContent = doc.body;
}
// Clean attributes that are not needed (keep href on links)
const cleanAttributes = (el) => {
for (const child of el.querySelectorAll('*')) {
// Keep: href on links, src on images/videos, alt, title
// Remove: onclick, onerror, data-*, style, class, id, etc.
const attrsToRemove = [];
for (const attr of child.attributes) {
const name = attr.name.toLowerCase();
if (name === 'href') continue;
if (name === 'src' && (child.tagName === 'IMG' || child.tagName === 'VIDEO' || child.tagName === 'AUDIO')) continue;
if (name === 'alt' || name === 'title' || name === 'width' || name === 'height') continue;
if (name.startsWith('data-')) continue;
attrsToRemove.push(attr.name);
}
attrsToRemove.forEach(a => child.removeAttribute(a));
}
};
cleanAttributes(mainContent);
const cleanedHtml = mainContent.innerHTML;
console.log(`[cleanHtml] Cleaned HTML: ${cleanedHtml.length} chars`);
return cleanedHtml;
} catch (error) {
console.error(`[cleanHtml] Error: ${error.message}`);
return preprocessHtml(html);
}
}
/**
* Extract main content using custom cleaner (preserves links), then convert to Markdown with turndown
*/
function extractWithReadability(html, url) {
const td = new TurndownService({
headingStyle: 'atx',
bulletListMarker: '-',
linkStyle: 'inlined'
});
try {
// Step 1: Clean HTML (remove noise, keep links)
const cleanedHtml = cleanHtml(html, url);
// Step 2: Convert to Markdown (only if needed)
const markdown = td.turndown(cleanedHtml);
// Extract title
const dom = new JSDOM(html, { url });
const title = dom.window.document.querySelector('title')?.textContent?.trim() || '';
console.log(`[extractWithReadability] Extracted content: "${title}", ${markdown.length} chars`);
return {
title,
content: markdown,
length: markdown.length,
byline: '',
dir: '',
excerpt: ''
};
} catch (error) {
console.error(`[extractWithReadability] Error: ${error.message}`);
const cleanedHtml = cleanHtml(html, url);
const markdown = td.turndown(cleanedHtml);
return {
title: '',
content: markdown,
byline: '',
dir: '',
length: markdown.length,
excerpt: ''
};
}
}
/**
* Convert HTML to Markdown using Turndown
*/
function convertToMarkdown(html, title) {
try {
const turndownService = new TurndownService({
headingStyle: 'atx',
bulletListMarker: '-',
codeBlockStyle: 'fenced',
emDelimiter: '*',
strongDelimiter: '**',
linkStyle: 'inlined'
});
// Remove images and base64 encoded data
turndownService.addRule('removeImages', {
filter: 'img',
replacement: () => ''
});
// Remove empty paragraphs
turndownService.addRule('removeEmptyParagraphs', {
filter: function (node) {
return node.nodeName === 'P' && node.textContent.trim() === '';
},
replacement: () => ''
});
// Convert to markdown
let markdown = turndownService.turndown(html);
// Clean up multiple blank lines
markdown = markdown.replace(/\n{3,}/g, '\n\n');
// Add title as H1 if provided
if (title && title.trim()) {
markdown = `# ${title}\n\n${markdown}`;
}
return markdown;
} catch (error) {
console.error(`[convertToMarkdown] Error: ${error.message}`);
return html; // Fallback to HTML if conversion fails
}
}
/**
* Safe heartbeat helper
*/
function sendHeartbeat(data) {
try {
const activity = require('@temporalio/activity').activity;
if (activity && typeof activity.heartbeat === 'function') {
activity.heartbeat(data);
}
} catch (e) {
// Silently ignore
}
}
/**
* Browser Provider Configuration
*/
const BROWSER_PROVIDERS = {
local: {
name: 'local',
launch: async (config) => {
const launchOptions = {
headless: true,
args: ['--no-sandbox', '--disable-setuid-sandbox']
};
if (config.proxyUrl) {
launchOptions.proxy = { server: config.proxyUrl };
}
return await chromium.launch(launchOptions);
}
},
browserless: {
name: 'browserless',
launch: async (config) => {
const wsEndpoint = process.env.BROWSERLESS_WS_ENDPOINT || config.browserlessWs;
if (!wsEndpoint) {
throw new Error('Browserless WebSocket endpoint not configured');
}
return await chromium.connectOverCDP(wsEndpoint);
}
},
brightdata: {
name: 'brightdata',
launch: async (config) => {
const wsEndpoint = process.env.BRIGHTDATA_WS_ENDPOINT || config.brightdataWs;
if (!wsEndpoint) {
throw new Error('Bright Data WebSocket endpoint not configured');
}
return await chromium.connectOverCDP(wsEndpoint);
}
}
};
/**
* Activity: Complete web scraping - handles entire lifecycle
* Like extract_with_marker in File Extractor
*
* @param {Object} input
* @param {string} input.jobId - Job ID
* @param {string} input.url - URL to scrape
* @param {string} input.bucket - MinIO bucket
* @param {Object} input.config - Scraping configuration
* @returns {Object} Result with paths and metadata
*/
async function scrapeWebPage(input) {
const { jobId, url, bucket, config } = input;
let browser = null;
let context = null;
// Create fresh S3 client for each activity execution
const s3 = new S3Client({
endpoint: process.env.MINIO_ENDPOINT || 'http://minio:9000',
region: 'us-east-1',
credentials: {
accessKeyId: process.env.MINIO_ACCESS_KEY || 'minioadmin',
secretAccessKey: process.env.MINIO_SECRET_KEY || 'minioadmin',
},
forcePathStyle: true,
});
try {
// STEP 1: Launch browser (20%)
sendHeartbeat({ step: 'launching', progress: 20, message: 'Lancement navigateur...' });
console.log(`[scrapeWebPage] browserProvider=${config.browserProvider}, hasBrightdataWs=${!!config.brightdataWs}, orgId=${config.organizationId}`);
// Le endpoint navigateur (BrightData/Browserless) est résolu par workflow-api
// et transmis en paramètre (config.brightdataWs) — pas d'appel config-service ici.
const provider = BROWSER_PROVIDERS[config.browserProvider || 'local'];
if (!provider) {
throw new Error(`Unknown browser provider: ${config.browserProvider}`);
}
browser = await provider.launch({
proxyUrl: config.useProxy ? config.proxyUrl : null,
brightdataWs: config.brightdataWs,
browserlessWs: config.browserlessWs,
});
// STEP 2: Create context and page (30%)
sendHeartbeat({ step: 'navigating', progress: 30, message: 'Navigation...' });
const contextOptions = {
userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36',
};
if (config.headers) contextOptions.extraHTTPHeaders = config.headers;
if (config.cookies) contextOptions.cookies = config.cookies;
context = await browser.newContext(contextOptions);
const page = await context.newPage();
// STEP 3: Navigate to page (40%)
try {
await page.goto(url, {
waitUntil: 'load',
timeout: config.timeout || 60000
});
console.log(`[scrapeWebPage] page.goto OK, url=${page.url()}`);
} catch (navError) {
console.log(`[scrapeWebPage] page.goto error: ${navError.message?.substring(0, 80)}`);
if (!navError.message?.includes('ERR_ABORTED')) throw navError;
}
// Wait for dynamic content to load
await page.waitForTimeout(2000);
if (config.waitForSelector) {
await page.waitForSelector(config.waitForSelector, { timeout: 10000 });
}
// STEP 4: Extract content (60%)
sendHeartbeat({ step: 'extracting', progress: 60, message: 'Extraction contenu...' });
const rawHtml = await page.content();
const pageTitle = await page.title();
const originalSize = rawHtml.length;
// Determine which HTML to use based on useReadability config
// useReadability = true (default): clean HTML (remove nav, ads, sidebar) via cleanHtml() → then convert to markdown
// useReadability = false: keep full HTML (just remove scripts/styles/comments) → convert to markdown
const useReadability = config.useReadability !== false;
let htmlToConvert;
let articleTitle = pageTitle;
if (useReadability) {
// Synthesis use case: clean HTML (remove nav, ads, sidebar, etc.) then convert
sendHeartbeat({ step: 'cleaning', progress: 65, message: 'Nettoyage contenu...' });
htmlToConvert = cleanHtml(rawHtml, url);
// Extract title from cleaned content
try {
const titleDom = new JSDOM(htmlToConvert);
articleTitle = titleDom.window.document.querySelector('h1, h2, title')?.textContent?.trim() || pageTitle;
} catch (e) {}
console.log(`[scrapeWebPage] Using cleaned HTML (${htmlToConvert.length} chars)`);
} else {
// Crawler use case: keep full HTML (just remove scripts/styles/comments)
sendHeartbeat({ step: 'cleaning', progress: 65, message: 'Nettoyage HTML minimal...' });
htmlToConvert = preprocessHtml(rawHtml);
console.log(`[scrapeWebPage] Using full HTML (${htmlToConvert.length} chars)`);
}
// Determine output format (independent from useReadability)
// outputFormat can be 'markdown' (default) or 'html'
const outputFormat = config.outputFormat || 'markdown';
// Apply cleaning based on useReadability
let cleanedHtml = htmlToConvert;
if (useReadability) {
// Clean HTML (remove nav, ads, sidebar, etc.)
cleanedHtml = cleanHtml(htmlToConvert, url);
// Extract title from cleaned content
try {
const titleDom = new JSDOM(cleanedHtml);
articleTitle = titleDom.window.document.querySelector('h1, h2, title')?.textContent?.trim() || pageTitle;
} catch (e) {}
}
// Convert to requested format
let contentToReturn;
if (outputFormat === 'markdown') {
contentToReturn = turndownService.turndown(cleanedHtml);
console.log(`[scrapeWebPage] Converted to markdown: ${contentToReturn.length} chars`);
} else {
contentToReturn = cleanedHtml;
console.log(`[scrapeWebPage] Keeping HTML (outputFormat=html): ${contentToReturn.length} chars`);
}
console.log(`[scrapeWebPage] Content processed: ${originalSize} -> ${contentToReturn.length} chars`);
// STEP 5: Take screenshot (75%)
sendHeartbeat({ step: 'screenshot', progress: 75, message: 'Capture écran...' });
const screenshotBuffer = await page.screenshot({
fullPage: true,
type: 'png'
});
// Close browser context and page
await context.close();
context = null;
// STEP 6: Upload to MinIO (85%)
sendHeartbeat({ step: 'uploading', progress: 85, message: 'Upload vers MinIO...' });
const screenshotPath = `${jobId}/screenshot.png`;
const contentType = outputFormat === 'markdown' ? 'text/markdown' : 'text/html';
const contentPath = outputFormat === 'markdown' ? `${jobId}/result.md` : `${jobId}/result.html`;
// Upload content (markdown or HTML)
await s3.send(new PutObjectCommand({
Bucket: bucket,
Key: contentPath,
Body: contentToReturn,
ContentType: contentType
}));
console.log(`[scrapeWebPage] Content uploaded: ${bucket}/${contentPath} (${contentToReturn.length} chars)`);
// Upload screenshot - minimal configuration
await s3.send(new PutObjectCommand({
Bucket: bucket,
Key: screenshotPath,
Body: screenshotBuffer,
ContentType: 'image/png'
}));
console.log(`[scrapeWebPage] Screenshot uploaded: ${bucket}/${screenshotPath}`);
// STEP 7: Close browser (95%)
sendHeartbeat({ step: 'closing', progress: 95, message: 'Fermeture navigateur...' });
await browser.close();
browser = null;
// Return result
return {
contentPath,
contentType,
screenshotPath,
bucket,
title: articleTitle,
url,
content: contentToReturn, // markdown or HTML depending on outputFormat
provider: config.browserProvider || 'local',
};
} catch (error) {
console.error(`[scrapeWebPage] Error: ${error.message}`);
// Cleanup on error
if (context) {
try { await context.close(); } catch (e) {}
}
if (browser) {
try { await browser.close(); } catch (e) {}
}
// Clean error message: remove "Call log:" and stack trace details
let cleanMessage = error.message.split('\nCall log:')[0];
const err = new Error(cleanMessage);
err.stack = error.stack;
throw err;
}
}
/**
* Activity: Resolve URL with a real browser (Playwright)
* Suit les redirects, passe les challenges Cloudflare, et determine si la cible est une page web ou un fichier
*
* @param {Object} input
* @param {string} input.url - URL to resolve
* @returns {Object} { resolvedUrl, isFile, isWeb, status, contentType }
*/
async function resolveUrlWithBrowser({ url }) {
console.log(`[resolveUrlWithBrowser] Resolving: ${url}`);
let browser = null;
try {
browser = await chromium.launch({
headless: true,
args: ['--no-sandbox', '--disable-setuid-sandbox'],
});
const context = await browser.newContext({
userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36',
});
const page = await context.newPage();
let finalUrl = url;
let contentType = null;
let firstResponse = true;
page.on('response', (response) => {
if (firstResponse) {
firstResponse = false;
finalUrl = response.url();
contentType = response.headers()['content-type'] || null;
}
});
try {
await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 30000 });
await page.waitForTimeout(3000);
} catch (navError) {
console.warn(`[resolveUrlWithBrowser] Navigation warning: ${navError.message}`);
}
const pageContentType = contentType || '';
const FILE_MIME_TYPES = ['application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument', 'application/vnd.ms-excel', 'application/vnd.ms-powerpoint', 'image/'];
const isFile = FILE_MIME_TYPES.some(mime => pageContentType.startsWith(mime));
console.log(`[resolveUrlWithBrowser] Resolved: ${url} → ${finalUrl} (isFile: ${isFile}, contentType: ${pageContentType})`);
return {
success: true,
originalUrl: url,
resolvedUrl: finalUrl,
status: 200,
isFile,
isWeb: !isFile,
contentType: pageContentType,
};
} catch (e) {
console.error(`[resolveUrlWithBrowser] Failed: ${url} - ${e.message}`);
throw e;
} finally {
if (browser) {
try { await browser.close(); } catch (e) {}
}
}
}
module.exports = {
scrapeWebPage,
resolveUrlWithBrowser,
}; |