-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathfigma.ts
More file actions
302 lines (271 loc) · 9.63 KB
/
figma.ts
File metadata and controls
302 lines (271 loc) · 9.63 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
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
import type {
GetImagesResponse,
GetFileResponse,
GetFileNodesResponse,
GetImageFillsResponse,
GetFileMetaResponse,
} from "@figma/rest-api-spec";
import { downloadAndProcessImage, type ImageProcessingResult } from "~/utils/image-processing.js";
import { Logger, writeLogs } from "~/utils/logger.js";
import { fetchWithRetry } from "~/utils/fetch-with-retry.js";
export type FigmaAuthOptions = {
figmaApiKey: string;
figmaOAuthToken: string;
useOAuth: boolean;
useCache: boolean;
};
type SvgOptions = {
outlineText: boolean;
includeId: boolean;
simplifyStroke: boolean;
};
export class FigmaService {
private readonly apiKey: string;
private readonly oauthToken: string;
private readonly useOAuth: boolean;
private readonly baseUrl = "https://api.figma.com/v1";
private readonly useCache: boolean;
constructor({ figmaApiKey, figmaOAuthToken, useOAuth, useCache }: FigmaAuthOptions) {
this.apiKey = figmaApiKey || "";
this.oauthToken = figmaOAuthToken || "";
this.useOAuth = !!useOAuth && !!this.oauthToken;
this.useCache = useCache;
}
private getAuthHeaders(): Record<string, string> {
if (this.useOAuth) {
Logger.log("Using OAuth Bearer token for authentication");
return { Authorization: `Bearer ${this.oauthToken}` };
} else {
Logger.log("Using Personal Access Token for authentication");
return { "X-Figma-Token": this.apiKey };
}
}
/**
* Filters out null values from Figma image responses. This ensures we only work with valid image URLs.
*/
private filterValidImages(
images: { [key: string]: string | null } | undefined,
): Record<string, string> {
if (!images) return {};
return Object.fromEntries(Object.entries(images).filter(([, value]) => !!value)) as Record<
string,
string
>;
}
private async request<T>(endpoint: string): Promise<T> {
try {
Logger.log(`Calling ${this.baseUrl}${endpoint}`);
const headers = this.getAuthHeaders();
return await fetchWithRetry<T>(`${this.baseUrl}${endpoint}`, { headers });
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error);
throw new Error(
`Failed to make request to Figma API endpoint '${endpoint}': ${errorMessage}`,
);
}
}
/**
* Builds URL query parameters for SVG image requests.
*/
private buildSvgQueryParams(svgIds: string[], svgOptions: SvgOptions): string {
const params = new URLSearchParams({
ids: svgIds.join(","),
format: "svg",
svg_outline_text: String(svgOptions.outlineText),
svg_include_id: String(svgOptions.includeId),
svg_simplify_stroke: String(svgOptions.simplifyStroke),
});
return params.toString();
}
/**
* Gets download URLs for image fills without downloading them.
*
* @returns Map of imageRef to download URL
*/
async getImageFillUrls(fileKey: string): Promise<Record<string, string>> {
const endpoint = `/files/${fileKey}/images`;
const response = await this.request<GetImageFillsResponse>(endpoint);
return response.meta.images || {};
}
/**
* Gets download URLs for rendered nodes without downloading them.
*
* @returns Map of node ID to download URL
*/
async getNodeRenderUrls(
fileKey: string,
nodeIds: string[],
format: "png" | "svg",
options: { pngScale?: number; svgOptions?: SvgOptions } = {},
): Promise<Record<string, string>> {
if (nodeIds.length === 0) return {};
if (format === "png") {
const scale = options.pngScale || 2;
const endpoint = `/images/${fileKey}?ids=${nodeIds.join(",")}&format=png&scale=${scale}`;
const response = await this.request<GetImagesResponse>(endpoint);
return this.filterValidImages(response.images);
} else {
const svgOptions = options.svgOptions || {
outlineText: true,
includeId: false,
simplifyStroke: true,
};
const params = this.buildSvgQueryParams(nodeIds, svgOptions);
const endpoint = `/images/${fileKey}?${params}`;
const response = await this.request<GetImagesResponse>(endpoint);
return this.filterValidImages(response.images);
}
}
/**
* Download images method with post-processing support for cropping and returning image dimensions.
*
* Supports:
* - Image fills vs rendered nodes (based on imageRef vs nodeId)
* - PNG vs SVG format (based on filename extension)
* - Image cropping based on transform matrices
* - CSS variable generation for image dimensions
*
* @returns Array of local file paths for successfully downloaded images
*/
async downloadImages(
fileKey: string,
localPath: string,
items: Array<{
imageRef?: string;
nodeId?: string;
fileName: string;
needsCropping?: boolean;
cropTransform?: any;
requiresImageDimensions?: boolean;
}>,
options: { pngScale?: number; svgOptions?: SvgOptions } = {},
): Promise<ImageProcessingResult[]> {
if (items.length === 0) return [];
const { pngScale = 2, svgOptions } = options;
const downloadPromises: Promise<ImageProcessingResult[]>[] = [];
// Separate items by type
const imageFills = items.filter(
(item): item is typeof item & { imageRef: string } => !!item.imageRef,
);
const renderNodes = items.filter(
(item): item is typeof item & { nodeId: string } => !!item.nodeId,
);
// Download image fills with processing
if (imageFills.length > 0) {
const fillUrls = await this.getImageFillUrls(fileKey);
const fillDownloads = imageFills
.map(({ imageRef, fileName, needsCropping, cropTransform, requiresImageDimensions }) => {
const imageUrl = fillUrls[imageRef];
return imageUrl
? downloadAndProcessImage(
fileName,
localPath,
imageUrl,
needsCropping,
cropTransform,
requiresImageDimensions,
)
: null;
})
.filter((promise): promise is Promise<ImageProcessingResult> => promise !== null);
if (fillDownloads.length > 0) {
downloadPromises.push(Promise.all(fillDownloads));
}
}
// Download rendered nodes with processing
if (renderNodes.length > 0) {
const pngNodes = renderNodes.filter((node) => !node.fileName.toLowerCase().endsWith(".svg"));
const svgNodes = renderNodes.filter((node) => node.fileName.toLowerCase().endsWith(".svg"));
// Download PNG renders
if (pngNodes.length > 0) {
const pngUrls = await this.getNodeRenderUrls(
fileKey,
pngNodes.map((n) => n.nodeId),
"png",
{ pngScale },
);
const pngDownloads = pngNodes
.map(({ nodeId, fileName, needsCropping, cropTransform, requiresImageDimensions }) => {
const imageUrl = pngUrls[nodeId];
return imageUrl
? downloadAndProcessImage(
fileName,
localPath,
imageUrl,
needsCropping,
cropTransform,
requiresImageDimensions,
)
: null;
})
.filter((promise): promise is Promise<ImageProcessingResult> => promise !== null);
if (pngDownloads.length > 0) {
downloadPromises.push(Promise.all(pngDownloads));
}
}
// Download SVG renders
if (svgNodes.length > 0) {
const svgUrls = await this.getNodeRenderUrls(
fileKey,
svgNodes.map((n) => n.nodeId),
"svg",
{ svgOptions },
);
const svgDownloads = svgNodes
.map(({ nodeId, fileName, needsCropping, cropTransform, requiresImageDimensions }) => {
const imageUrl = svgUrls[nodeId];
return imageUrl
? downloadAndProcessImage(
fileName,
localPath,
imageUrl,
needsCropping,
cropTransform,
requiresImageDimensions,
)
: null;
})
.filter((promise): promise is Promise<ImageProcessingResult> => promise !== null);
if (svgDownloads.length > 0) {
downloadPromises.push(Promise.all(svgDownloads));
}
}
}
const results = await Promise.all(downloadPromises);
return results.flat();
}
/**
* Get file meta data
*/
async getFileMeta(fileKey: string): Promise<GetFileMetaResponse> {
const endpoint = `/files/${fileKey}/meta`;
const response = await this.request<GetFileMetaResponse>(endpoint);
return response;
}
/**
* Get raw Figma API response for a file (for use with flexible extractors)
*/
async getRawFile(fileKey: string, depth?: number | null): Promise<GetFileResponse> {
const endpoint = `/files/${fileKey}${depth ? `?depth=${depth}` : ""}`;
Logger.log(`Retrieving raw Figma file: ${fileKey} (depth: ${depth ?? "default"})`);
const response = await this.request<GetFileResponse>(endpoint);
writeLogs("figma-raw.json", response);
return response;
}
/**
* Get raw Figma API response for specific nodes (for use with flexible extractors)
*/
async getRawNode(
fileKey: string,
nodeId: string,
depth?: number | null,
): Promise<GetFileNodesResponse> {
const endpoint = `/files/${fileKey}/nodes?ids=${nodeId}${depth ? `&depth=${depth}` : ""}`;
Logger.log(
`Retrieving raw Figma node: ${nodeId} from ${fileKey} (depth: ${depth ?? "default"})`,
);
const response = await this.request<GetFileNodesResponse>(endpoint);
writeLogs("figma-raw.json", response);
return response;
}
}