/**
* Screenshot management utilities
*/
import * as fs from 'fs';
import * as path from 'path';
import { Page, Locator } from 'playwright';
import { SCREENSHOTS_DIR, MAX_FILENAME_LENGTH } from '../constants/config.js';
/**
* Ensure screenshots directory exists
*/
export function ensureScreenshotsDirectory(): void {
if (!fs.existsSync(SCREENSHOTS_DIR)) {
fs.mkdirSync(SCREENSHOTS_DIR, { recursive: true });
}
}
/**
* Generate a filename-safe string from arbitrary text
*/
export function sanitizeFilename(text: string, maxLength: number = MAX_FILENAME_LENGTH): string {
return text
.replace(/[^a-z0-9]/gi, '-')
.toLowerCase()
.substring(0, maxLength);
}
/**
* Capture a screenshot of the entire page
*/
export async function captureFullPageScreenshot(page: Page): Promise<string> {
const timestamp = Date.now();
const filename = `scan-${timestamp}.png`;
const screenshotPath = path.join(SCREENSHOTS_DIR, filename);
await page.screenshot({ path: screenshotPath, fullPage: true });
return screenshotPath;
}
/**
* Capture a screenshot of a specific element
*/
export async function captureElementScreenshot(
locator: Locator,
prefix: string = 'element'
): Promise<string> {
const timestamp = Date.now();
const filename = `${prefix}-${timestamp}.png`;
const screenshotPath = path.join(SCREENSHOTS_DIR, filename);
await locator.screenshot({ path: screenshotPath });
return screenshotPath;
}
/**
* Capture a screenshot with a custom filename
*/
export async function captureNamedScreenshot(
page: Page | Locator,
name: string
): Promise<string> {
const timestamp = Date.now();
const sanitizedName = sanitizeFilename(name);
const filename = `${sanitizedName}-${timestamp}.png`;
const screenshotPath = path.join(SCREENSHOTS_DIR, filename);
await page.screenshot({ path: screenshotPath });
return screenshotPath;
}