figma.ts 7.68 KB
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;
};