All files / src/handlers content-handlers.ts

96.22% Statements 51/53
100% Branches 30/30
100% Functions 5/5
96.22% Lines 51/53

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                                        7x   7x               5x   5x 2x     5x   5x                 2x         11x 11x     10x 2x           8x 6x   6x 6x 1x 1x       6x 1x     1x       6x     5x 5x 5x 5x   5x     5x 5x     1x       8x         8x 8x   8x   8x 7x             8x             8x   3x         4x 4x     4x 2x     2x                                 2x         3x 3x     3x                           1x 1x   1x                          
import { BaseHandler } from './base-handler.js';
import {
  MarkdownEndpointOptions,
  MarkdownEndpointResponse,
  ScreenshotEndpointOptions,
  ScreenshotEndpointResponse,
  PDFEndpointOptions,
  PDFEndpointResponse,
  HTMLEndpointOptions,
  HTMLEndpointResponse,
  FilterType,
} from '../types.js';
import * as fs from 'fs/promises';
import * as path from 'path';
import * as os from 'os';
 
export class ContentHandlers extends BaseHandler {
  async getMarkdown(
    options: Omit<MarkdownEndpointOptions, 'f' | 'q' | 'c'> & { filter?: string; query?: string; cache?: string },
  ) {
    try {
      // Map from schema property names to API parameter names
      const result: MarkdownEndpointResponse = await this.service.getMarkdown({
        url: options.url,
        f: options.filter as FilterType | undefined, // Schema provides 'filter', API expects 'f'
        q: options.query, // Schema provides 'query', API expects 'q'
        c: options.cache, // Schema provides 'cache', API expects 'c'
      });
 
      // Format the response
      let formattedText = `URL: ${result.url}\nFilter: ${result.filter}`;
 
      if (result.query) {
        formattedText += `\nQuery: ${result.query}`;
      }
 
      formattedText += `\nCache: ${result.cache}\n\nMarkdown:\n${result.markdown || 'No content found.'}`;
 
      return {
        content: [
          {
            type: 'text',
            text: formattedText,
          },
        ],
      };
    } catch (error) {
      throw this.formatError(error, 'get markdown');
    }
  }
 
  async captureScreenshot(options: ScreenshotEndpointOptions) {
    try {
      const result: ScreenshotEndpointResponse = await this.service.captureScreenshot(options);
 
      // Response has { success: true, screenshot: "base64string" }
      if (!result.success || !result.screenshot) {
        throw new Error('Screenshot capture failed - no screenshot data in response');
      }
 
      let savedFilePath: string | undefined;
 
      // Save to local directory if requested
      if (options.save_to_directory) {
        try {
          // Resolve home directory path
          let resolvedPath = options.save_to_directory;
          if (resolvedPath.startsWith('~')) {
            const homedir = os.homedir();
            resolvedPath = path.join(homedir, resolvedPath.slice(1));
          }
 
          // Check if user provided a file path instead of directory
          if (resolvedPath.endsWith('.png') || resolvedPath.endsWith('.jpg')) {
            console.warn(
              `Warning: save_to_directory should be a directory path, not a file path. Using parent directory.`,
            );
            resolvedPath = path.dirname(resolvedPath);
          }
 
          // Ensure directory exists
          await fs.mkdir(resolvedPath, { recursive: true });
 
          // Generate filename from URL and timestamp
          const url = new URL(options.url);
          const hostname = url.hostname.replace(/[^a-z0-9]/gi, '-');
          const timestamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, -5);
          const filename = `${hostname}-${timestamp}.png`;
 
          savedFilePath = path.join(resolvedPath, filename);
 
          // Convert base64 to buffer and save
          const buffer = Buffer.from(result.screenshot, 'base64');
          await fs.writeFile(savedFilePath, buffer);
        } catch (saveError) {
          // Log error but don't fail the operation
          console.error('Failed to save screenshot locally:', saveError);
        }
      }
 
      const textContent = savedFilePath
        ? `Screenshot captured for: ${options.url}\nSaved to: ${savedFilePath}`
        : `Screenshot captured for: ${options.url}`;
 
      // If saved locally and screenshot is large (>800KB), don't return the base64 data
      const screenshotSize = Buffer.from(result.screenshot, 'base64').length;
      const shouldReturnImage = !savedFilePath || screenshotSize < 800 * 1024; // 800KB threshold
 
      const content = [];
 
      if (shouldReturnImage) {
        content.push({
          type: 'image',
          data: result.screenshot,
          mimeType: 'image/png',
        });
      }
 
      content.push({
        type: 'text',
        text: shouldReturnImage
          ? textContent
          : `${textContent}\n\nNote: Screenshot data not returned due to size (${Math.round(screenshotSize / 1024)}KB). View the saved file instead.`,
      });
 
      return { content };
    } catch (error) {
      throw this.formatError(error, 'capture screenshot');
    }
  }
 
  async generatePDF(options: PDFEndpointOptions) {
    try {
      const result: PDFEndpointResponse = await this.service.generatePDF(options);
 
      // Response has { success: true, pdf: "base64string" }
      if (!result.success || !result.pdf) {
        throw new Error('PDF generation failed - no PDF data in response');
      }
 
      return {
        content: [
          {
            type: 'resource',
            resource: {
              uri: `data:application/pdf;name=${encodeURIComponent(new URL(String(options.url)).hostname)}.pdf;base64,${result.pdf}`,
              mimeType: 'application/pdf',
              blob: result.pdf,
            },
          },
          {
            type: 'text',
            text: `PDF generated for: ${options.url}`,
          },
        ],
      };
    } catch (error) {
      throw this.formatError(error, 'generate PDF');
    }
  }
 
  async getHTML(options: HTMLEndpointOptions) {
    try {
      const result: HTMLEndpointResponse = await this.service.getHTML(options);
 
      // Response has { html: string, url: string, success: true }
      return {
        content: [
          {
            type: 'text',
            text: result.html || '',
          },
        ],
      };
    } catch (error) {
      throw this.formatError(error, 'get HTML');
    }
  }
 
  async extractWithLLM(options: { url: string; query: string }) {
    try {
      const result = await this.service.extractWithLLM(options);
 
      return {
        content: [
          {
            type: 'text',
            text: result.answer,
          },
        ],
      };
    } catch (error) {
      throw this.formatError(error, 'extract with LLM');
    }
  }
}