-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfigma.js
More file actions
482 lines (411 loc) · 16.9 KB
/
Copy pathfigma.js
File metadata and controls
482 lines (411 loc) · 16.9 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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
import express from 'express';
import axios from 'axios';
import dotenv from 'dotenv';
import cors from 'cors';
import FormData from "form-data";
dotenv.config();
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(cors());
const {
FIGMA_ACCESS_TOKEN,
CONTENT_HUB_URL,
API_SECRET_KEY,
} = process.env;
const FIGMA_API_URL = 'https://api.figma.com/v1';
// ─────────────────────────────────────────────
// ROOT
// ─────────────────────────────────────────────
app.get('/', (req, res) => {
res.json({
status: '✅ Figma → Content Hub Middleware is running',
endpoints: {
import: 'POST /api/figma/import',
health: 'GET /api/figma/health',
}
});
});
// ─────────────────────────────────────────────
// Get Content Hub Token
// ─────────────────────────────────────────────
async function getContentHubToken(contentHubBaseUrl) {
try {
console.log('🔐 Authenticating with Content Hub...');
const response = await axios.post(
`${contentHubBaseUrl}/api/authenticate`,
{
user_name: "Uday.Sanghani@bpggroup.com",
password: "Uday@123",
},
{ headers: { 'Content-Type': 'application/json' } }
);
const token = response.data.token || response.data.access_token;
if (!token) {
console.error('❌ Token extraction failed:', JSON.stringify(response.data));
return null;
}
console.log('✅ Content Hub token obtained');
return token;
} catch (err) {
console.error('❌ Content Hub auth failed:', err.response?.status, err.message);
return null;
}
}
// ─────────────────────────────────────────────
// Fetch Figma file + export images
// ─────────────────────────────────────────────
async function getFigmaExports(fileId, nodeId = null) {
try {
console.log(`🎨 Fetching Figma file: ${fileId}`);
const fileResponse = await axios.get(
`${FIGMA_API_URL}/files/${fileId}`,
{
headers: { 'X-Figma-Token': FIGMA_ACCESS_TOKEN }
}
);
const { name: fileName, lastModified, document } = fileResponse.data;
console.log('✅ File fetched:', fileName);
let nodesToExport = [];
const nodeNames = {}; // nodeId → human-readable name
if (nodeId) {
// If specific node ID provided, use it — look up its name
nodesToExport = [nodeId];
nodeNames[nodeId] = findNodeName(document, nodeId) || `Node_${nodeId}`;
console.log('✅ Using specific node ID:', nodeId, '→', nodeNames[nodeId]);
} else {
// Strategy 1: Look for FRAME, COMPONENT, BOARD at top level
const topLevel = document.children.filter(n =>
['FRAME', 'COMPONENT', 'BOARD', 'SECTION'].includes(n.type)
);
topLevel.forEach(n => { nodeNames[n.id] = n.name; });
nodesToExport = topLevel.map(n => n.id);
console.log('✅ Top-level exportable nodes found:', nodesToExport.length);
// Strategy 2: If no frames, look inside CANVAS/SECTION/GROUP nodes
if (nodesToExport.length === 0) {
console.log('⚠️ No top-level frames found, looking inside CANVAS/SECTION nodes...');
document.children.forEach(parent => {
console.log(` 📂 Checking "${parent.name}" (type: ${parent.type})`);
if (parent.children && Array.isArray(parent.children)) {
console.log(` - Has ${parent.children.length} children`);
parent.children.forEach(n => {
const exportableTypes = ['FRAME', 'COMPONENT', 'GROUP', 'BOARD', 'RECTANGLE', 'TEXT', 'IMAGE'];
if (exportableTypes.includes(n.type)) {
console.log(` ✓ Found "${n.name}" (${n.type})`);
nodeNames[n.id] = n.name;
nodesToExport.push(n.id);
}
});
}
});
}
// Strategy 3: Last resort - export all top-level nodes
if (nodesToExport.length === 0) {
console.log('⚠️ No exportable children found, exporting all top-level nodes...');
document.children.forEach(n => {
nodeNames[n.id] = n.name;
nodesToExport.push(n.id);
});
}
}
console.log('✅ Total nodes to export:', nodesToExport.length);
if (nodesToExport.length === 0) {
console.warn('⚠️ No nodes found to export');
return { fileName, lastModified, exports: {}, nodeNames: {} };
}
// Get export URLs
console.log('📤 Requesting exports for nodes:', nodesToExport);
const exportResponse = await axios.get(
`${FIGMA_API_URL}/files/${fileId}/images`,
{
params: {
ids: nodesToExport.join(','),
format: 'png',
scale: 2,
},
headers: { 'X-Figma-Token': FIGMA_ACCESS_TOKEN }
}
);
console.log('✅ Export response received');
// IMPORTANT: Figma API returns images under .meta.images, not directly under .images
const images = exportResponse.data.meta?.images || exportResponse.data.images;
console.log('📊 Images in response:', images ? Object.keys(images).length : 'undefined');
if (!images || Object.keys(images).length === 0) {
console.error('❌ No images in Figma response:', JSON.stringify(exportResponse.data, null, 2));
return { fileName, lastModified, exports: {}, nodeNames: {} };
}
return {
fileName,
lastModified,
exports: images,
nodeNames,
};
} catch (err) {
console.error('❌ Figma fetch failed:', err.response?.status, err.message);
if (err.response?.data) {
console.error(' Response:', JSON.stringify(err.response.data, null, 2));
}
throw err;
}
}
/**
* Recursively searches the Figma document tree for a node by its ID,
* and returns its human-readable name.
*/
function findNodeName(node, targetId) {
if (node.id === targetId) return node.name;
if (node.children) {
for (const child of node.children) {
const found = findNodeName(child, targetId);
if (found) return found;
}
}
return null;
}
// ─────────────────────────────────────────────
// Upload image buffer to Content Hub
// Uses the upload-session flow (v2.0/upload) which
// is the proven working approach for this CH instance.
// ─────────────────────────────────────────────
async function uploadToContentHub(imageBuffer, fileName, contentHubBaseUrl, token) {
try {
console.log(`📤 Uploading: ${fileName}`);
// STEP 1 — Request Upload URL
const createUploadResponse = await axios.post(
`${contentHubBaseUrl}/api/v2.0/upload`,
{
file_name: fileName,
file_size: imageBuffer.length,
upload_configuration: {
name: "AssetUploadConfiguration"
},
action: {
name: "NewAsset"
}
},
{
headers: {
'X-Auth-Token': token,
"Content-Type": "application/json"
}
}
);
console.log("✅ Upload session created");
const uploadUrl = createUploadResponse.headers.location;
if (!uploadUrl) {
throw new Error("No upload URL returned");
}
// STEP 2 — Upload File
const formData = new FormData();
formData.append("file", imageBuffer, fileName);
// The location header may be absolute or relative depending on the CH version
const binaryUploadUrl = uploadUrl.startsWith('http')
? uploadUrl
: `${contentHubBaseUrl}${uploadUrl}`;
await axios.post(
binaryUploadUrl,
formData,
{
headers: {
Authorization: `Bearer ${token}`,
...formData.getHeaders()
},
maxBodyLength: Infinity
}
);
console.log("✅ Binary uploaded");
// STEP 3 — Finalize Upload
const finalizeResponse = await axios.post(
`${contentHubBaseUrl}/api/v2.0/upload/finalize`,
createUploadResponse.data,
{
headers: {
'X-Auth-Token': token,
"Content-Type": "application/json"
}
}
);
console.log("✅ Upload finalized");
return finalizeResponse.data.asset_id;
} catch (err) {
console.error(
"❌ Upload failed:",
err.response?.status,
err.response?.data || err.message
);
console.error("URL:", err.config?.url);
throw err;
}
}
// ─────────────────────────────────────────────
// Extract file ID (and optional node ID) from a Figma URL
//
// Handles formats like:
// https://www.figma.com/design/{fileId}/{slug}
// https://www.figma.com/file/{fileId}/{slug}?node-id=1-2
// https://www.figma.com/proto/{fileId}/{slug}?node-id=1%3A2
// ─────────────────────────────────────────────
function parseFigmaUrl(url) {
try {
const parsed = new URL(url);
const segments = parsed.pathname.split('/').filter(Boolean);
const typeIndex = segments.findIndex(s => ['design', 'file', 'proto'].includes(s));
if (typeIndex === -1 || typeIndex + 1 >= segments.length) {
return null;
}
const fileId = segments[typeIndex + 1];
if (!fileId || fileId.length < 10) return null;
const nodeId = parsed.searchParams.get('node-id') || null;
return { fileId, nodeId };
} catch {
return null;
}
}
// ─────────────────────────────────────────────
// GET — test connection
// ─────────────────────────────────────────────
app.get('/api/figma/import', (req, res) => {
res.json({ status: '✅ Figma import endpoint is ready. Use POST to import.' });
});
// ─────────────────────────────────────────────
// MAIN ROUTE: Import Figma file to Content Hub
// POST /api/figma/import
// ─────────────────────────────────────────────
app.post('/api/figma/import', async (req, res) => {
console.log('📥 Incoming Figma import request');
console.log('Body:', JSON.stringify(req.body));
// Security check
const apiKey = req.headers['x-api-key'];
if (!apiKey || apiKey !== API_SECRET_KEY) {
console.error('❌ Unauthorized - invalid x-api-key');
return res.status(401).json({ error: 'Unauthorized' });
}
if (!FIGMA_ACCESS_TOKEN) {
return res.status(500).json({ error: 'FIGMA_ACCESS_TOKEN not configured' });
}
// ─────────────────────────────────────────────
// Content Hub triggers wrap "Values" inside a
// `context` object alongside `saveEntityMessage`.
// Fall back to context if top-level fields are absent.
// ─────────────────────────────────────────────
let { figmaFileId, figmaNodeId, figmaUrl } = req.body;
if (!figmaUrl) figmaUrl = req.body.context?.figmaUrl;
if (!figmaFileId) figmaFileId = req.body.context?.figmaFileId;
if (!figmaNodeId) figmaNodeId = req.body.context?.figmaNodeId;
console.log('🔍 Resolved figmaUrl:', figmaUrl || '(none)');
console.log('🔍 Resolved figmaFileId:', figmaFileId || '(none)');
// Accept either a raw file ID or a full Figma URL
if (!figmaFileId && figmaUrl) {
const parsed = parseFigmaUrl(figmaUrl);
if (!parsed) {
return res.status(400).json({
error: 'Invalid Figma URL',
hint: 'Provide a valid Figma URL like https://www.figma.com/design/{fileId}/{slug}'
});
}
figmaFileId = parsed.fileId;
if (parsed.nodeId && !figmaNodeId) {
figmaNodeId = parsed.nodeId;
}
console.log('🔗 Parsed Figma URL → fileId:', figmaFileId, 'nodeId:', figmaNodeId || '(none)');
}
if (!figmaFileId) {
return res.status(400).json({
error: 'figmaFileId or figmaUrl required in body',
hint: 'Send { "figmaFileId": "your-file-id" } or { "figmaUrl": "https://www.figma.com/design/..." }'
});
}
console.log('✅ File ID:', figmaFileId);
console.log('✅ Node ID:', figmaNodeId || '(all frames)');
try {
// Step 1: Get Figma exports
const figmaData = await getFigmaExports(figmaFileId, figmaNodeId);
if (Object.keys(figmaData.exports).length === 0) {
return res.status(400).json({
error: 'No exportable frames or components found in Figma file',
hint: 'Ensure your Figma file has FRAME or COMPONENT elements at the top level'
});
}
// Step 2: Authenticate with Content Hub
const chToken = await getContentHubToken(CONTENT_HUB_URL);
if (!chToken) {
return res.status(500).json({ error: 'Content Hub authentication failed' });
}
// Step 3: For each exported image, download + upload to CH
const uploadedAssets = [];
const failedAssets = [];
const nameCounts = {}; // track duplicates: "Color" → 3
let imageIndex = 0;
for (const [nodeId, exportUrl] of Object.entries(figmaData.exports)) {
imageIndex++;
try {
console.log(`📥 Downloading Figma export: ${exportUrl}`);
const imageResponse = await axios.get(exportUrl, {
responseType: 'arraybuffer',
timeout: 30000,
});
const imageBuffer = Buffer.from(imageResponse.data);
// Build the file name from the Figma node name
// If the export key doesn't match any known node (Figma sometimes
// returns version hashes instead of node IDs), fall back to a counter.
const rawName = figmaData.nodeNames?.[nodeId];
const displayName = rawName || `${figmaData.fileName} ${imageIndex}`;
// Handle duplicate names (e.g. 6 "Color" rectangles → Color, Color 2, …)
const count = nameCounts[displayName] = (nameCounts[displayName] || 0) + 1;
const dedupedName = count > 1 ? `${displayName} ${count}` : displayName;
// Sanitise: remove chars unsafe for filenames, collapse spaces
const safeName = dedupedName
.replace(/[<>:"/\\|?*]/g, '')
.replace(/\s+/g, ' ')
.trim();
const fileName = `${safeName}.png`;
const assetId = await uploadToContentHub(
imageBuffer,
fileName,
CONTENT_HUB_URL,
chToken
);
uploadedAssets.push({ nodeId, assetId, fileName });
console.log(`✅ Successfully uploaded: ${fileName}`);
} catch (err) {
console.error(`⚠️ Failed to upload ${nodeId}:`, err.message);
failedAssets.push({ nodeId, error: err.message });
}
}
res.json({
success: true,
fileName: figmaData.fileName,
uploadedCount: uploadedAssets.length,
failedCount: failedAssets.length,
assets: uploadedAssets,
failed: failedAssets.length > 0 ? failedAssets : undefined,
message: `Successfully imported ${uploadedAssets.length} assets from Figma${failedAssets.length > 0 ? ` (${failedAssets.length} failed)` : ''}`,
timestamp: new Date().toISOString(),
});
} catch (err) {
console.error('❌ Figma import failed:', err.message);
res.status(500).json({
error: 'Failed to import from Figma',
details: err.message,
});
}
});
// ─────────────────────────────────────────────
// HEALTH CHECK
// ─────────────────────────────────────────────
app.get('/api/figma/health', (req, res) => {
console.log('✅ Figma health check');
res.json({
status: '✅ healthy',
service: 'Figma → Content Hub Middleware',
timestamp: new Date().toISOString(),
});
});
// ─────────────────────────────────────────────
// ERROR HANDLING
// ─────────────────────────────────────────────
app.use((err, req, res, next) => {
console.error('❌ Unhandled error:', err);
res.status(500).json({ error: 'Internal server error', message: err.message });
});
export default app;