figma.ts
7.68 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
import { FigmaFrameInfo, FigmaImageFormat, FigmaColorObject } from '../../types/figma-types';
import { get } from '../../utils/axios';
import { logger } from '../../utils/logger';
/**
* Retry an async request on transient / rate-limit errors with exponential
* backoff. The Figma REST API (especially the image-export endpoint) enforces
* fairly strict rate limits and returns HTTP 429; without retry a single
* throttled request aborts the whole generation (the thumbnail fetch is
* mandatory). We retry on 429 and 5xx, honouring a `Retry-After` header if the
* server sends one.
*/
const FIGMA_MAX_RETRIES = 5;
const FIGMA_BASE_BACKOFF_MS = 1000;
// Ceiling for a single retry wait on a *transient* 429. Figma occasionally
// returns an absurd `Retry-After` (e.g. 343424 seconds ≈ 95h) which, if honoured
// literally, would stall the whole generation "forever". We clamp every wait to
// this value for genuine transient throttling.
const FIGMA_MAX_BACKOFF_MS = 30000;
// Above this, the `Retry-After` is not transient throttling — it is a long
// cooldown ban Figma imposes after repeated abuse. Retrying is pointless and
// would just burn minutes; we fail fast with an actionable error instead.
const FIGMA_BAN_THRESHOLD_MS = 300000; // 5 minutes
async function withFigmaRetry<T>(label: string, fn: () => Promise<T>): Promise<T> {
let lastError: unknown;
for (let attempt = 0; attempt <= FIGMA_MAX_RETRIES; attempt++) {
try {
return await fn();
} catch (error) {
lastError = error;
const resp = (error as { response?: { status?: number; headers?: Record<string, string> } })?.response;
const status = resp?.status;
const retryAfterSec = Number(resp?.headers?.['retry-after']);
const retryAfterMs = Number.isFinite(retryAfterSec) && retryAfterSec > 0 ? retryAfterSec * 1000 : 0;
// Long cooldown ban: Figma blocks the token for hours/days. Surface a
// clear, actionable message instead of pointlessly retrying.
if (status === 429 && retryAfterMs >= FIGMA_BAN_THRESHOLD_MS) {
const resetAt = new Date(Date.now() + retryAfterMs).toISOString();
throw new Error(
`Figma API rate-limit ban (HTTP 429). The Figma file (or token) is blocked until ~${resetAt} ` +
`(Figma returned Retry-After: ${retryAfterSec}s ≈ ${(retryAfterMs / 3600000).toFixed(1)}h). ` +
`Fix: duplicate the Figma file to get a new fileId (fresh rate-limit bucket), or wait for the cooldown to expire.`,
);
}
const isRetryable =
status === 429 || status === 500 || status === 502 || status === 503 || status === 504 || status === undefined;
if (!isRetryable || attempt === FIGMA_MAX_RETRIES) {
throw error;
}
// Honour `Retry-After` (HTTP seconds) when present, but clamp it to
// FIGMA_MAX_BACKOFF_MS so a runaway value never hangs the run.
const exponentialMs = FIGMA_BASE_BACKOFF_MS * Math.pow(2, attempt);
const delayMs = Math.min(retryAfterMs > 0 ? retryAfterMs : exponentialMs, FIGMA_MAX_BACKOFF_MS);
logger.printWarnLog(
`[figma] ${label} throttled (${status ?? 'network'}), retrying in ${Math.round(delayMs)}ms ` +
`(attempt ${attempt + 1}/${FIGMA_MAX_RETRIES})`,
);
await new Promise(resolve => setTimeout(resolve, delayMs));
}
}
throw lastError;
}
/**
* Fetch Figma nodes by fileId and nodeId
* @param fileId - Figma file ID
* @param nodeId - Figma node ID
* @param token - Figma API token
* @returns Figma frame information
*/
export const fetchFigmaNode = async (fileId: string, nodeId: string, token: string): Promise<FigmaFrameInfo | undefined> => {
const url = `https://api.figma.com/v1/files/${fileId}/nodes?ids=${nodeId}`;
try {
const data = await withFigmaRetry('fetch node', () =>
get<{ nodes: Record<string, { document: FigmaFrameInfo }> }>(url, {
headers: {
'X-Figma-Token': token,
},
}),
);
// format node id to match the format in the response
const resData = data.nodes?.[nodeId];
return resData?.document;
} catch (error) {
const resp = (error as { response?: { status?: number; data?: unknown } })?.response;
const status = resp?.status;
let msg = error instanceof Error ? error.message : 'Unknown error';
// Figma returns a clear reason in the response body for auth failures
// (e.g. {"status":403,"err":"Token expired"}). Surface it so the user
// isn't left guessing why a 403 happened.
if (status === 403) {
const body = resp?.data as { err?: string; message?: string } | undefined;
const figmaErr = body?.err || body?.message;
msg =
`Figma 返回 403${figmaErr ? `(${figmaErr})` : ''}:通常是 Figma 个人访问令牌已过期或无效。` +
` 请在 Figma 账号设置重新生成 token,更新 ~/.coderio/config.yaml 的 figma.token,并重启后端后再试`;
}
logger.printErrorLog(`获取 Figma 节点失败:${msg}`);
return undefined;
}
};
/**
* Fetch Figma image by fileId and nodeId
* @param fileId - Figma file ID
* @param nodeIds - Figma node ID, multiple node ids can be passed separated by commas
* @param token - Figma API token
* @param format - Figma image format
* @returns Figma image
*/
export const fetchFigmaImages = async (
fileId: string,
nodeIds: string,
token: string,
format?: FigmaImageFormat
): Promise<Record<string, string>> => {
const url = `https://api.figma.com/v1/images/${fileId}`;
try {
const data = await withFigmaRetry('fetch images', () =>
get<{ images: Record<string, string> }>(url, {
headers: {
'X-Figma-Token': token,
},
params: {
ids: nodeIds,
format: format || 'png',
},
}),
);
const images = data.images || {};
// format node id to match the format from response to request
return Object.fromEntries(Object.entries(images));
} catch (error) {
logger.printErrorLog(`获取 Figma 图片失败:${error instanceof Error ? error.message : 'Unknown error'}`);
return {};
}
};
/**
* Clean Figma node and children. Remove invisible nodes and children.
* @param node - Figma node or children
* @returns Cleaned Figma node or children. If the node is invisible, return null.
*/
export const cleanFigma = (node: FigmaFrameInfo): FigmaFrameInfo | undefined => {
// if node is invisible, return undefined
if (node.visible === false) {
return undefined;
}
// if node has children, recursively clean each child
if (node.children && Array.isArray(node.children)) {
node.children = node.children
.map(child => cleanFigma(child)) // recursively clean each child
.filter(child => child !== undefined); // filter out invisible nodes
}
return node;
};
/**
* Check if node has border
* @param node - Figma node
* @returns True if node has border, false otherwise
*/
export const checkBorder = (node: FigmaFrameInfo): boolean => {
const strokes = node.strokes;
const strokeWeight = node.strokeWeight;
if (!strokes || !strokes.length || !strokeWeight) return false;
const visibleStrokes = strokes.filter((s: FigmaColorObject) => s.visible !== false);
if (visibleStrokes.length === 0) return false;
return true;
};