All files / src/core scraper.ts

0% Statements 0/163
0% Branches 0/51
0% Functions 0/20
0% Lines 0/162

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 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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 
import { EventEmitter } from 'eventemitter3';
import {
  ScraperEngine,
  ScraperDefinition,
  ScraperResult,
  ScraperExecutionOptions,
  ScraperContext,
  ScraperHook,
  HookHandler,
  ScraperPlugin,
  ScraperEvents,
  ScraperEngineConfig,
  Logger,
} from './types';
import { BrowserPool } from './browser-pool';
 
// Helper interfaces for navigation configs (internal, no need for extensive JSDoc for public API)
interface FormConfig {
  inputSelector?: string;
  submitSelector?: string;
}
 
interface SelectorConfig {
  selector?: string;
}
 
interface ResponseConfig {
  urlPattern?: string;
}
 
interface TimeoutConfig {
  duration?: number;
}
 
/**
 * @file Provides the core implementation of the ScraperEngine, orchestrating
 * the entire scraping lifecycle including browser management, hook execution,
 * plugin integration, and data parsing.
 */
 
/**
 * The main engine for managing and executing scrapers.
 * It handles the browser pool, plugin lifecycle, global and scraper-specific hooks,
 * and the overall execution flow of scraper definitions.
 * Emits various events throughout the scraping lifecycle (see {@link ScraperEvents}).
 */
export class CrawleeScraperEngine extends EventEmitter<ScraperEvents> implements ScraperEngine {
  private browserPool: BrowserPool;
  private logger: Logger;
  private config: ScraperEngineConfig;
  private definitions = new Map<string, ScraperDefinition<unknown, unknown>>();
  private plugins = new Map<string, ScraperPlugin>();
  private globalHooks = new Map<ScraperHook, HookHandler<unknown, unknown>[]>();
 
  /**
   * Creates an instance of the CrawleeScraperEngine.
   * @param config The configuration object for the scraper engine. See {@link ScraperEngineConfig}.
   * @param logger An instance of a logger conforming to the {@link Logger} interface.
   */
  constructor(config: ScraperEngineConfig, logger: Logger) {
    super();
    this.config = config;
    this.logger = logger;
    this.browserPool = new BrowserPool(config.browserPool, logger);
    this.initializeGlobalHooks();
    this.logger.info('CrawleeScraperEngine initialized.', {
      browserPoolConfig: config.browserPool.maxSize,
    });
  }
 
  /**
   * Executes a registered scraper definition with the given input and runtime options.
   * This method orchestrates the entire scraping lifecycle for a single task, including:
   * - Input validation.
   * - Acquiring a browser instance from the pool.
   * - Executing `beforeRequest`, scraper `parse`, `afterRequest`, `onSuccess` hooks.
   * - Handling retries with `onRetry` hooks upon failure.
   * - Managing errors with `onError` hooks.
   * - Output validation.
   * - Releasing the browser instance.
   * Emits `scraper:start`, `scraper:success`, `scraper:error`, and `scraper:retry` events.
   *
   * @template Input The type of the input data the scraper expects.
   * @template Output The type of the data the scraper's `parse` function will return.
   * @param definition The {@link ScraperDefinition} to execute.
   * @param input The input data to pass to the scraper.
   * @param options Optional. Partial {@link ScraperExecutionOptions} that can override
   *                default and definition-specific options for this execution.
   * @returns A Promise that resolves to a {@link ScraperResult} containing the outcome of the execution.
   */
  async execute<Input, Output>(
    definition: ScraperDefinition<Input, Output>,
    input: Input,
    options?: Partial<ScraperExecutionOptions>
  ): Promise<ScraperResult<Output>> {
    const startTime = Date.now();
    const executionOptions = { ...this.config.defaultOptions, ...definition.options, ...options };
 
    this.logger.info('Starting scraper execution', {
      scraperId: definition.id,
      input: typeof input === 'string' ? input : '[object]',
    });
 
    this.emit('scraper:start', { scraperId: definition.id, input });
 
    // Validate input
    Iif (definition.validateInput) {
      const validation = definition.validateInput(input);
      Iif (validation !== true) {
        const error = new Error(`Input validation failed: ${validation}`);
        this.emit('scraper:error', { scraperId: definition.id, error });
        return this.createErrorResult<Output>(definition.id, error, 0, startTime);
      }
    }
 
    let lastError: Error | undefined;
    let attempts = 0;
 
    for (attempts = 1; attempts <= executionOptions.retries + 1; attempts++) {
      const instance = await this.browserPool.acquire();
 
      try {
        const context: ScraperContext<Input, Output> = {
          input,
          page: instance.page,
          attempt: attempts,
          startTime,
          options: executionOptions,
          metadata: {},
          log: this.logger,
        };
 
        // Execute hooks and scraper logic
        await this.executeHooks('beforeRequest', context, definition);
 
        const result = await this.executeScraper(definition, context);
 
        context.result = result;
        await this.executeHooks('afterRequest', context, definition);
        await this.executeHooks('onSuccess', context, definition);
 
        // Validate output
        Iif (definition.validateOutput) {
          const validation = definition.validateOutput(result);
          Iif (validation !== true) {
            throw new Error(`Output validation failed: ${validation}`);
          }
        }
 
        const successResult = this.createSuccessResult(definition.id, result, attempts, startTime);
        this.emit('scraper:success', { scraperId: definition.id, result: successResult });
 
        return successResult;
      } catch (error) {
        lastError = error instanceof Error ? error : new Error(String(error));
 
        this.logger.warn('Scraper execution attempt failed', {
          scraperId: definition.id,
          attempt: attempts,
          error: lastError.message,
        });
 
        const context: ScraperContext<Input, Output> = {
          input,
          page: instance.page,
          attempt: attempts,
          startTime,
          options: executionOptions,
          metadata: {},
          log: this.logger,
          error: lastError,
        };
 
        await this.executeHooks('onError', context, definition);
 
        Iif (attempts <= executionOptions.retries) {
          this.emit('scraper:retry', { scraperId: definition.id, attempt: attempts });
          await this.executeHooks('onRetry', context, definition);
          await this.delay(executionOptions.retryDelay);
        }
      } finally {
        this.browserPool.release(instance);
      }
    }
 
    Iif (lastError === undefined) {
      // This path should ideally not be reached if the loop logic ensures lastError is set on failure.
      // Creating a generic error to handle this unexpected state.
      const undefinedError = new Error(
        'Scraper execution failed, but no specific error was captured by lastError.'
      );
      this.logger.error(
        'Critical: lastError is undefined after retry loop. This may indicate a logic flaw.',
        {
          scraperId: definition.id,
        }
      );
      const errorResult = this.createErrorResult<Output>(
        definition.id,
        undefinedError,
        attempts - 1,
        startTime
      );
      this.emit('scraper:error', { scraperId: definition.id, error: undefinedError });
      return errorResult;
    }
 
    // If we reach here, lastError is defined and is of type Error due to the check above.
    const errorResult = this.createErrorResult<Output>(
      definition.id,
      lastError,
      attempts - 1,
      startTime
    );
    this.emit('scraper:error', { scraperId: definition.id, error: lastError });
 
    return errorResult;
  }
 
  /**
   * Registers a scraper definition with the engine, making it available for execution.
   * If a definition with the same ID already exists, it will be overwritten.
   * @template Input The type of the input data the scraper definition expects.
   * @template Output The type of the data the scraper definition will output.
   * @param definition The {@link ScraperDefinition} to register.
   */
  register<Input, Output>(definition: ScraperDefinition<Input, Output>): void {
    this.logger.info('Registering scraper definition', { scraperId: definition.id });
    this.definitions.set(definition.id, definition as ScraperDefinition<unknown, unknown>);
  }
 
  /**
   * Retrieves a registered scraper definition by its ID.
   * @param id The unique identifier of the scraper definition.
   * @returns The {@link ScraperDefinition} if found, otherwise `undefined`.
   */
  getDefinition(id: string): ScraperDefinition | undefined {
    this.logger.debug('Retrieving scraper definition', { scraperId: id });
    return this.definitions.get(id);
  }
 
  /**
   * Lists all currently registered scraper definitions.
   * @returns An array of {@link ScraperDefinition} objects.
   */
  listDefinitions(): ScraperDefinition[] {
    this.logger.debug('Listing all scraper definitions');
    return Array.from(this.definitions.values());
  }
 
  /**
   * Installs a plugin, allowing it to extend the engine's functionality.
   * The plugin's `install` method will be called with this engine instance.
   * @param plugin The {@link ScraperPlugin} instance to install.
   */
  use(plugin: ScraperPlugin): void {
    this.logger.info('Installing plugin', {
      name: plugin.name,
      version: plugin.version,
    });
 
    Iif (this.plugins.has(plugin.name)) {
      this.logger.warn(`Plugin "${plugin.name}" is already installed. Re-installing.`);
      // Optionally, call uninstall on the existing plugin if it exists and supports it
      const existingPlugin = this.plugins.get(plugin.name);
      Iif (existingPlugin?.uninstall) {
        try {
          existingPlugin.uninstall(this);
        } catch (error) {
          this.logger.error(
            `Error uninstalling existing plugin "${plugin.name}" before re-installation.`,
            { error }
          );
        }
      }
    }
 
    this.plugins.set(plugin.name, plugin);
    try {
      plugin.install(this);
      this.logger.info(`Plugin "${plugin.name}" installed successfully.`);
    } catch (error) {
      this.logger.error(
        `Error during installation of plugin "${plugin.name}". Plugin may not function correctly.`,
        { error }
      );
      // Optionally, remove the plugin if install fails
      this.plugins.delete(plugin.name);
      throw error; // Re-throw error if install is critical
    }
  }
 
  /**
   * Adds a global hook handler for a specified lifecycle event.
   * Global hooks are executed for all scrapers managed by this engine.
   * @param hook The {@link ScraperHook} event type (e.g., 'beforeRequest', 'onError').
   * @param handler The {@link HookHandler} function to execute when the event occurs.
   */
  addHook(hook: ScraperHook, handler: HookHandler<unknown, unknown>): void {
    Iif (!this.globalHooks.has(hook)) {
      this.globalHooks.set(hook, []);
    }
    const handlers = this.globalHooks.get(hook);
    // Ensure handlers is not undefined (shouldn't be due to above check, but for type safety)
    Iif (handlers) {
      handlers.push(handler);
      this.logger.debug(`Added global hook for "${hook}" event.`);
    }
  }
 
  /**
   * Removes a previously added global hook handler.
   * @param hook The {@link ScraperHook} event type.
   * @param handler The specific {@link HookHandler} function to remove.
   *                It must be the same function reference that was originally added.
   */
  removeHook(hook: ScraperHook, handler: HookHandler<unknown, unknown>): void {
    const handlers = this.globalHooks.get(hook);
    Iif (handlers) {
      const index = handlers.indexOf(handler);
      if (index > -1) {
        handlers.splice(index, 1);
        this.logger.debug(`Removed global hook for "${hook}" event.`);
      } else {
        this.logger.warn(`Attempted to remove a global hook for "${hook}" that was not found.`);
      }
    }
  }
 
  /**
   * Gracefully shuts down the scraper engine.
   * This includes uninstalling all plugins that have an `uninstall` method
   * and shutting down the browser pool, closing all browser instances.
   * @returns A Promise that resolves when shutdown is complete.
   */
  async shutdown(): Promise<void> {
    this.logger.info('Shutting down scraper engine...');
 
    // Uninstall plugins
    this.logger.debug('Uninstalling plugins...');
    for (const plugin of this.plugins.values()) {
      Iif (plugin.uninstall) {
        plugin.uninstall(this);
      }
    }
 
    await this.browserPool.shutdown();
    this.logger.info('Scraper engine shutdown complete');
  }
 
  /**
   * Execute the actual scraper logic
   */
  private async executeScraper<Input, Output>(
    definition: ScraperDefinition<Input, Output>,
    context: ScraperContext<Input, Output>
  ): Promise<Output> {
    const { page, options } = context;
 
    // Set page options
    await page.setViewportSize(options.viewport);
 
    Iif (options.userAgent) {
      await page.setExtraHTTPHeaders({ 'User-Agent': options.userAgent });
    }
 
    Iif (Object.keys(options.headers).length > 0) {
      await page.setExtraHTTPHeaders(options.headers);
    }
 
    // Handle navigation based on strategy
    await this.handleNavigation(definition, context);
 
    // Handle waiting based on strategy
    await this.handleWaitStrategy(definition, context);
 
    // Execute the parse function
    return await definition.parse(context);
  }
 
  /**
   * Handle navigation based on the navigation strategy
   */
  private async handleNavigation<Input, Output>(
    definition: ScraperDefinition<Input, Output>,
    context: ScraperContext<Input, Output>
  ): Promise<void> {
    const { page, input } = context;
    const { navigation } = definition;
 
    switch (navigation.type) {
      case 'direct':
        await page.goto(definition.url, { timeout: context.options.timeout });
        break;
 
      case 'form': {
        await page.goto(definition.url, { timeout: context.options.timeout });
        const formConfig = navigation.config as FormConfig;
 
        Iif (formConfig.inputSelector) {
          await page.fill(formConfig.inputSelector, String(input));
        }
 
        Iif (formConfig.submitSelector) {
          await page.click(formConfig.submitSelector);
        }
        break;
      }
 
      case 'api': {
        // For API-based navigation, construct URL with parameters
        const url = this.buildApiUrl(definition.url, input, navigation.config);
        await page.goto(url, { timeout: context.options.timeout });
        break;
      }
 
      case 'custom':
        // Custom navigation logic should be handled in the parse function
        break;
 
      default:
        throw new Error(`Unknown navigation type: ${navigation.type}`);
    }
  }
 
  /**
   * Handle wait strategy
   */
  private async handleWaitStrategy<Input, Output>(
    definition: ScraperDefinition<Input, Output>,
    context: ScraperContext<Input, Output>
  ): Promise<void> {
    const { page, options } = context;
    const { waitStrategy } = definition;
 
    switch (waitStrategy.type) {
      case 'selector': {
        const selectorConfig = waitStrategy.config as SelectorConfig;
        Iif (selectorConfig.selector) {
          await page.waitForSelector(selectorConfig.selector, {
            timeout: options.timeout,
          });
        }
        break;
      }
 
      case 'response': {
        const responseConfig = waitStrategy.config as ResponseConfig;
        Iif (responseConfig.urlPattern) {
          await page.waitForResponse(
            response => response.url().includes(responseConfig.urlPattern ?? ''),
            { timeout: options.timeout }
          );
        }
        break;
      }
 
      case 'timeout': {
        const timeoutConfig = waitStrategy.config as TimeoutConfig;
        Iif (timeoutConfig.duration) {
          await page.waitForTimeout(timeoutConfig.duration);
        }
        break;
      }
 
      case 'custom':
        // Custom wait logic should be handled in the parse function
        break;
 
      default:
        throw new Error(`Unknown wait strategy type: ${waitStrategy.type}`);
    }
  }
 
  /**
   * Execute hooks for a specific event
   */
  private async executeHooks<Input, Output>(
    hook: ScraperHook,
    context: ScraperContext<Input, Output>,
    definition: ScraperDefinition<Input, Output>
  ): Promise<void> {
    // Execute global hooks
    const globalHandlers = this.globalHooks.get(hook) ?? [];
    for (const handler of globalHandlers) {
      try {
        await handler(context);
      } catch (error) {
        this.logger.warn('Global hook execution failed', {
          hook,
          error: error instanceof Error ? error.message : String(error),
        });
      }
    }
 
    // Execute definition-specific hooks
    const definitionHandlers = definition.hooks?.[hook] ?? [];
    for (const handler of definitionHandlers) {
      try {
        await handler(context);
      } catch (error) {
        this.logger.warn('Definition hook execution failed', {
          hook,
          scraperId: definition.id,
          error: error instanceof Error ? error.message : String(error),
        });
      }
    }
  }
 
  /**
   * Build API URL with parameters
   */
  private buildApiUrl(baseUrl: string, input: unknown, config: Record<string, unknown>): string {
    Iif (config.paramName && typeof config.paramName === 'string' && typeof input === 'string') {
      const url = new URL(baseUrl);
      url.searchParams.set(config.paramName, input);
      return url.toString();
    }
    return baseUrl;
  }
 
  /**
   * Create success result
   */
  private createSuccessResult<Output>(
    scraperId: string,
    data: Output,
    attempts: number,
    startTime: number
  ): ScraperResult<Output> {
    return {
      success: true,
      data,
      attempts,
      duration: Date.now() - startTime,
      metadata: {
        scraperId,
        timestamp: Date.now(),
        userAgent: 'crawlee-scraper-toolkit',
        url: '',
      },
    };
  }
 
  /**
   * Create error result
   */
  private createErrorResult<Output = unknown>(
    scraperId: string,
    error: Error,
    attempts: number,
    startTime: number
  ): ScraperResult<Output> {
    return {
      success: false,
      error,
      attempts,
      duration: Date.now() - startTime,
      metadata: {
        scraperId,
        timestamp: Date.now(),
        userAgent: 'crawlee-scraper-toolkit',
        url: '',
      },
    };
  }
 
  /**
   * Initialize global hooks from config
   */
  private initializeGlobalHooks(): void {
    for (const [hook, handlers] of Object.entries(this.config.globalHooks)) {
      this.globalHooks.set(hook as ScraperHook, handlers || []);
    }
  }
 
  /**
   * Delay execution
   */
  private async delay(ms: number): Promise<void> {
    return new Promise(resolve => setTimeout(resolve, ms));
  }
}