fetch-thumbnail-dimensions.ts
1.91 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
/**
* Utility to fetch Figma thumbnail and extract its dimensions
* Matches the Python reference implementation from evolt
*/
import axios from 'axios';
import { logger } from '../../../utils/logger';
export interface ThumbnailDimensions {
width: number;
height: number;
}
/**
* Fetches Figma thumbnail and extracts its dimensions.
* This ensures the browser viewport matches the Figma thumbnail dimensions,
* preventing screenshot dimension mismatches.
*
* Based on evolt Python implementation: _fetch_figma_thumbnail_with_dimensions()
*
* @param figmaThumbnailUrl - Figma thumbnail CDN URL
* @returns Promise resolving to thumbnail dimensions, or undefined if fetch fails
*
* @example
* ```typescript
* const dimensions = await fetchThumbnailDimensions(figmaThumbnailUrl);
* if (dimensions) {
* const viewport = { width: dimensions.width, height: dimensions.height };
* // Use viewport for browser launch
* }
* ```
*/
export async function fetchThumbnailDimensions(figmaThumbnailUrl: string): Promise<ThumbnailDimensions | undefined> {
if (!figmaThumbnailUrl) {
return undefined;
}
try {
const sharp = (await import('sharp')).default;
// Fetch the image from Figma CDN
const response = await axios.get(figmaThumbnailUrl, {
responseType: 'arraybuffer',
timeout: 30000,
});
// Extract dimensions using Sharp
const imageBuffer = Buffer.from(response.data);
const metadata = await sharp(imageBuffer).metadata();
if (!metadata.width || !metadata.height) {
return undefined;
}
return {
width: metadata.width,
height: metadata.height,
};
} catch (error) {
const errorMsg = error instanceof Error ? error.message : String(error);
logger.printWarnLog(`Failed to fetch Figma thumbnail: ${errorMsg}`);
return undefined;
}
}