url-parser.ts 2.67 KB
/**
 * Parsed Figma URL information.
 *
 * Shared between the orchestration backend (apps/server) and the web UI so both
 * validate Figma links with the exact same logic. The implementation is pure
 * (only `URL` / `decodeURIComponent`) and has no dependency on the `coderio`
 * engine, so it is safe to bundle into the browser without leaking native deps.
 */
export interface FigmaUrlInfo {
    /** The ID of the Figma file */
    fileId: string | null;
    /** The name of the Figma file */
    name: string;
    /** The ID of the Figma node */
    nodeId: string | null;
    /** The name of the project */
    projectName: string | null;
}

/**
 * Parse Figma URL and extract fileId, name, and nodeId in one pass.
 * @example
 * parseFigmaUrl('https://www.figma.com/design/aONcu8L82l1PdcT304Q8Za/Intern?node-id=0-495')
 * // Returns: { fileId: 'aONcu8L82l1PdcT304Q8Za', name: 'intern', nodeId: '0-495' }
 */
export const parseFigmaUrl = (url: string): FigmaUrlInfo => {
    let fileId: string | null = null;
    let name = 'untitled';
    let nodeId: string | null = null;

    try {
        const urlObj = new URL(decodeURIComponent(url));
        const pathParts = urlObj.pathname.split('/').filter(Boolean);
        if (pathParts.length >= 3) {
            fileId = pathParts[pathParts.length - 2] || null;
            const fileName = pathParts[pathParts.length - 1];
            name = slugifyFigmaName(fileName ?? 'untitled');
            name = name.length > 20 ? name.substring(0, 20) : name;
        }

        nodeId = urlObj.searchParams.get('node-id') || null;
        nodeId = nodeId ? nodeId.replace(/-/g, ':') : null;
    } catch {}

    if (!fileId || !nodeId) {
        throw new Error('Invalid Figma URL');
    }

    return { fileId, name, nodeId, projectName: `${name}_${nodeId.replace(/:/g, '_')}` };
};

/**
 * Turn a Figma file name into a filesystem / package-safe slug.
 *
 * The Figma URL is already percent-decoded once by `new URL(decodeURIComponent(url))`,
 * but some URLs are double-encoded (e.g. `%25E3%2580%2590` instead of `%E3%80%90`).
 * We fully decode the name first, then keep unicode letters/digits and replace every
 * other character (spaces, brackets, `%`, etc.) with a single underscore.
 */
function slugifyFigmaName(raw: string): string {
    let decoded = raw;
    try {
        let prev: string;
        do {
            prev = decoded;
            decoded = decodeURIComponent(prev);
        } while (decoded !== prev);
    } catch {
        /* leave as the last successfully decoded value */
    }

    const slug = decoded
        .normalize('NFKC')
        .replace(/[^\p{L}\p{N}]+/gu, '_')
        .replace(/^_+|_+$/g, '')
        .toLowerCase();

    return slug || 'untitled';
}