zp-figma-converter
Version:
Convert Figma designs to various code formats
209 lines • 8.61 kB
JavaScript
;
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.FigmaApi = void 0;
const axios_1 = __importDefault(require("axios"));
const dotenv = __importStar(require("dotenv"));
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const file_utils_1 = require("../utils/file-utils");
// Load .env file
dotenv.config();
/**
* Service for Figma API
*/
class FigmaApi {
constructor(apiKey) {
this.apiKey = apiKey;
this.baseUrl = process.env.FIGMA_API_BASE_URL || 'https://api.figma.com/v1';
if (!this.apiKey) {
throw new Error('Figma access token not found. Please set FIGMA_API_KEY in .env file');
}
this.apiClient = axios_1.default.create({
baseURL: this.baseUrl,
headers: {
'X-Figma-Token': this.apiKey
}
});
}
/**
* Get information of a Figma file
* @param fileKey Key of Figma file
* @returns Information of Figma file
*/
getFile(fileKey) {
return __awaiter(this, void 0, void 0, function* () {
try {
const response = yield this.apiClient.get(`/files/${fileKey}`);
return response.data;
}
catch (error) {
if (axios_1.default.isAxiosError(error)) {
throw new Error(`Failed to get Figma file: ${error.message}`);
}
throw error;
}
});
}
/**
* Get information of a specific node in a Figma file
* @param fileKey Key of Figma file
* @param nodeId ID of node
* @returns Information of node
*/
getNode(fileKey, nodeId) {
return __awaiter(this, void 0, void 0, function* () {
nodeId = this.normalizeNodeId(nodeId);
console.debug(`Getting node ${nodeId} from file ${fileKey}`);
try {
const response = yield this.apiClient.get(`/files/${fileKey}/nodes?ids=${nodeId}`);
if (!response.data.nodes[nodeId]) {
throw new Error(`Node ${nodeId} not found in file ${fileKey}`);
}
return response.data.nodes[nodeId].document;
}
catch (error) {
if (axios_1.default.isAxiosError(error)) {
throw new Error(`Failed to get Figma node: ${error.message}`);
}
throw error;
}
});
}
/**
* Get image URLs from nodes in a Figma file
* @param fileKey Key of Figma file
* @param nodeIds List of IDs of nodes
* @param format Format of image (png, svg, jpg...)
* @param scale Scale of image
* @returns List of image URLs
*/
getImageUrls(fileKey_1, nodeIds_1) {
return __awaiter(this, arguments, void 0, function* (fileKey, nodeIds, format = 'png', scale = 1) {
try {
const idsParam = nodeIds.join(',');
const response = yield this.apiClient.get(`/images/${fileKey}?ids=${idsParam}&format=${format}&scale=${scale}`);
return response.data.images;
}
catch (error) {
if (axios_1.default.isAxiosError(error)) {
throw new Error(`Failed to get image URLs: ${error.message}`);
}
throw error;
}
});
}
/**
* Download image from a URL and save to local
* @param imageUrl URL of image
* @param outputPath Path of image
* @returns Path of image
*/
downloadImage(imageUrl, outputPath) {
return __awaiter(this, void 0, void 0, function* () {
try {
// Ensure directory exists
const directory = path.dirname(outputPath);
(0, file_utils_1.createFolderIfNotExists)(directory);
// Download image
const response = yield axios_1.default.get(imageUrl, { responseType: 'arraybuffer' });
const buffer = Buffer.from(response.data, 'binary');
// Save image
fs.writeFileSync(outputPath, buffer);
return outputPath;
}
catch (error) {
if (axios_1.default.isAxiosError(error)) {
throw new Error(`Failed to download image: ${error.message}`);
}
throw error;
}
});
}
/**
* Download multiple images from Figma
* @param fileKey Key of Figma file
* @param nodeIds List of IDs of nodes and corresponding file names
* @param format Format of image
* @returns List of paths to images
*/
downloadImages(fileKey_1, nodeIds_1) {
return __awaiter(this, arguments, void 0, function* (fileKey, nodeIds, format = 'png') {
try {
console.debug(`Downloading images for file ${fileKey}`);
// Get URLs of images
const ids = nodeIds.map(node => node.id);
const imageUrls = yield this.getImageUrls(fileKey, ids, format);
// Download and save each image
const downloadPromises = nodeIds.map((node) => __awaiter(this, void 0, void 0, function* () {
const imageUrl = imageUrls[node.id];
if (!imageUrl) {
// Log warning instead of throwing error
console.warn(`Image URL for node ${node.id} not found. Skipping download.`);
return null; // Return null for failed downloads
}
const outputPath = `${node.filePath}.${format}`;
return this.downloadImage(imageUrl, outputPath);
}));
// Filter out null results (failed downloads)
const results = yield Promise.all(downloadPromises);
return results.filter(result => result !== null);
}
catch (error) {
if (axios_1.default.isAxiosError(error)) {
throw new Error(`Failed to download images: ${error.message}`);
}
throw error;
}
});
}
normalizeNodeId(nodeId) {
return nodeId.split('-').join(':');
}
}
exports.FigmaApi = FigmaApi;
//# sourceMappingURL=figma-api.js.map