{"repo_name": "cursor-talk-to-figma-mcp", "file_name": "/cursor-talk-to-figma-mcp/src/cursor_mcp_plugin/setcharacters.js", "inference_info": {"prefix_code": "", "suffix_code": "\nexport const setCharacters = async (node, characters, options) => {\n const fallbackFont = options?.fallbackFont || {\n family: \"Roboto\",\n style: \"Regular\",\n };\n try {\n if (node.fontName === figma.mixed) {\n if (options?.smartStrategy === \"prevail\") {\n const fontHashTree = {};\n for (let i = 1; i < node.characters.length; i++) {\n const charFont = node.getRangeFontName(i - 1, i);\n const key = `${charFont.family}::${charFont.style}`;\n fontHashTree[key] = fontHashTree[key] ? fontHashTree[key] + 1 : 1;\n }\n const prevailedTreeItem = Object.entries(fontHashTree).sort(\n (a, b) => b[1] - a[1]\n )[0];\n const [family, style] = prevailedTreeItem[0].split(\"::\");\n const prevailedFont = {\n family,\n style,\n };\n await figma.loadFontAsync(prevailedFont);\n node.fontName = prevailedFont;\n } else if (options?.smartStrategy === \"strict\") {\n return setCharactersWithStrictMatchFont(node, characters, fallbackFont);\n } else if (options?.smartStrategy === \"experimental\") {\n return setCharactersWithSmartMatchFont(node, characters, fallbackFont);\n } else {\n const firstCharFont = node.getRangeFontName(0, 1);\n await figma.loadFontAsync(firstCharFont);\n node.fontName = firstCharFont;\n }\n } else {\n await figma.loadFontAsync({\n family: node.fontName.family,\n style: node.fontName.style,\n });\n }\n } catch (err) {\n console.warn(\n `Failed to load \"${node.fontName[\"family\"]} ${node.fontName[\"style\"]}\" font and replaced with fallback \"${fallbackFont.family} ${fallbackFont.style}\"`,\n err\n );\n await figma.loadFontAsync(fallbackFont);\n node.fontName = fallbackFont;\n }\n try {\n node.characters = characters;\n return true;\n } catch (err) {\n console.warn(`Failed to set characters. Skipped.`, err);\n return false;\n }\n};\n\nconst setCharactersWithStrictMatchFont = async (\n node,\n characters,\n fallbackFont\n) => {\n const fontHashTree = {};\n for (let i = 1; i < node.characters.length; i++) {\n const startIdx = i - 1;\n const startCharFont = node.getRangeFontName(startIdx, i);\n const startCharFontVal = `${startCharFont.family}::${startCharFont.style}`;\n while (i < node.characters.length) {\n i++;\n const charFont = node.getRangeFontName(i - 1, i);\n if (startCharFontVal !== `${charFont.family}::${charFont.style}`) {\n break;\n }\n }\n fontHashTree[`${startIdx}_${i}`] = startCharFontVal;\n }\n await figma.loadFontAsync(fallbackFont);\n node.fontName = fallbackFont;\n node.characters = characters;\n console.log(fontHashTree);\n await Promise.all(\n Object.keys(fontHashTree).map(async (range) => {\n console.log(range, fontHashTree[range]);\n const [start, end] = range.split(\"_\");\n const [family, style] = fontHashTree[range].split(\"::\");\n const matchedFont = {\n family,\n style,\n };\n await figma.loadFontAsync(matchedFont);\n return node.setRangeFontName(Number(start), Number(end), matchedFont);\n })\n );\n return true;\n};\n\nconst getDelimiterPos = (str, delimiter, startIdx = 0, endIdx = str.length) => {\n const indices = [];\n let temp = startIdx;\n for (let i = startIdx; i < endIdx; i++) {\n if (\n str[i] === delimiter &&\n i + startIdx !== endIdx &&\n temp !== i + startIdx\n ) {\n indices.push([temp, i + startIdx]);\n temp = i + startIdx + 1;\n }\n }\n temp !== endIdx && indices.push([temp, endIdx]);\n return indices.filter(Boolean);\n};\n\nconst buildLinearOrder = (node) => {\n const fontTree = [];\n const newLinesPos = getDelimiterPos(node.characters, \"\\n\");\n newLinesPos.forEach(([newLinesRangeStart, newLinesRangeEnd], n) => {\n const newLinesRangeFont = node.getRangeFontName(\n newLinesRangeStart,\n newLinesRangeEnd\n );\n if (newLinesRangeFont === figma.mixed) {\n const spacesPos = getDelimiterPos(\n node.characters,\n \" \",\n newLinesRangeStart,\n newLinesRangeEnd\n );\n spacesPos.forEach(([spacesRangeStart, spacesRangeEnd], s) => {\n const spacesRangeFont = node.getRangeFontName(\n spacesRangeStart,\n spacesRangeEnd\n );\n if (spacesRangeFont === figma.mixed) {\n const spacesRangeFont = node.getRangeFontName(\n spacesRangeStart,\n spacesRangeStart[0]\n );\n fontTree.push({\n start: spacesRangeStart,\n delimiter: \" \",\n family: spacesRangeFont.family,\n style: spacesRangeFont.style,\n });\n } else {\n fontTree.push({\n start: spacesRangeStart,\n delimiter: \" \",\n family: spacesRangeFont.family,\n style: spacesRangeFont.style,\n });\n }\n });\n } else {\n fontTree.push({\n start: newLinesRangeStart,\n delimiter: \"\\n\",\n family: newLinesRangeFont.family,\n style: newLinesRangeFont.style,\n });\n }\n });\n return fontTree\n .sort((a, b) => +a.start - +b.start)\n .map(({ family, style, delimiter }) => ({ family, style, delimiter }));\n};\n\nconst setCharactersWithSmartMatchFont = async (\n node,\n characters,\n fallbackFont\n) => {\n const rangeTree = buildLinearOrder(node);\n const fontsToLoad = uniqBy(\n rangeTree,\n ({ family, style }) => `${family}::${style}`\n ).map(({ family, style }) => ({\n family,\n style,\n }));\n\n await Promise.all([...fontsToLoad, fallbackFont].map(figma.loadFontAsync));\n\n node.fontName = fallbackFont;\n node.characters = characters;\n\n let prevPos = 0;\n rangeTree.forEach(({ family, style, delimiter }) => {\n if (prevPos < node.characters.length) {\n const delimeterPos = node.characters.indexOf(delimiter, prevPos);\n const endPos =\n delimeterPos > prevPos ? delimeterPos : node.characters.length;\n const matchedFont = {\n family,\n style,\n };\n node.setRangeFontName(prevPos, endPos, matchedFont);\n prevPos = endPos + 1;\n }\n });\n return true;\n};\n", "middle_code": "function uniqBy(arr, predicate) {\n const cb = typeof predicate === \"function\" ? predicate : (o) => o[predicate];\n return [\n ...arr\n .reduce((map, item) => {\n const key = item === null || item === undefined ? item : cb(item);\n map.has(key) || map.set(key, item);\n return map;\n }, new Map())\n .values(),\n ];\n}", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "javascript", "sub_task_type": null}, "context_code": [["/cursor-talk-to-figma-mcp/src/cursor_mcp_plugin/code.js", "// This is the main code file for the Cursor MCP Figma plugin\n// It handles Figma API commands\n\n// Plugin state\nconst state = {\n serverPort: 3055, // Default port\n};\n\n\n// Helper function for progress updates\nfunction sendProgressUpdate(\n commandId,\n commandType,\n status,\n progress,\n totalItems,\n processedItems,\n message,\n payload = null\n) {\n const update = {\n type: \"command_progress\",\n commandId,\n commandType,\n status,\n progress,\n totalItems,\n processedItems,\n message,\n timestamp: Date.now(),\n };\n\n // Add optional chunk information if present\n if (payload) {\n if (\n payload.currentChunk !== undefined &&\n payload.totalChunks !== undefined\n ) {\n update.currentChunk = payload.currentChunk;\n update.totalChunks = payload.totalChunks;\n update.chunkSize = payload.chunkSize;\n }\n update.payload = payload;\n }\n\n // Send to UI\n figma.ui.postMessage(update);\n console.log(`Progress update: ${status} - ${progress}% - ${message}`);\n\n return update;\n}\n\n// Show UI\nfigma.showUI(__html__, { width: 350, height: 450 });\n\n// Plugin commands from UI\nfigma.ui.onmessage = async (msg) => {\n switch (msg.type) {\n case \"update-settings\":\n updateSettings(msg);\n break;\n case \"notify\":\n figma.notify(msg.message);\n break;\n case \"close-plugin\":\n figma.closePlugin();\n break;\n case \"execute-command\":\n // Execute commands received from UI (which gets them from WebSocket)\n try {\n const result = await handleCommand(msg.command, msg.params);\n // Send result back to UI\n figma.ui.postMessage({\n type: \"command-result\",\n id: msg.id,\n result,\n });\n } catch (error) {\n figma.ui.postMessage({\n type: \"command-error\",\n id: msg.id,\n error: error.message || \"Error executing command\",\n });\n }\n break;\n }\n};\n\n// Listen for plugin commands from menu\nfigma.on(\"run\", ({ command }) => {\n figma.ui.postMessage({ type: \"auto-connect\" });\n});\n\n// Update plugin settings\nfunction updateSettings(settings) {\n if (settings.serverPort) {\n state.serverPort = settings.serverPort;\n }\n\n figma.clientStorage.setAsync(\"settings\", {\n serverPort: state.serverPort,\n });\n}\n\n// Handle commands from UI\nasync function handleCommand(command, params) {\n switch (command) {\n case \"get_document_info\":\n return await getDocumentInfo();\n case \"get_selection\":\n return await getSelection();\n case \"get_node_info\":\n if (!params || !params.nodeId) {\n throw new Error(\"Missing nodeId parameter\");\n }\n return await getNodeInfo(params.nodeId);\n case \"get_nodes_info\":\n if (!params || !params.nodeIds || !Array.isArray(params.nodeIds)) {\n throw new Error(\"Missing or invalid nodeIds parameter\");\n }\n return await getNodesInfo(params.nodeIds);\n case \"read_my_design\":\n return await readMyDesign();\n case \"create_rectangle\":\n return await createRectangle(params);\n case \"create_frame\":\n return await createFrame(params);\n case \"create_text\":\n return await createText(params);\n case \"set_fill_color\":\n return await setFillColor(params);\n case \"set_stroke_color\":\n return await setStrokeColor(params);\n case \"move_node\":\n return await moveNode(params);\n case \"resize_node\":\n return await resizeNode(params);\n case \"delete_node\":\n return await deleteNode(params);\n case \"delete_multiple_nodes\":\n return await deleteMultipleNodes(params);\n case \"get_styles\":\n return await getStyles();\n case \"get_local_components\":\n return await getLocalComponents();\n // case \"get_team_components\":\n // return await getTeamComponents();\n case \"create_component_instance\":\n return await createComponentInstance(params);\n case \"export_node_as_image\":\n return await exportNodeAsImage(params);\n case \"set_corner_radius\":\n return await setCornerRadius(params);\n case \"set_text_content\":\n return await setTextContent(params);\n case \"clone_node\":\n return await cloneNode(params);\n case \"scan_text_nodes\":\n return await scanTextNodes(params);\n case \"set_multiple_text_contents\":\n return await setMultipleTextContents(params);\n case \"get_annotations\":\n return await getAnnotations(params);\n case \"set_annotation\":\n return await setAnnotation(params);\n case \"scan_nodes_by_types\":\n return await scanNodesByTypes(params);\n case \"set_multiple_annotations\":\n return await setMultipleAnnotations(params);\n case \"get_instance_overrides\":\n // Check if instanceNode parameter is provided\n if (params && params.instanceNodeId) {\n // Get the instance node by ID\n const instanceNode = await figma.getNodeByIdAsync(params.instanceNodeId);\n if (!instanceNode) {\n throw new Error(`Instance node not found with ID: ${params.instanceNodeId}`);\n }\n return await getInstanceOverrides(instanceNode);\n }\n // Call without instance node if not provided\n return await getInstanceOverrides();\n\n case \"set_instance_overrides\":\n // Check if instanceNodeIds parameter is provided\n if (params && params.targetNodeIds) {\n // Validate that targetNodeIds is an array\n if (!Array.isArray(params.targetNodeIds)) {\n throw new Error(\"targetNodeIds must be an array\");\n }\n\n // Get the instance nodes by IDs\n const targetNodes = await getValidTargetInstances(params.targetNodeIds);\n if (!targetNodes.success) {\n figma.notify(targetNodes.message);\n return { success: false, message: targetNodes.message };\n }\n\n if (params.sourceInstanceId) {\n\n // get source instance data\n let sourceInstanceData = null;\n sourceInstanceData = await getSourceInstanceData(params.sourceInstanceId);\n\n if (!sourceInstanceData.success) {\n figma.notify(sourceInstanceData.message);\n return { success: false, message: sourceInstanceData.message };\n }\n return await setInstanceOverrides(targetNodes.targetInstances, sourceInstanceData);\n } else {\n throw new Error(\"Missing sourceInstanceId parameter\");\n }\n }\n case \"set_layout_mode\":\n return await setLayoutMode(params);\n case \"set_padding\":\n return await setPadding(params);\n case \"set_axis_align\":\n return await setAxisAlign(params);\n case \"set_layout_sizing\":\n return await setLayoutSizing(params);\n case \"set_item_spacing\":\n return await setItemSpacing(params);\n case \"get_reactions\":\n if (!params || !params.nodeIds || !Array.isArray(params.nodeIds)) {\n throw new Error(\"Missing or invalid nodeIds parameter\");\n }\n return await getReactions(params.nodeIds); \n case \"set_default_connector\":\n return await setDefaultConnector(params);\n case \"create_connections\":\n return await createConnections(params);\n default:\n throw new Error(`Unknown command: ${command}`);\n }\n}\n\n// Command implementations\n\nasync function getDocumentInfo() {\n await figma.currentPage.loadAsync();\n const page = figma.currentPage;\n return {\n name: page.name,\n id: page.id,\n type: page.type,\n children: page.children.map((node) => ({\n id: node.id,\n name: node.name,\n type: node.type,\n })),\n currentPage: {\n id: page.id,\n name: page.name,\n childCount: page.children.length,\n },\n pages: [\n {\n id: page.id,\n name: page.name,\n childCount: page.children.length,\n },\n ],\n };\n}\n\nasync function getSelection() {\n return {\n selectionCount: figma.currentPage.selection.length,\n selection: figma.currentPage.selection.map((node) => ({\n id: node.id,\n name: node.name,\n type: node.type,\n visible: node.visible,\n })),\n };\n}\n\nfunction rgbaToHex(color) {\n var r = Math.round(color.r * 255);\n var g = Math.round(color.g * 255);\n var b = Math.round(color.b * 255);\n var a = color.a !== undefined ? Math.round(color.a * 255) : 255;\n\n if (a === 255) {\n return (\n \"#\" +\n [r, g, b]\n .map((x) => {\n return x.toString(16).padStart(2, \"0\");\n })\n .join(\"\")\n );\n }\n\n return (\n \"#\" +\n [r, g, b, a]\n .map((x) => {\n return x.toString(16).padStart(2, \"0\");\n })\n .join(\"\")\n );\n}\n\nfunction filterFigmaNode(node) {\n if (node.type === \"VECTOR\") {\n return null;\n }\n\n var filtered = {\n id: node.id,\n name: node.name,\n type: node.type,\n };\n\n if (node.fills && node.fills.length > 0) {\n filtered.fills = node.fills.map((fill) => {\n var processedFill = Object.assign({}, fill);\n delete processedFill.boundVariables;\n delete processedFill.imageRef;\n\n if (processedFill.gradientStops) {\n processedFill.gradientStops = processedFill.gradientStops.map(\n (stop) => {\n var processedStop = Object.assign({}, stop);\n if (processedStop.color) {\n processedStop.color = rgbaToHex(processedStop.color);\n }\n delete processedStop.boundVariables;\n return processedStop;\n }\n );\n }\n\n if (processedFill.color) {\n processedFill.color = rgbaToHex(processedFill.color);\n }\n\n return processedFill;\n });\n }\n\n if (node.strokes && node.strokes.length > 0) {\n filtered.strokes = node.strokes.map((stroke) => {\n var processedStroke = Object.assign({}, stroke);\n delete processedStroke.boundVariables;\n if (processedStroke.color) {\n processedStroke.color = rgbaToHex(processedStroke.color);\n }\n return processedStroke;\n });\n }\n\n if (node.cornerRadius !== undefined) {\n filtered.cornerRadius = node.cornerRadius;\n }\n\n if (node.absoluteBoundingBox) {\n filtered.absoluteBoundingBox = node.absoluteBoundingBox;\n }\n\n if (node.characters) {\n filtered.characters = node.characters;\n }\n\n if (node.style) {\n filtered.style = {\n fontFamily: node.style.fontFamily,\n fontStyle: node.style.fontStyle,\n fontWeight: node.style.fontWeight,\n fontSize: node.style.fontSize,\n textAlignHorizontal: node.style.textAlignHorizontal,\n letterSpacing: node.style.letterSpacing,\n lineHeightPx: node.style.lineHeightPx,\n };\n }\n\n if (node.children) {\n filtered.children = node.children\n .map((child) => {\n return filterFigmaNode(child);\n })\n .filter((child) => {\n return child !== null;\n });\n }\n\n return filtered;\n}\n\nasync function getNodeInfo(nodeId) {\n const node = await figma.getNodeByIdAsync(nodeId);\n\n if (!node) {\n throw new Error(`Node not found with ID: ${nodeId}`);\n }\n\n const response = await node.exportAsync({\n format: \"JSON_REST_V1\",\n });\n\n return filterFigmaNode(response.document);\n}\n\nasync function getNodesInfo(nodeIds) {\n try {\n // Load all nodes in parallel\n const nodes = await Promise.all(\n nodeIds.map((id) => figma.getNodeByIdAsync(id))\n );\n\n // Filter out any null values (nodes that weren't found)\n const validNodes = nodes.filter((node) => node !== null);\n\n // Export all valid nodes in parallel\n const responses = await Promise.all(\n validNodes.map(async (node) => {\n const response = await node.exportAsync({\n format: \"JSON_REST_V1\",\n });\n return {\n nodeId: node.id,\n document: filterFigmaNode(response.document),\n };\n })\n );\n\n return responses;\n } catch (error) {\n throw new Error(`Error getting nodes info: ${error.message}`);\n }\n}\n\nasync function getReactions(nodeIds) {\n try {\n const commandId = generateCommandId();\n sendProgressUpdate(\n commandId,\n \"get_reactions\",\n \"started\",\n 0,\n nodeIds.length,\n 0,\n `Starting deep search for reactions in ${nodeIds.length} nodes and their children`\n );\n\n // Function to find nodes with reactions from the node and all its children\n async function findNodesWithReactions(node, processedNodes = new Set(), depth = 0, results = []) {\n // Skip already processed nodes (prevent circular references)\n if (processedNodes.has(node.id)) {\n return results;\n }\n \n processedNodes.add(node.id);\n \n // Check if the current node has reactions\n let filteredReactions = [];\n if (node.reactions && node.reactions.length > 0) {\n // Filter out reactions with navigation === 'CHANGE_TO'\n filteredReactions = node.reactions.filter(r => {\n // Some reactions may have action or actions array\n if (r.action && r.action.navigation === 'CHANGE_TO') return false;\n if (Array.isArray(r.actions)) {\n // If any action in actions array is CHANGE_TO, exclude\n return !r.actions.some(a => a.navigation === 'CHANGE_TO');\n }\n return true;\n });\n }\n const hasFilteredReactions = filteredReactions.length > 0;\n \n // If the node has filtered reactions, add it to results and apply highlight effect\n if (hasFilteredReactions) {\n results.push({\n id: node.id,\n name: node.name,\n type: node.type,\n depth: depth,\n hasReactions: true,\n reactions: filteredReactions,\n path: getNodePath(node)\n });\n // Apply highlight effect (orange border)\n await highlightNodeWithAnimation(node);\n }\n \n // If node has children, recursively search them\n if (node.children) {\n for (const child of node.children) {\n await findNodesWithReactions(child, processedNodes, depth + 1, results);\n }\n }\n \n return results;\n }\n \n // Function to apply animated highlight effect to a node\n async function highlightNodeWithAnimation(node) {\n // Save original stroke properties\n const originalStrokeWeight = node.strokeWeight;\n const originalStrokes = node.strokes ? [...node.strokes] : [];\n \n try {\n // Apply orange border stroke\n node.strokeWeight = 4;\n node.strokes = [{\n type: 'SOLID',\n color: { r: 1, g: 0.5, b: 0 }, // Orange color\n opacity: 0.8\n }];\n \n // Set timeout for animation effect (restore to original after 1.5 seconds)\n setTimeout(() => {\n try {\n // Restore original stroke properties\n node.strokeWeight = originalStrokeWeight;\n node.strokes = originalStrokes;\n } catch (restoreError) {\n console.error(`Error restoring node stroke: ${restoreError.message}`);\n }\n }, 1500);\n } catch (highlightError) {\n console.error(`Error highlighting node: ${highlightError.message}`);\n // Continue even if highlighting fails\n }\n }\n \n // Get node hierarchy path as a string\n function getNodePath(node) {\n const path = [];\n let current = node;\n \n while (current && current.parent) {\n path.unshift(current.name);\n current = current.parent;\n }\n \n return path.join(' > ');\n }\n\n // Array to store all results\n let allResults = [];\n let processedCount = 0;\n const totalCount = nodeIds.length;\n \n // Iterate through each node and its children to search for reactions\n for (let i = 0; i < nodeIds.length; i++) {\n try {\n const nodeId = nodeIds[i];\n const node = await figma.getNodeByIdAsync(nodeId);\n \n if (!node) {\n processedCount++;\n sendProgressUpdate(\n commandId,\n \"get_reactions\",\n \"in_progress\",\n processedCount / totalCount,\n totalCount,\n processedCount,\n `Node not found: ${nodeId}`\n );\n continue;\n }\n \n // Search for reactions in the node and its children\n const processedNodes = new Set();\n const nodeResults = await findNodesWithReactions(node, processedNodes);\n \n // Add results\n allResults = allResults.concat(nodeResults);\n \n // Update progress\n processedCount++;\n sendProgressUpdate(\n commandId,\n \"get_reactions\",\n \"in_progress\",\n processedCount / totalCount,\n totalCount,\n processedCount,\n `Processed node ${processedCount}/${totalCount}, found ${nodeResults.length} nodes with reactions`\n );\n } catch (error) {\n processedCount++;\n sendProgressUpdate(\n commandId,\n \"get_reactions\",\n \"in_progress\",\n processedCount / totalCount,\n totalCount,\n processedCount,\n `Error processing node: ${error.message}`\n );\n }\n }\n\n // Completion update\n sendProgressUpdate(\n commandId,\n \"get_reactions\",\n \"completed\",\n 1,\n totalCount,\n totalCount,\n `Completed deep search: found ${allResults.length} nodes with reactions.`\n );\n\n return {\n nodesCount: nodeIds.length,\n nodesWithReactions: allResults.length,\n nodes: allResults\n };\n } catch (error) {\n throw new Error(`Failed to get reactions: ${error.message}`);\n }\n}\n\nasync function readMyDesign() {\n try {\n // Load all selected nodes in parallel\n const nodes = await Promise.all(\n figma.currentPage.selection.map((node) => figma.getNodeByIdAsync(node.id))\n );\n\n // Filter out any null values (nodes that weren't found)\n const validNodes = nodes.filter((node) => node !== null);\n\n // Export all valid nodes in parallel\n const responses = await Promise.all(\n validNodes.map(async (node) => {\n const response = await node.exportAsync({\n format: \"JSON_REST_V1\",\n });\n return {\n nodeId: node.id,\n document: filterFigmaNode(response.document),\n };\n })\n );\n\n return responses;\n } catch (error) {\n throw new Error(`Error getting nodes info: ${error.message}`);\n }\n}\n\nasync function createRectangle(params) {\n const {\n x = 0,\n y = 0,\n width = 100,\n height = 100,\n name = \"Rectangle\",\n parentId,\n } = params || {};\n\n const rect = figma.createRectangle();\n rect.x = x;\n rect.y = y;\n rect.resize(width, height);\n rect.name = name;\n\n // If parentId is provided, append to that node, otherwise append to current page\n if (parentId) {\n const parentNode = await figma.getNodeByIdAsync(parentId);\n if (!parentNode) {\n throw new Error(`Parent node not found with ID: ${parentId}`);\n }\n if (!(\"appendChild\" in parentNode)) {\n throw new Error(`Parent node does not support children: ${parentId}`);\n }\n parentNode.appendChild(rect);\n } else {\n figma.currentPage.appendChild(rect);\n }\n\n return {\n id: rect.id,\n name: rect.name,\n x: rect.x,\n y: rect.y,\n width: rect.width,\n height: rect.height,\n parentId: rect.parent ? rect.parent.id : undefined,\n };\n}\n\nasync function createFrame(params) {\n const {\n x = 0,\n y = 0,\n width = 100,\n height = 100,\n name = \"Frame\",\n parentId,\n fillColor,\n strokeColor,\n strokeWeight,\n layoutMode = \"NONE\",\n layoutWrap = \"NO_WRAP\",\n paddingTop = 10,\n paddingRight = 10,\n paddingBottom = 10,\n paddingLeft = 10,\n primaryAxisAlignItems = \"MIN\",\n counterAxisAlignItems = \"MIN\",\n layoutSizingHorizontal = \"FIXED\",\n layoutSizingVertical = \"FIXED\",\n itemSpacing = 0,\n } = params || {};\n\n const frame = figma.createFrame();\n frame.x = x;\n frame.y = y;\n frame.resize(width, height);\n frame.name = name;\n\n // Set layout mode if provided\n if (layoutMode !== \"NONE\") {\n frame.layoutMode = layoutMode;\n frame.layoutWrap = layoutWrap;\n\n // Set padding values only when layoutMode is not NONE\n frame.paddingTop = paddingTop;\n frame.paddingRight = paddingRight;\n frame.paddingBottom = paddingBottom;\n frame.paddingLeft = paddingLeft;\n\n // Set axis alignment only when layoutMode is not NONE\n frame.primaryAxisAlignItems = primaryAxisAlignItems;\n frame.counterAxisAlignItems = counterAxisAlignItems;\n\n // Set layout sizing only when layoutMode is not NONE\n frame.layoutSizingHorizontal = layoutSizingHorizontal;\n frame.layoutSizingVertical = layoutSizingVertical;\n\n // Set item spacing only when layoutMode is not NONE\n frame.itemSpacing = itemSpacing;\n }\n\n // Set fill color if provided\n if (fillColor) {\n const paintStyle = {\n type: \"SOLID\",\n color: {\n r: parseFloat(fillColor.r) || 0,\n g: parseFloat(fillColor.g) || 0,\n b: parseFloat(fillColor.b) || 0,\n },\n opacity: parseFloat(fillColor.a) || 1,\n };\n frame.fills = [paintStyle];\n }\n\n // Set stroke color and weight if provided\n if (strokeColor) {\n const strokeStyle = {\n type: \"SOLID\",\n color: {\n r: parseFloat(strokeColor.r) || 0,\n g: parseFloat(strokeColor.g) || 0,\n b: parseFloat(strokeColor.b) || 0,\n },\n opacity: parseFloat(strokeColor.a) || 1,\n };\n frame.strokes = [strokeStyle];\n }\n\n // Set stroke weight if provided\n if (strokeWeight !== undefined) {\n frame.strokeWeight = strokeWeight;\n }\n\n // If parentId is provided, append to that node, otherwise append to current page\n if (parentId) {\n const parentNode = await figma.getNodeByIdAsync(parentId);\n if (!parentNode) {\n throw new Error(`Parent node not found with ID: ${parentId}`);\n }\n if (!(\"appendChild\" in parentNode)) {\n throw new Error(`Parent node does not support children: ${parentId}`);\n }\n parentNode.appendChild(frame);\n } else {\n figma.currentPage.appendChild(frame);\n }\n\n return {\n id: frame.id,\n name: frame.name,\n x: frame.x,\n y: frame.y,\n width: frame.width,\n height: frame.height,\n fills: frame.fills,\n strokes: frame.strokes,\n strokeWeight: frame.strokeWeight,\n layoutMode: frame.layoutMode,\n layoutWrap: frame.layoutWrap,\n parentId: frame.parent ? frame.parent.id : undefined,\n };\n}\n\nasync function createText(params) {\n const {\n x = 0,\n y = 0,\n text = \"Text\",\n fontSize = 14,\n fontWeight = 400,\n fontColor = { r: 0, g: 0, b: 0, a: 1 }, // Default to black\n name = \"\",\n parentId,\n } = params || {};\n\n // Map common font weights to Figma font styles\n const getFontStyle = (weight) => {\n switch (weight) {\n case 100:\n return \"Thin\";\n case 200:\n return \"Extra Light\";\n case 300:\n return \"Light\";\n case 400:\n return \"Regular\";\n case 500:\n return \"Medium\";\n case 600:\n return \"Semi Bold\";\n case 700:\n return \"Bold\";\n case 800:\n return \"Extra Bold\";\n case 900:\n return \"Black\";\n default:\n return \"Regular\";\n }\n };\n\n const textNode = figma.createText();\n textNode.x = x;\n textNode.y = y;\n textNode.name = name || text;\n try {\n await figma.loadFontAsync({\n family: \"Inter\",\n style: getFontStyle(fontWeight),\n });\n textNode.fontName = { family: \"Inter\", style: getFontStyle(fontWeight) };\n textNode.fontSize = parseInt(fontSize);\n } catch (error) {\n console.error(\"Error setting font size\", error);\n }\n setCharacters(textNode, text);\n\n // Set text color\n const paintStyle = {\n type: \"SOLID\",\n color: {\n r: parseFloat(fontColor.r) || 0,\n g: parseFloat(fontColor.g) || 0,\n b: parseFloat(fontColor.b) || 0,\n },\n opacity: parseFloat(fontColor.a) || 1,\n };\n textNode.fills = [paintStyle];\n\n // If parentId is provided, append to that node, otherwise append to current page\n if (parentId) {\n const parentNode = await figma.getNodeByIdAsync(parentId);\n if (!parentNode) {\n throw new Error(`Parent node not found with ID: ${parentId}`);\n }\n if (!(\"appendChild\" in parentNode)) {\n throw new Error(`Parent node does not support children: ${parentId}`);\n }\n parentNode.appendChild(textNode);\n } else {\n figma.currentPage.appendChild(textNode);\n }\n\n return {\n id: textNode.id,\n name: textNode.name,\n x: textNode.x,\n y: textNode.y,\n width: textNode.width,\n height: textNode.height,\n characters: textNode.characters,\n fontSize: textNode.fontSize,\n fontWeight: fontWeight,\n fontColor: fontColor,\n fontName: textNode.fontName,\n fills: textNode.fills,\n parentId: textNode.parent ? textNode.parent.id : undefined,\n };\n}\n\nasync function setFillColor(params) {\n console.log(\"setFillColor\", params);\n const {\n nodeId,\n color: { r, g, b, a },\n } = params || {};\n\n if (!nodeId) {\n throw new Error(\"Missing nodeId parameter\");\n }\n\n const node = await figma.getNodeByIdAsync(nodeId);\n if (!node) {\n throw new Error(`Node not found with ID: ${nodeId}`);\n }\n\n if (!(\"fills\" in node)) {\n throw new Error(`Node does not support fills: ${nodeId}`);\n }\n\n // Create RGBA color\n const rgbColor = {\n r: parseFloat(r) || 0,\n g: parseFloat(g) || 0,\n b: parseFloat(b) || 0,\n a: parseFloat(a) || 1,\n };\n\n // Set fill\n const paintStyle = {\n type: \"SOLID\",\n color: {\n r: parseFloat(rgbColor.r),\n g: parseFloat(rgbColor.g),\n b: parseFloat(rgbColor.b),\n },\n opacity: parseFloat(rgbColor.a),\n };\n\n console.log(\"paintStyle\", paintStyle);\n\n node.fills = [paintStyle];\n\n return {\n id: node.id,\n name: node.name,\n fills: [paintStyle],\n };\n}\n\nasync function setStrokeColor(params) {\n const {\n nodeId,\n color: { r, g, b, a },\n weight = 1,\n } = params || {};\n\n if (!nodeId) {\n throw new Error(\"Missing nodeId parameter\");\n }\n\n const node = await figma.getNodeByIdAsync(nodeId);\n if (!node) {\n throw new Error(`Node not found with ID: ${nodeId}`);\n }\n\n if (!(\"strokes\" in node)) {\n throw new Error(`Node does not support strokes: ${nodeId}`);\n }\n\n // Create RGBA color\n const rgbColor = {\n r: r !== undefined ? r : 0,\n g: g !== undefined ? g : 0,\n b: b !== undefined ? b : 0,\n a: a !== undefined ? a : 1,\n };\n\n // Set stroke\n const paintStyle = {\n type: \"SOLID\",\n color: {\n r: rgbColor.r,\n g: rgbColor.g,\n b: rgbColor.b,\n },\n opacity: rgbColor.a,\n };\n\n node.strokes = [paintStyle];\n\n // Set stroke weight if available\n if (\"strokeWeight\" in node) {\n node.strokeWeight = weight;\n }\n\n return {\n id: node.id,\n name: node.name,\n strokes: node.strokes,\n strokeWeight: \"strokeWeight\" in node ? node.strokeWeight : undefined,\n };\n}\n\nasync function moveNode(params) {\n const { nodeId, x, y } = params || {};\n\n if (!nodeId) {\n throw new Error(\"Missing nodeId parameter\");\n }\n\n if (x === undefined || y === undefined) {\n throw new Error(\"Missing x or y parameters\");\n }\n\n const node = await figma.getNodeByIdAsync(nodeId);\n if (!node) {\n throw new Error(`Node not found with ID: ${nodeId}`);\n }\n\n if (!(\"x\" in node) || !(\"y\" in node)) {\n throw new Error(`Node does not support position: ${nodeId}`);\n }\n\n node.x = x;\n node.y = y;\n\n return {\n id: node.id,\n name: node.name,\n x: node.x,\n y: node.y,\n };\n}\n\nasync function resizeNode(params) {\n const { nodeId, width, height } = params || {};\n\n if (!nodeId) {\n throw new Error(\"Missing nodeId parameter\");\n }\n\n if (width === undefined || height === undefined) {\n throw new Error(\"Missing width or height parameters\");\n }\n\n const node = await figma.getNodeByIdAsync(nodeId);\n if (!node) {\n throw new Error(`Node not found with ID: ${nodeId}`);\n }\n\n if (!(\"resize\" in node)) {\n throw new Error(`Node does not support resizing: ${nodeId}`);\n }\n\n node.resize(width, height);\n\n return {\n id: node.id,\n name: node.name,\n width: node.width,\n height: node.height,\n };\n}\n\nasync function deleteNode(params) {\n const { nodeId } = params || {};\n\n if (!nodeId) {\n throw new Error(\"Missing nodeId parameter\");\n }\n\n const node = await figma.getNodeByIdAsync(nodeId);\n if (!node) {\n throw new Error(`Node not found with ID: ${nodeId}`);\n }\n\n // Save node info before deleting\n const nodeInfo = {\n id: node.id,\n name: node.name,\n type: node.type,\n };\n\n node.remove();\n\n return nodeInfo;\n}\n\nasync function getStyles() {\n const styles = {\n colors: await figma.getLocalPaintStylesAsync(),\n texts: await figma.getLocalTextStylesAsync(),\n effects: await figma.getLocalEffectStylesAsync(),\n grids: await figma.getLocalGridStylesAsync(),\n };\n\n return {\n colors: styles.colors.map((style) => ({\n id: style.id,\n name: style.name,\n key: style.key,\n paint: style.paints[0],\n })),\n texts: styles.texts.map((style) => ({\n id: style.id,\n name: style.name,\n key: style.key,\n fontSize: style.fontSize,\n fontName: style.fontName,\n })),\n effects: styles.effects.map((style) => ({\n id: style.id,\n name: style.name,\n key: style.key,\n })),\n grids: styles.grids.map((style) => ({\n id: style.id,\n name: style.name,\n key: style.key,\n })),\n };\n}\n\nasync function getLocalComponents() {\n await figma.loadAllPagesAsync();\n\n const components = figma.root.findAllWithCriteria({\n types: [\"COMPONENT\"],\n });\n\n return {\n count: components.length,\n components: components.map((component) => ({\n id: component.id,\n name: component.name,\n key: \"key\" in component ? component.key : null,\n })),\n };\n}\n\n// async function getTeamComponents() {\n// try {\n// const teamComponents =\n// await figma.teamLibrary.getAvailableComponentsAsync();\n\n// return {\n// count: teamComponents.length,\n// components: teamComponents.map((component) => ({\n// key: component.key,\n// name: component.name,\n// description: component.description,\n// libraryName: component.libraryName,\n// })),\n// };\n// } catch (error) {\n// throw new Error(`Error getting team components: ${error.message}`);\n// }\n// }\n\nasync function createComponentInstance(params) {\n const { componentKey, x = 0, y = 0 } = params || {};\n\n if (!componentKey) {\n throw new Error(\"Missing componentKey parameter\");\n }\n\n try {\n const component = await figma.importComponentByKeyAsync(componentKey);\n const instance = component.createInstance();\n\n instance.x = x;\n instance.y = y;\n\n figma.currentPage.appendChild(instance);\n\n return {\n id: instance.id,\n name: instance.name,\n x: instance.x,\n y: instance.y,\n width: instance.width,\n height: instance.height,\n componentId: instance.componentId,\n };\n } catch (error) {\n throw new Error(`Error creating component instance: ${error.message}`);\n }\n}\n\nasync function exportNodeAsImage(params) {\n const { nodeId, scale = 1 } = params || {};\n\n const format = \"PNG\";\n\n if (!nodeId) {\n throw new Error(\"Missing nodeId parameter\");\n }\n\n const node = await figma.getNodeByIdAsync(nodeId);\n if (!node) {\n throw new Error(`Node not found with ID: ${nodeId}`);\n }\n\n if (!(\"exportAsync\" in node)) {\n throw new Error(`Node does not support exporting: ${nodeId}`);\n }\n\n try {\n const settings = {\n format: format,\n constraint: { type: \"SCALE\", value: scale },\n };\n\n const bytes = await node.exportAsync(settings);\n\n let mimeType;\n switch (format) {\n case \"PNG\":\n mimeType = \"image/png\";\n break;\n case \"JPG\":\n mimeType = \"image/jpeg\";\n break;\n case \"SVG\":\n mimeType = \"image/svg+xml\";\n break;\n case \"PDF\":\n mimeType = \"application/pdf\";\n break;\n default:\n mimeType = \"application/octet-stream\";\n }\n\n // Proper way to convert Uint8Array to base64\n const base64 = customBase64Encode(bytes);\n // const imageData = `data:${mimeType};base64,${base64}`;\n\n return {\n nodeId,\n format,\n scale,\n mimeType,\n imageData: base64,\n };\n } catch (error) {\n throw new Error(`Error exporting node as image: ${error.message}`);\n }\n}\nfunction customBase64Encode(bytes) {\n const chars =\n \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n let base64 = \"\";\n\n const byteLength = bytes.byteLength;\n const byteRemainder = byteLength % 3;\n const mainLength = byteLength - byteRemainder;\n\n let a, b, c, d;\n let chunk;\n\n // Main loop deals with bytes in chunks of 3\n for (let i = 0; i < mainLength; i = i + 3) {\n // Combine the three bytes into a single integer\n chunk = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2];\n\n // Use bitmasks to extract 6-bit segments from the triplet\n a = (chunk & 16515072) >> 18; // 16515072 = (2^6 - 1) << 18\n b = (chunk & 258048) >> 12; // 258048 = (2^6 - 1) << 12\n c = (chunk & 4032) >> 6; // 4032 = (2^6 - 1) << 6\n d = chunk & 63; // 63 = 2^6 - 1\n\n // Convert the raw binary segments to the appropriate ASCII encoding\n base64 += chars[a] + chars[b] + chars[c] + chars[d];\n }\n\n // Deal with the remaining bytes and padding\n if (byteRemainder === 1) {\n chunk = bytes[mainLength];\n\n a = (chunk & 252) >> 2; // 252 = (2^6 - 1) << 2\n\n // Set the 4 least significant bits to zero\n b = (chunk & 3) << 4; // 3 = 2^2 - 1\n\n base64 += chars[a] + chars[b] + \"==\";\n } else if (byteRemainder === 2) {\n chunk = (bytes[mainLength] << 8) | bytes[mainLength + 1];\n\n a = (chunk & 64512) >> 10; // 64512 = (2^6 - 1) << 10\n b = (chunk & 1008) >> 4; // 1008 = (2^6 - 1) << 4\n\n // Set the 2 least significant bits to zero\n c = (chunk & 15) << 2; // 15 = 2^4 - 1\n\n base64 += chars[a] + chars[b] + chars[c] + \"=\";\n }\n\n return base64;\n}\n\nasync function setCornerRadius(params) {\n const { nodeId, radius, corners } = params || {};\n\n if (!nodeId) {\n throw new Error(\"Missing nodeId parameter\");\n }\n\n if (radius === undefined) {\n throw new Error(\"Missing radius parameter\");\n }\n\n const node = await figma.getNodeByIdAsync(nodeId);\n if (!node) {\n throw new Error(`Node not found with ID: ${nodeId}`);\n }\n\n // Check if node supports corner radius\n if (!(\"cornerRadius\" in node)) {\n throw new Error(`Node does not support corner radius: ${nodeId}`);\n }\n\n // If corners array is provided, set individual corner radii\n if (corners && Array.isArray(corners) && corners.length === 4) {\n if (\"topLeftRadius\" in node) {\n // Node supports individual corner radii\n if (corners[0]) node.topLeftRadius = radius;\n if (corners[1]) node.topRightRadius = radius;\n if (corners[2]) node.bottomRightRadius = radius;\n if (corners[3]) node.bottomLeftRadius = radius;\n } else {\n // Node only supports uniform corner radius\n node.cornerRadius = radius;\n }\n } else {\n // Set uniform corner radius\n node.cornerRadius = radius;\n }\n\n return {\n id: node.id,\n name: node.name,\n cornerRadius: \"cornerRadius\" in node ? node.cornerRadius : undefined,\n topLeftRadius: \"topLeftRadius\" in node ? node.topLeftRadius : undefined,\n topRightRadius: \"topRightRadius\" in node ? node.topRightRadius : undefined,\n bottomRightRadius:\n \"bottomRightRadius\" in node ? node.bottomRightRadius : undefined,\n bottomLeftRadius:\n \"bottomLeftRadius\" in node ? node.bottomLeftRadius : undefined,\n };\n}\n\nasync function setTextContent(params) {\n const { nodeId, text } = params || {};\n\n if (!nodeId) {\n throw new Error(\"Missing nodeId parameter\");\n }\n\n if (text === undefined) {\n throw new Error(\"Missing text parameter\");\n }\n\n const node = await figma.getNodeByIdAsync(nodeId);\n if (!node) {\n throw new Error(`Node not found with ID: ${nodeId}`);\n }\n\n if (node.type !== \"TEXT\") {\n throw new Error(`Node is not a text node: ${nodeId}`);\n }\n\n try {\n await figma.loadFontAsync(node.fontName);\n\n await setCharacters(node, text);\n\n return {\n id: node.id,\n name: node.name,\n characters: node.characters,\n fontName: node.fontName,\n };\n } catch (error) {\n throw new Error(`Error setting text content: ${error.message}`);\n }\n}\n\n// Initialize settings on load\n(async function initializePlugin() {\n try {\n const savedSettings = await figma.clientStorage.getAsync(\"settings\");\n if (savedSettings) {\n if (savedSettings.serverPort) {\n state.serverPort = savedSettings.serverPort;\n }\n }\n\n // Send initial settings to UI\n figma.ui.postMessage({\n type: \"init-settings\",\n settings: {\n serverPort: state.serverPort,\n },\n });\n } catch (error) {\n console.error(\"Error loading settings:\", error);\n }\n})();\n\nfunction uniqBy(arr, predicate) {\n const cb = typeof predicate === \"function\" ? predicate : (o) => o[predicate];\n return [\n ...arr\n .reduce((map, item) => {\n const key = item === null || item === undefined ? item : cb(item);\n\n map.has(key) || map.set(key, item);\n\n return map;\n }, new Map())\n .values(),\n ];\n}\nconst setCharacters = async (node, characters, options) => {\n const fallbackFont = (options && options.fallbackFont) || {\n family: \"Inter\",\n style: \"Regular\",\n };\n try {\n if (node.fontName === figma.mixed) {\n if (options && options.smartStrategy === \"prevail\") {\n const fontHashTree = {};\n for (let i = 1; i < node.characters.length; i++) {\n const charFont = node.getRangeFontName(i - 1, i);\n const key = `${charFont.family}::${charFont.style}`;\n fontHashTree[key] = fontHashTree[key] ? fontHashTree[key] + 1 : 1;\n }\n const prevailedTreeItem = Object.entries(fontHashTree).sort(\n (a, b) => b[1] - a[1]\n )[0];\n const [family, style] = prevailedTreeItem[0].split(\"::\");\n const prevailedFont = {\n family,\n style,\n };\n await figma.loadFontAsync(prevailedFont);\n node.fontName = prevailedFont;\n } else if (options && options.smartStrategy === \"strict\") {\n return setCharactersWithStrictMatchFont(node, characters, fallbackFont);\n } else if (options && options.smartStrategy === \"experimental\") {\n return setCharactersWithSmartMatchFont(node, characters, fallbackFont);\n } else {\n const firstCharFont = node.getRangeFontName(0, 1);\n await figma.loadFontAsync(firstCharFont);\n node.fontName = firstCharFont;\n }\n } else {\n await figma.loadFontAsync({\n family: node.fontName.family,\n style: node.fontName.style,\n });\n }\n } catch (err) {\n console.warn(\n `Failed to load \"${node.fontName[\"family\"]} ${node.fontName[\"style\"]}\" font and replaced with fallback \"${fallbackFont.family} ${fallbackFont.style}\"`,\n err\n );\n await figma.loadFontAsync(fallbackFont);\n node.fontName = fallbackFont;\n }\n try {\n node.characters = characters;\n return true;\n } catch (err) {\n console.warn(`Failed to set characters. Skipped.`, err);\n return false;\n }\n};\n\nconst setCharactersWithStrictMatchFont = async (\n node,\n characters,\n fallbackFont\n) => {\n const fontHashTree = {};\n for (let i = 1; i < node.characters.length; i++) {\n const startIdx = i - 1;\n const startCharFont = node.getRangeFontName(startIdx, i);\n const startCharFontVal = `${startCharFont.family}::${startCharFont.style}`;\n while (i < node.characters.length) {\n i++;\n const charFont = node.getRangeFontName(i - 1, i);\n if (startCharFontVal !== `${charFont.family}::${charFont.style}`) {\n break;\n }\n }\n fontHashTree[`${startIdx}_${i}`] = startCharFontVal;\n }\n await figma.loadFontAsync(fallbackFont);\n node.fontName = fallbackFont;\n node.characters = characters;\n console.log(fontHashTree);\n await Promise.all(\n Object.keys(fontHashTree).map(async (range) => {\n console.log(range, fontHashTree[range]);\n const [start, end] = range.split(\"_\");\n const [family, style] = fontHashTree[range].split(\"::\");\n const matchedFont = {\n family,\n style,\n };\n await figma.loadFontAsync(matchedFont);\n return node.setRangeFontName(Number(start), Number(end), matchedFont);\n })\n );\n return true;\n};\n\nconst getDelimiterPos = (str, delimiter, startIdx = 0, endIdx = str.length) => {\n const indices = [];\n let temp = startIdx;\n for (let i = startIdx; i < endIdx; i++) {\n if (\n str[i] === delimiter &&\n i + startIdx !== endIdx &&\n temp !== i + startIdx\n ) {\n indices.push([temp, i + startIdx]);\n temp = i + startIdx + 1;\n }\n }\n temp !== endIdx && indices.push([temp, endIdx]);\n return indices.filter(Boolean);\n};\n\nconst buildLinearOrder = (node) => {\n const fontTree = [];\n const newLinesPos = getDelimiterPos(node.characters, \"\\n\");\n newLinesPos.forEach(([newLinesRangeStart, newLinesRangeEnd], n) => {\n const newLinesRangeFont = node.getRangeFontName(\n newLinesRangeStart,\n newLinesRangeEnd\n );\n if (newLinesRangeFont === figma.mixed) {\n const spacesPos = getDelimiterPos(\n node.characters,\n \" \",\n newLinesRangeStart,\n newLinesRangeEnd\n );\n spacesPos.forEach(([spacesRangeStart, spacesRangeEnd], s) => {\n const spacesRangeFont = node.getRangeFontName(\n spacesRangeStart,\n spacesRangeEnd\n );\n if (spacesRangeFont === figma.mixed) {\n const spacesRangeFont = node.getRangeFontName(\n spacesRangeStart,\n spacesRangeStart[0]\n );\n fontTree.push({\n start: spacesRangeStart,\n delimiter: \" \",\n family: spacesRangeFont.family,\n style: spacesRangeFont.style,\n });\n } else {\n fontTree.push({\n start: spacesRangeStart,\n delimiter: \" \",\n family: spacesRangeFont.family,\n style: spacesRangeFont.style,\n });\n }\n });\n } else {\n fontTree.push({\n start: newLinesRangeStart,\n delimiter: \"\\n\",\n family: newLinesRangeFont.family,\n style: newLinesRangeFont.style,\n });\n }\n });\n return fontTree\n .sort((a, b) => +a.start - +b.start)\n .map(({ family, style, delimiter }) => ({ family, style, delimiter }));\n};\n\nconst setCharactersWithSmartMatchFont = async (\n node,\n characters,\n fallbackFont\n) => {\n const rangeTree = buildLinearOrder(node);\n const fontsToLoad = uniqBy(\n rangeTree,\n ({ family, style }) => `${family}::${style}`\n ).map(({ family, style }) => ({\n family,\n style,\n }));\n\n await Promise.all([...fontsToLoad, fallbackFont].map(figma.loadFontAsync));\n\n node.fontName = fallbackFont;\n node.characters = characters;\n\n let prevPos = 0;\n rangeTree.forEach(({ family, style, delimiter }) => {\n if (prevPos < node.characters.length) {\n const delimeterPos = node.characters.indexOf(delimiter, prevPos);\n const endPos =\n delimeterPos > prevPos ? delimeterPos : node.characters.length;\n const matchedFont = {\n family,\n style,\n };\n node.setRangeFontName(prevPos, endPos, matchedFont);\n prevPos = endPos + 1;\n }\n });\n return true;\n};\n\n// Add the cloneNode function implementation\nasync function cloneNode(params) {\n const { nodeId, x, y } = params || {};\n\n if (!nodeId) {\n throw new Error(\"Missing nodeId parameter\");\n }\n\n const node = await figma.getNodeByIdAsync(nodeId);\n if (!node) {\n throw new Error(`Node not found with ID: ${nodeId}`);\n }\n\n // Clone the node\n const clone = node.clone();\n\n // If x and y are provided, move the clone to that position\n if (x !== undefined && y !== undefined) {\n if (!(\"x\" in clone) || !(\"y\" in clone)) {\n throw new Error(`Cloned node does not support position: ${nodeId}`);\n }\n clone.x = x;\n clone.y = y;\n }\n\n // Add the clone to the same parent as the original node\n if (node.parent) {\n node.parent.appendChild(clone);\n } else {\n figma.currentPage.appendChild(clone);\n }\n\n return {\n id: clone.id,\n name: clone.name,\n x: \"x\" in clone ? clone.x : undefined,\n y: \"y\" in clone ? clone.y : undefined,\n width: \"width\" in clone ? clone.width : undefined,\n height: \"height\" in clone ? clone.height : undefined,\n };\n}\n\nasync function scanTextNodes(params) {\n console.log(`Starting to scan text nodes from node ID: ${params.nodeId}`);\n const {\n nodeId,\n useChunking = true,\n chunkSize = 10,\n commandId = generateCommandId(),\n } = params || {};\n\n const node = await figma.getNodeByIdAsync(nodeId);\n\n if (!node) {\n console.error(`Node with ID ${nodeId} not found`);\n // Send error progress update\n sendProgressUpdate(\n commandId,\n \"scan_text_nodes\",\n \"error\",\n 0,\n 0,\n 0,\n `Node with ID ${nodeId} not found`,\n { error: `Node not found: ${nodeId}` }\n );\n throw new Error(`Node with ID ${nodeId} not found`);\n }\n\n // If chunking is not enabled, use the original implementation\n if (!useChunking) {\n const textNodes = [];\n try {\n // Send started progress update\n sendProgressUpdate(\n commandId,\n \"scan_text_nodes\",\n \"started\",\n 0,\n 1, // Not known yet how many nodes there are\n 0,\n `Starting scan of node \"${node.name || nodeId}\" without chunking`,\n null\n );\n\n await findTextNodes(node, [], 0, textNodes);\n\n // Send completed progress update\n sendProgressUpdate(\n commandId,\n \"scan_text_nodes\",\n \"completed\",\n 100,\n textNodes.length,\n textNodes.length,\n `Scan complete. Found ${textNodes.length} text nodes.`,\n { textNodes }\n );\n\n return {\n success: true,\n message: `Scanned ${textNodes.length} text nodes.`,\n count: textNodes.length,\n textNodes: textNodes,\n commandId,\n };\n } catch (error) {\n console.error(\"Error scanning text nodes:\", error);\n\n // Send error progress update\n sendProgressUpdate(\n commandId,\n \"scan_text_nodes\",\n \"error\",\n 0,\n 0,\n 0,\n `Error scanning text nodes: ${error.message}`,\n { error: error.message }\n );\n\n throw new Error(`Error scanning text nodes: ${error.message}`);\n }\n }\n\n // Chunked implementation\n console.log(`Using chunked scanning with chunk size: ${chunkSize}`);\n\n // First, collect all nodes to process (without processing them yet)\n const nodesToProcess = [];\n\n // Send started progress update\n sendProgressUpdate(\n commandId,\n \"scan_text_nodes\",\n \"started\",\n 0,\n 0, // Not known yet how many nodes there are\n 0,\n `Starting chunked scan of node \"${node.name || nodeId}\"`,\n { chunkSize }\n );\n\n await collectNodesToProcess(node, [], 0, nodesToProcess);\n\n const totalNodes = nodesToProcess.length;\n console.log(`Found ${totalNodes} total nodes to process`);\n\n // Calculate number of chunks needed\n const totalChunks = Math.ceil(totalNodes / chunkSize);\n console.log(`Will process in ${totalChunks} chunks`);\n\n // Send update after node collection\n sendProgressUpdate(\n commandId,\n \"scan_text_nodes\",\n \"in_progress\",\n 5, // 5% progress for collection phase\n totalNodes,\n 0,\n `Found ${totalNodes} nodes to scan. Will process in ${totalChunks} chunks.`,\n {\n totalNodes,\n totalChunks,\n chunkSize,\n }\n );\n\n // Process nodes in chunks\n const allTextNodes = [];\n let processedNodes = 0;\n let chunksProcessed = 0;\n\n for (let i = 0; i < totalNodes; i += chunkSize) {\n const chunkEnd = Math.min(i + chunkSize, totalNodes);\n console.log(\n `Processing chunk ${chunksProcessed + 1}/${totalChunks} (nodes ${i} to ${chunkEnd - 1\n })`\n );\n\n // Send update before processing chunk\n sendProgressUpdate(\n commandId,\n \"scan_text_nodes\",\n \"in_progress\",\n Math.round(5 + (chunksProcessed / totalChunks) * 90), // 5-95% for processing\n totalNodes,\n processedNodes,\n `Processing chunk ${chunksProcessed + 1}/${totalChunks}`,\n {\n currentChunk: chunksProcessed + 1,\n totalChunks,\n textNodesFound: allTextNodes.length,\n }\n );\n\n const chunkNodes = nodesToProcess.slice(i, chunkEnd);\n const chunkTextNodes = [];\n\n // Process each node in this chunk\n for (const nodeInfo of chunkNodes) {\n if (nodeInfo.node.type === \"TEXT\") {\n try {\n const textNodeInfo = await processTextNode(\n nodeInfo.node,\n nodeInfo.parentPath,\n nodeInfo.depth\n );\n if (textNodeInfo) {\n chunkTextNodes.push(textNodeInfo);\n }\n } catch (error) {\n console.error(`Error processing text node: ${error.message}`);\n // Continue with other nodes\n }\n }\n\n // Brief delay to allow UI updates and prevent freezing\n await delay(5);\n }\n\n // Add results from this chunk\n allTextNodes.push(...chunkTextNodes);\n processedNodes += chunkNodes.length;\n chunksProcessed++;\n\n // Send update after processing chunk\n sendProgressUpdate(\n commandId,\n \"scan_text_nodes\",\n \"in_progress\",\n Math.round(5 + (chunksProcessed / totalChunks) * 90), // 5-95% for processing\n totalNodes,\n processedNodes,\n `Processed chunk ${chunksProcessed}/${totalChunks}. Found ${allTextNodes.length} text nodes so far.`,\n {\n currentChunk: chunksProcessed,\n totalChunks,\n processedNodes,\n textNodesFound: allTextNodes.length,\n chunkResult: chunkTextNodes,\n }\n );\n\n // Small delay between chunks to prevent UI freezing\n if (i + chunkSize < totalNodes) {\n await delay(50);\n }\n }\n\n // Send completed progress update\n sendProgressUpdate(\n commandId,\n \"scan_text_nodes\",\n \"completed\",\n 100,\n totalNodes,\n processedNodes,\n `Scan complete. Found ${allTextNodes.length} text nodes.`,\n {\n textNodes: allTextNodes,\n processedNodes,\n chunks: chunksProcessed,\n }\n );\n\n return {\n success: true,\n message: `Chunked scan complete. Found ${allTextNodes.length} text nodes.`,\n totalNodes: allTextNodes.length,\n processedNodes: processedNodes,\n chunks: chunksProcessed,\n textNodes: allTextNodes,\n commandId,\n };\n}\n\n// Helper function to collect all nodes that need to be processed\nasync function collectNodesToProcess(\n node,\n parentPath = [],\n depth = 0,\n nodesToProcess = []\n) {\n // Skip invisible nodes\n if (node.visible === false) return;\n\n // Get the path to this node\n const nodePath = [...parentPath, node.name || `Unnamed ${node.type}`];\n\n // Add this node to the processing list\n nodesToProcess.push({\n node: node,\n parentPath: nodePath,\n depth: depth,\n });\n\n // Recursively add children\n if (\"children\" in node) {\n for (const child of node.children) {\n await collectNodesToProcess(child, nodePath, depth + 1, nodesToProcess);\n }\n }\n}\n\n// Process a single text node\nasync function processTextNode(node, parentPath, depth) {\n if (node.type !== \"TEXT\") return null;\n\n try {\n // Safely extract font information\n let fontFamily = \"\";\n let fontStyle = \"\";\n\n if (node.fontName) {\n if (typeof node.fontName === \"object\") {\n if (\"family\" in node.fontName) fontFamily = node.fontName.family;\n if (\"style\" in node.fontName) fontStyle = node.fontName.style;\n }\n }\n\n // Create a safe representation of the text node\n const safeTextNode = {\n id: node.id,\n name: node.name || \"Text\",\n type: node.type,\n characters: node.characters,\n fontSize: typeof node.fontSize === \"number\" ? node.fontSize : 0,\n fontFamily: fontFamily,\n fontStyle: fontStyle,\n x: typeof node.x === \"number\" ? node.x : 0,\n y: typeof node.y === \"number\" ? node.y : 0,\n width: typeof node.width === \"number\" ? node.width : 0,\n height: typeof node.height === \"number\" ? node.height : 0,\n path: parentPath.join(\" > \"),\n depth: depth,\n };\n\n // Highlight the node briefly (optional visual feedback)\n try {\n const originalFills = JSON.parse(JSON.stringify(node.fills));\n node.fills = [\n {\n type: \"SOLID\",\n color: { r: 1, g: 0.5, b: 0 },\n opacity: 0.3,\n },\n ];\n\n // Brief delay for the highlight to be visible\n await delay(100);\n\n try {\n node.fills = originalFills;\n } catch (err) {\n console.error(\"Error resetting fills:\", err);\n }\n } catch (highlightErr) {\n console.error(\"Error highlighting text node:\", highlightErr);\n // Continue anyway, highlighting is just visual feedback\n }\n\n return safeTextNode;\n } catch (nodeErr) {\n console.error(\"Error processing text node:\", nodeErr);\n return null;\n }\n}\n\n// A delay function that returns a promise\nfunction delay(ms) {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n// Keep the original findTextNodes for backward compatibility\nasync function findTextNodes(node, parentPath = [], depth = 0, textNodes = []) {\n // Skip invisible nodes\n if (node.visible === false) return;\n\n // Get the path to this node including its name\n const nodePath = [...parentPath, node.name || `Unnamed ${node.type}`];\n\n if (node.type === \"TEXT\") {\n try {\n // Safely extract font information to avoid Symbol serialization issues\n let fontFamily = \"\";\n let fontStyle = \"\";\n\n if (node.fontName) {\n if (typeof node.fontName === \"object\") {\n if (\"family\" in node.fontName) fontFamily = node.fontName.family;\n if (\"style\" in node.fontName) fontStyle = node.fontName.style;\n }\n }\n\n // Create a safe representation of the text node with only serializable properties\n const safeTextNode = {\n id: node.id,\n name: node.name || \"Text\",\n type: node.type,\n characters: node.characters,\n fontSize: typeof node.fontSize === \"number\" ? node.fontSize : 0,\n fontFamily: fontFamily,\n fontStyle: fontStyle,\n x: typeof node.x === \"number\" ? node.x : 0,\n y: typeof node.y === \"number\" ? node.y : 0,\n width: typeof node.width === \"number\" ? node.width : 0,\n height: typeof node.height === \"number\" ? node.height : 0,\n path: nodePath.join(\" > \"),\n depth: depth,\n };\n\n // Only highlight the node if it's not being done via API\n try {\n // Safe way to create a temporary highlight without causing serialization issues\n const originalFills = JSON.parse(JSON.stringify(node.fills));\n node.fills = [\n {\n type: \"SOLID\",\n color: { r: 1, g: 0.5, b: 0 },\n opacity: 0.3,\n },\n ];\n\n // Promise-based delay instead of setTimeout\n await delay(500);\n\n try {\n node.fills = originalFills;\n } catch (err) {\n console.error(\"Error resetting fills:\", err);\n }\n } catch (highlightErr) {\n console.error(\"Error highlighting text node:\", highlightErr);\n // Continue anyway, highlighting is just visual feedback\n }\n\n textNodes.push(safeTextNode);\n } catch (nodeErr) {\n console.error(\"Error processing text node:\", nodeErr);\n // Skip this node but continue with others\n }\n }\n\n // Recursively process children of container nodes\n if (\"children\" in node) {\n for (const child of node.children) {\n await findTextNodes(child, nodePath, depth + 1, textNodes);\n }\n }\n}\n\n// Replace text in a specific node\nasync function setMultipleTextContents(params) {\n const { nodeId, text } = params || {};\n const commandId = params.commandId || generateCommandId();\n\n if (!nodeId || !text || !Array.isArray(text)) {\n const errorMsg = \"Missing required parameters: nodeId and text array\";\n\n // Send error progress update\n sendProgressUpdate(\n commandId,\n \"set_multiple_text_contents\",\n \"error\",\n 0,\n 0,\n 0,\n errorMsg,\n { error: errorMsg }\n );\n\n throw new Error(errorMsg);\n }\n\n console.log(\n `Starting text replacement for node: ${nodeId} with ${text.length} text replacements`\n );\n\n // Send started progress update\n sendProgressUpdate(\n commandId,\n \"set_multiple_text_contents\",\n \"started\",\n 0,\n text.length,\n 0,\n `Starting text replacement for ${text.length} nodes`,\n { totalReplacements: text.length }\n );\n\n // Define the results array and counters\n const results = [];\n let successCount = 0;\n let failureCount = 0;\n\n // Split text replacements into chunks of 5\n const CHUNK_SIZE = 5;\n const chunks = [];\n\n for (let i = 0; i < text.length; i += CHUNK_SIZE) {\n chunks.push(text.slice(i, i + CHUNK_SIZE));\n }\n\n console.log(`Split ${text.length} replacements into ${chunks.length} chunks`);\n\n // Send chunking info update\n sendProgressUpdate(\n commandId,\n \"set_multiple_text_contents\",\n \"in_progress\",\n 5, // 5% progress for planning phase\n text.length,\n 0,\n `Preparing to replace text in ${text.length} nodes using ${chunks.length} chunks`,\n {\n totalReplacements: text.length,\n chunks: chunks.length,\n chunkSize: CHUNK_SIZE,\n }\n );\n\n // Process each chunk sequentially\n for (let chunkIndex = 0; chunkIndex < chunks.length; chunkIndex++) {\n const chunk = chunks[chunkIndex];\n console.log(\n `Processing chunk ${chunkIndex + 1}/${chunks.length} with ${chunk.length\n } replacements`\n );\n\n // Send chunk processing start update\n sendProgressUpdate(\n commandId,\n \"set_multiple_text_contents\",\n \"in_progress\",\n Math.round(5 + (chunkIndex / chunks.length) * 90), // 5-95% for processing\n text.length,\n successCount + failureCount,\n `Processing text replacements chunk ${chunkIndex + 1}/${chunks.length}`,\n {\n currentChunk: chunkIndex + 1,\n totalChunks: chunks.length,\n successCount,\n failureCount,\n }\n );\n\n // Process replacements within a chunk in parallel\n const chunkPromises = chunk.map(async (replacement) => {\n if (!replacement.nodeId || replacement.text === undefined) {\n console.error(`Missing nodeId or text for replacement`);\n return {\n success: false,\n nodeId: replacement.nodeId || \"unknown\",\n error: \"Missing nodeId or text in replacement entry\",\n };\n }\n\n try {\n console.log(\n `Attempting to replace text in node: ${replacement.nodeId}`\n );\n\n // Get the text node to update (just to check it exists and get original text)\n const textNode = await figma.getNodeByIdAsync(replacement.nodeId);\n\n if (!textNode) {\n console.error(`Text node not found: ${replacement.nodeId}`);\n return {\n success: false,\n nodeId: replacement.nodeId,\n error: `Node not found: ${replacement.nodeId}`,\n };\n }\n\n if (textNode.type !== \"TEXT\") {\n console.error(\n `Node is not a text node: ${replacement.nodeId} (type: ${textNode.type})`\n );\n return {\n success: false,\n nodeId: replacement.nodeId,\n error: `Node is not a text node: ${replacement.nodeId} (type: ${textNode.type})`,\n };\n }\n\n // Save original text for the result\n const originalText = textNode.characters;\n console.log(`Original text: \"${originalText}\"`);\n console.log(`Will translate to: \"${replacement.text}\"`);\n\n // Highlight the node before changing text\n let originalFills;\n try {\n // Save original fills for restoration later\n originalFills = JSON.parse(JSON.stringify(textNode.fills));\n // Apply highlight color (orange with 30% opacity)\n textNode.fills = [\n {\n type: \"SOLID\",\n color: { r: 1, g: 0.5, b: 0 },\n opacity: 0.3,\n },\n ];\n } catch (highlightErr) {\n console.error(\n `Error highlighting text node: ${highlightErr.message}`\n );\n // Continue anyway, highlighting is just visual feedback\n }\n\n // Use the existing setTextContent function to handle font loading and text setting\n await setTextContent({\n nodeId: replacement.nodeId,\n text: replacement.text,\n });\n\n // Keep highlight for a moment after text change, then restore original fills\n if (originalFills) {\n try {\n // Use delay function for consistent timing\n await delay(500);\n textNode.fills = originalFills;\n } catch (restoreErr) {\n console.error(`Error restoring fills: ${restoreErr.message}`);\n }\n }\n\n console.log(\n `Successfully replaced text in node: ${replacement.nodeId}`\n );\n return {\n success: true,\n nodeId: replacement.nodeId,\n originalText: originalText,\n translatedText: replacement.text,\n };\n } catch (error) {\n console.error(\n `Error replacing text in node ${replacement.nodeId}: ${error.message}`\n );\n return {\n success: false,\n nodeId: replacement.nodeId,\n error: `Error applying replacement: ${error.message}`,\n };\n }\n });\n\n // Wait for all replacements in this chunk to complete\n const chunkResults = await Promise.all(chunkPromises);\n\n // Process results for this chunk\n chunkResults.forEach((result) => {\n if (result.success) {\n successCount++;\n } else {\n failureCount++;\n }\n results.push(result);\n });\n\n // Send chunk processing complete update with partial results\n sendProgressUpdate(\n commandId,\n \"set_multiple_text_contents\",\n \"in_progress\",\n Math.round(5 + ((chunkIndex + 1) / chunks.length) * 90), // 5-95% for processing\n text.length,\n successCount + failureCount,\n `Completed chunk ${chunkIndex + 1}/${chunks.length\n }. ${successCount} successful, ${failureCount} failed so far.`,\n {\n currentChunk: chunkIndex + 1,\n totalChunks: chunks.length,\n successCount,\n failureCount,\n chunkResults: chunkResults,\n }\n );\n\n // Add a small delay between chunks to avoid overloading Figma\n if (chunkIndex < chunks.length - 1) {\n console.log(\"Pausing between chunks to avoid overloading Figma...\");\n await delay(1000); // 1 second delay between chunks\n }\n }\n\n console.log(\n `Replacement complete: ${successCount} successful, ${failureCount} failed`\n );\n\n // Send completed progress update\n sendProgressUpdate(\n commandId,\n \"set_multiple_text_contents\",\n \"completed\",\n 100,\n text.length,\n successCount + failureCount,\n `Text replacement complete: ${successCount} successful, ${failureCount} failed`,\n {\n totalReplacements: text.length,\n replacementsApplied: successCount,\n replacementsFailed: failureCount,\n completedInChunks: chunks.length,\n results: results,\n }\n );\n\n return {\n success: successCount > 0,\n nodeId: nodeId,\n replacementsApplied: successCount,\n replacementsFailed: failureCount,\n totalReplacements: text.length,\n results: results,\n completedInChunks: chunks.length,\n commandId,\n };\n}\n\n// Function to generate simple UUIDs for command IDs\nfunction generateCommandId() {\n return (\n \"cmd_\" +\n Math.random().toString(36).substring(2, 15) +\n Math.random().toString(36).substring(2, 15)\n );\n}\n\nasync function getAnnotations(params) {\n try {\n const { nodeId, includeCategories = true } = params;\n\n // Get categories first if needed\n let categoriesMap = {};\n if (includeCategories) {\n const categories = await figma.annotations.getAnnotationCategoriesAsync();\n categoriesMap = categories.reduce((map, category) => {\n map[category.id] = {\n id: category.id,\n label: category.label,\n color: category.color,\n isPreset: category.isPreset,\n };\n return map;\n }, {});\n }\n\n if (nodeId) {\n // Get annotations for a specific node\n const node = await figma.getNodeByIdAsync(nodeId);\n if (!node) {\n throw new Error(`Node not found: ${nodeId}`);\n }\n\n if (!(\"annotations\" in node)) {\n throw new Error(`Node type ${node.type} does not support annotations`);\n }\n\n const result = {\n nodeId: node.id,\n name: node.name,\n annotations: node.annotations || [],\n };\n\n if (includeCategories) {\n result.categories = Object.values(categoriesMap);\n }\n\n return result;\n } else {\n // Get all annotations in the current page\n const annotations = [];\n const processNode = async (node) => {\n if (\n \"annotations\" in node &&\n node.annotations &&\n node.annotations.length > 0\n ) {\n annotations.push({\n nodeId: node.id,\n name: node.name,\n annotations: node.annotations,\n });\n }\n if (\"children\" in node) {\n for (const child of node.children) {\n await processNode(child);\n }\n }\n };\n\n // Start from current page\n await processNode(figma.currentPage);\n\n const result = {\n annotatedNodes: annotations,\n };\n\n if (includeCategories) {\n result.categories = Object.values(categoriesMap);\n }\n\n return result;\n }\n } catch (error) {\n console.error(\"Error in getAnnotations:\", error);\n throw error;\n }\n}\n\nasync function setAnnotation(params) {\n try {\n console.log(\"=== setAnnotation Debug Start ===\");\n console.log(\"Input params:\", JSON.stringify(params, null, 2));\n\n const { nodeId, annotationId, labelMarkdown, categoryId, properties } =\n params;\n\n // Validate required parameters\n if (!nodeId) {\n console.error(\"Validation failed: Missing nodeId\");\n return { success: false, error: \"Missing nodeId\" };\n }\n\n if (!labelMarkdown) {\n console.error(\"Validation failed: Missing labelMarkdown\");\n return { success: false, error: \"Missing labelMarkdown\" };\n }\n\n console.log(\"Attempting to get node:\", nodeId);\n // Get and validate node\n const node = await figma.getNodeByIdAsync(nodeId);\n console.log(\"Node lookup result:\", {\n id: nodeId,\n found: !!node,\n type: node ? node.type : undefined,\n name: node ? node.name : undefined,\n hasAnnotations: node ? \"annotations\" in node : false,\n });\n\n if (!node) {\n console.error(\"Node lookup failed:\", nodeId);\n return { success: false, error: `Node not found: ${nodeId}` };\n }\n\n // Validate node supports annotations\n if (!(\"annotations\" in node)) {\n console.error(\"Node annotation support check failed:\", {\n nodeType: node.type,\n nodeId: node.id,\n });\n return {\n success: false,\n error: `Node type ${node.type} does not support annotations`,\n };\n }\n\n // Create the annotation object\n const newAnnotation = {\n labelMarkdown,\n };\n\n // Validate and add categoryId if provided\n if (categoryId) {\n console.log(\"Adding categoryId to annotation:\", categoryId);\n newAnnotation.categoryId = categoryId;\n }\n\n // Validate and add properties if provided\n if (properties && Array.isArray(properties) && properties.length > 0) {\n console.log(\n \"Adding properties to annotation:\",\n JSON.stringify(properties, null, 2)\n );\n newAnnotation.properties = properties;\n }\n\n // Log current annotations before update\n console.log(\"Current node annotations:\", node.annotations);\n\n // Overwrite annotations\n console.log(\n \"Setting new annotation:\",\n JSON.stringify(newAnnotation, null, 2)\n );\n node.annotations = [newAnnotation];\n\n // Verify the update\n console.log(\"Updated node annotations:\", node.annotations);\n console.log(\"=== setAnnotation Debug End ===\");\n\n return {\n success: true,\n nodeId: node.id,\n name: node.name,\n annotations: node.annotations,\n };\n } catch (error) {\n console.error(\"=== setAnnotation Error ===\");\n console.error(\"Error details:\", {\n message: error.message,\n stack: error.stack,\n params: JSON.stringify(params, null, 2),\n });\n return { success: false, error: error.message };\n }\n}\n\n/**\n * Scan for nodes with specific types within a node\n * @param {Object} params - Parameters object\n * @param {string} params.nodeId - ID of the node to scan within\n * @param {Array} params.types - Array of node types to find (e.g. ['COMPONENT', 'FRAME'])\n * @returns {Object} - Object containing found nodes\n */\nasync function scanNodesByTypes(params) {\n console.log(`Starting to scan nodes by types from node ID: ${params.nodeId}`);\n const { nodeId, types = [] } = params || {};\n\n if (!types || types.length === 0) {\n throw new Error(\"No types specified to search for\");\n }\n\n const node = await figma.getNodeByIdAsync(nodeId);\n\n if (!node) {\n throw new Error(`Node with ID ${nodeId} not found`);\n }\n\n // Simple implementation without chunking\n const matchingNodes = [];\n\n // Send a single progress update to notify start\n const commandId = generateCommandId();\n sendProgressUpdate(\n commandId,\n \"scan_nodes_by_types\",\n \"started\",\n 0,\n 1,\n 0,\n `Starting scan of node \"${node.name || nodeId}\" for types: ${types.join(\n \", \"\n )}`,\n null\n );\n\n // Recursively find nodes with specified types\n await findNodesByTypes(node, types, matchingNodes);\n\n // Send completion update\n sendProgressUpdate(\n commandId,\n \"scan_nodes_by_types\",\n \"completed\",\n 100,\n matchingNodes.length,\n matchingNodes.length,\n `Scan complete. Found ${matchingNodes.length} matching nodes.`,\n { matchingNodes }\n );\n\n return {\n success: true,\n message: `Found ${matchingNodes.length} matching nodes.`,\n count: matchingNodes.length,\n matchingNodes: matchingNodes,\n searchedTypes: types,\n };\n}\n\n/**\n * Helper function to recursively find nodes with specific types\n * @param {SceneNode} node - The root node to start searching from\n * @param {Array} types - Array of node types to find\n * @param {Array} matchingNodes - Array to store found nodes\n */\nasync function findNodesByTypes(node, types, matchingNodes = []) {\n // Skip invisible nodes\n if (node.visible === false) return;\n\n // Check if this node is one of the specified types\n if (types.includes(node.type)) {\n // Create a minimal representation with just ID, type and bbox\n matchingNodes.push({\n id: node.id,\n name: node.name || `Unnamed ${node.type}`,\n type: node.type,\n // Basic bounding box info\n bbox: {\n x: typeof node.x === \"number\" ? node.x : 0,\n y: typeof node.y === \"number\" ? node.y : 0,\n width: typeof node.width === \"number\" ? node.width : 0,\n height: typeof node.height === \"number\" ? node.height : 0,\n },\n });\n }\n\n // Recursively process children of container nodes\n if (\"children\" in node) {\n for (const child of node.children) {\n await findNodesByTypes(child, types, matchingNodes);\n }\n }\n}\n\n// Set multiple annotations with async progress updates\nasync function setMultipleAnnotations(params) {\n console.log(\"=== setMultipleAnnotations Debug Start ===\");\n console.log(\"Input params:\", JSON.stringify(params, null, 2));\n\n const { nodeId, annotations } = params;\n\n if (!annotations || annotations.length === 0) {\n console.error(\"Validation failed: No annotations provided\");\n return { success: false, error: \"No annotations provided\" };\n }\n\n console.log(\n `Processing ${annotations.length} annotations for node ${nodeId}`\n );\n\n const results = [];\n let successCount = 0;\n let failureCount = 0;\n\n // Process annotations sequentially\n for (let i = 0; i < annotations.length; i++) {\n const annotation = annotations[i];\n console.log(\n `\\nProcessing annotation ${i + 1}/${annotations.length}:`,\n JSON.stringify(annotation, null, 2)\n );\n\n try {\n console.log(\"Calling setAnnotation with params:\", {\n nodeId: annotation.nodeId,\n labelMarkdown: annotation.labelMarkdown,\n categoryId: annotation.categoryId,\n properties: annotation.properties,\n });\n\n const result = await setAnnotation({\n nodeId: annotation.nodeId,\n labelMarkdown: annotation.labelMarkdown,\n categoryId: annotation.categoryId,\n properties: annotation.properties,\n });\n\n console.log(\"setAnnotation result:\", JSON.stringify(result, null, 2));\n\n if (result.success) {\n successCount++;\n results.push({ success: true, nodeId: annotation.nodeId });\n console.log(`✓ Annotation ${i + 1} applied successfully`);\n } else {\n failureCount++;\n results.push({\n success: false,\n nodeId: annotation.nodeId,\n error: result.error,\n });\n console.error(`✗ Annotation ${i + 1} failed:`, result.error);\n }\n } catch (error) {\n failureCount++;\n const errorResult = {\n success: false,\n nodeId: annotation.nodeId,\n error: error.message,\n };\n results.push(errorResult);\n console.error(`✗ Annotation ${i + 1} failed with error:`, error);\n console.error(\"Error details:\", {\n message: error.message,\n stack: error.stack,\n });\n }\n }\n\n const summary = {\n success: successCount > 0,\n annotationsApplied: successCount,\n annotationsFailed: failureCount,\n totalAnnotations: annotations.length,\n results: results,\n };\n\n console.log(\"\\n=== setMultipleAnnotations Summary ===\");\n console.log(JSON.stringify(summary, null, 2));\n console.log(\"=== setMultipleAnnotations Debug End ===\");\n\n return summary;\n}\n\nasync function deleteMultipleNodes(params) {\n const { nodeIds } = params || {};\n const commandId = generateCommandId();\n\n if (!nodeIds || !Array.isArray(nodeIds) || nodeIds.length === 0) {\n const errorMsg = \"Missing or invalid nodeIds parameter\";\n sendProgressUpdate(\n commandId,\n \"delete_multiple_nodes\",\n \"error\",\n 0,\n 0,\n 0,\n errorMsg,\n { error: errorMsg }\n );\n throw new Error(errorMsg);\n }\n\n console.log(`Starting deletion of ${nodeIds.length} nodes`);\n\n // Send started progress update\n sendProgressUpdate(\n commandId,\n \"delete_multiple_nodes\",\n \"started\",\n 0,\n nodeIds.length,\n 0,\n `Starting deletion of ${nodeIds.length} nodes`,\n { totalNodes: nodeIds.length }\n );\n\n const results = [];\n let successCount = 0;\n let failureCount = 0;\n\n // Process nodes in chunks of 5 to avoid overwhelming Figma\n const CHUNK_SIZE = 5;\n const chunks = [];\n\n for (let i = 0; i < nodeIds.length; i += CHUNK_SIZE) {\n chunks.push(nodeIds.slice(i, i + CHUNK_SIZE));\n }\n\n console.log(`Split ${nodeIds.length} deletions into ${chunks.length} chunks`);\n\n // Send chunking info update\n sendProgressUpdate(\n commandId,\n \"delete_multiple_nodes\",\n \"in_progress\",\n 5,\n nodeIds.length,\n 0,\n `Preparing to delete ${nodeIds.length} nodes using ${chunks.length} chunks`,\n {\n totalNodes: nodeIds.length,\n chunks: chunks.length,\n chunkSize: CHUNK_SIZE,\n }\n );\n\n // Process each chunk sequentially\n for (let chunkIndex = 0; chunkIndex < chunks.length; chunkIndex++) {\n const chunk = chunks[chunkIndex];\n console.log(\n `Processing chunk ${chunkIndex + 1}/${chunks.length} with ${chunk.length\n } nodes`\n );\n\n // Send chunk processing start update\n sendProgressUpdate(\n commandId,\n \"delete_multiple_nodes\",\n \"in_progress\",\n Math.round(5 + (chunkIndex / chunks.length) * 90),\n nodeIds.length,\n successCount + failureCount,\n `Processing deletion chunk ${chunkIndex + 1}/${chunks.length}`,\n {\n currentChunk: chunkIndex + 1,\n totalChunks: chunks.length,\n successCount,\n failureCount,\n }\n );\n\n // Process deletions within a chunk in parallel\n const chunkPromises = chunk.map(async (nodeId) => {\n try {\n const node = await figma.getNodeByIdAsync(nodeId);\n\n if (!node) {\n console.error(`Node not found: ${nodeId}`);\n return {\n success: false,\n nodeId: nodeId,\n error: `Node not found: ${nodeId}`,\n };\n }\n\n // Save node info before deleting\n const nodeInfo = {\n id: node.id,\n name: node.name,\n type: node.type,\n };\n\n // Delete the node\n node.remove();\n\n console.log(`Successfully deleted node: ${nodeId}`);\n return {\n success: true,\n nodeId: nodeId,\n nodeInfo: nodeInfo,\n };\n } catch (error) {\n console.error(`Error deleting node ${nodeId}: ${error.message}`);\n return {\n success: false,\n nodeId: nodeId,\n error: error.message,\n };\n }\n });\n\n // Wait for all deletions in this chunk to complete\n const chunkResults = await Promise.all(chunkPromises);\n\n // Process results for this chunk\n chunkResults.forEach((result) => {\n if (result.success) {\n successCount++;\n } else {\n failureCount++;\n }\n results.push(result);\n });\n\n // Send chunk processing complete update\n sendProgressUpdate(\n commandId,\n \"delete_multiple_nodes\",\n \"in_progress\",\n Math.round(5 + ((chunkIndex + 1) / chunks.length) * 90),\n nodeIds.length,\n successCount + failureCount,\n `Completed chunk ${chunkIndex + 1}/${chunks.length\n }. ${successCount} successful, ${failureCount} failed so far.`,\n {\n currentChunk: chunkIndex + 1,\n totalChunks: chunks.length,\n successCount,\n failureCount,\n chunkResults: chunkResults,\n }\n );\n\n // Add a small delay between chunks\n if (chunkIndex < chunks.length - 1) {\n console.log(\"Pausing between chunks...\");\n await delay(1000);\n }\n }\n\n console.log(\n `Deletion complete: ${successCount} successful, ${failureCount} failed`\n );\n\n // Send completed progress update\n sendProgressUpdate(\n commandId,\n \"delete_multiple_nodes\",\n \"completed\",\n 100,\n nodeIds.length,\n successCount + failureCount,\n `Node deletion complete: ${successCount} successful, ${failureCount} failed`,\n {\n totalNodes: nodeIds.length,\n nodesDeleted: successCount,\n nodesFailed: failureCount,\n completedInChunks: chunks.length,\n results: results,\n }\n );\n\n return {\n success: successCount > 0,\n nodesDeleted: successCount,\n nodesFailed: failureCount,\n totalNodes: nodeIds.length,\n results: results,\n completedInChunks: chunks.length,\n commandId,\n };\n}\n\n// Implementation for getInstanceOverrides function\nasync function getInstanceOverrides(instanceNode = null) {\n console.log(\"=== getInstanceOverrides called ===\");\n\n let sourceInstance = null;\n\n // Check if an instance node was passed directly\n if (instanceNode) {\n console.log(\"Using provided instance node\");\n\n // Validate that the provided node is an instance\n if (instanceNode.type !== \"INSTANCE\") {\n console.error(\"Provided node is not an instance\");\n figma.notify(\"Provided node is not a component instance\");\n return { success: false, message: \"Provided node is not a component instance\" };\n }\n\n sourceInstance = instanceNode;\n } else {\n // No node provided, use selection\n console.log(\"No node provided, using current selection\");\n\n // Get the current selection\n const selection = figma.currentPage.selection;\n\n // Check if there's anything selected\n if (selection.length === 0) {\n console.log(\"No nodes selected\");\n figma.notify(\"Please select at least one instance\");\n return { success: false, message: \"No nodes selected\" };\n }\n\n // Filter for instances in the selection\n const instances = selection.filter(node => node.type === \"INSTANCE\");\n\n if (instances.length === 0) {\n console.log(\"No instances found in selection\");\n figma.notify(\"Please select at least one component instance\");\n return { success: false, message: \"No instances found in selection\" };\n }\n\n // Take the first instance from the selection\n sourceInstance = instances[0];\n }\n\n try {\n console.log(`Getting instance information:`);\n console.log(sourceInstance);\n\n // Get component overrides and main component\n const overrides = sourceInstance.overrides || [];\n console.log(` Raw Overrides:`, overrides);\n\n // Get main component\n const mainComponent = await sourceInstance.getMainComponentAsync();\n if (!mainComponent) {\n console.error(\"Failed to get main component\");\n figma.notify(\"Failed to get main component\");\n return { success: false, message: \"Failed to get main component\" };\n }\n\n // return data to MCP server\n const returnData = {\n success: true,\n message: `Got component information from \"${sourceInstance.name}\" for overrides.length: ${overrides.length}`,\n sourceInstanceId: sourceInstance.id,\n mainComponentId: mainComponent.id,\n overridesCount: overrides.length\n };\n\n console.log(\"Data to return to MCP server:\", returnData);\n figma.notify(`Got component information from \"${sourceInstance.name}\"`);\n\n return returnData;\n } catch (error) {\n console.error(\"Error in getInstanceOverrides:\", error);\n figma.notify(`Error: ${error.message}`);\n return {\n success: false,\n message: `Error: ${error.message}`\n };\n }\n}\n\n/**\n * Helper function to validate and get target instances\n * @param {string[]} targetNodeIds - Array of instance node IDs\n * @returns {instanceNode[]} targetInstances - Array of target instances\n */\nasync function getValidTargetInstances(targetNodeIds) {\n let targetInstances = [];\n\n // Handle array of instances or single instance\n if (Array.isArray(targetNodeIds)) {\n if (targetNodeIds.length === 0) {\n return { success: false, message: \"No instances provided\" };\n }\n for (const targetNodeId of targetNodeIds) {\n const targetNode = await figma.getNodeByIdAsync(targetNodeId);\n if (targetNode && targetNode.type === \"INSTANCE\") {\n targetInstances.push(targetNode);\n }\n }\n if (targetInstances.length === 0) {\n return { success: false, message: \"No valid instances provided\" };\n }\n } else {\n return { success: false, message: \"Invalid target node IDs provided\" };\n }\n\n\n return { success: true, message: \"Valid target instances provided\", targetInstances };\n}\n\n/**\n * Helper function to validate and get saved override data\n * @param {string} sourceInstanceId - Source instance ID\n * @returns {Promise} - Validation result with source instance data or error\n */\nasync function getSourceInstanceData(sourceInstanceId) {\n if (!sourceInstanceId) {\n return { success: false, message: \"Missing source instance ID\" };\n }\n\n // Get source instance by ID\n const sourceInstance = await figma.getNodeByIdAsync(sourceInstanceId);\n if (!sourceInstance) {\n return {\n success: false,\n message: \"Source instance not found. The original instance may have been deleted.\"\n };\n }\n\n // Verify it's an instance\n if (sourceInstance.type !== \"INSTANCE\") {\n return {\n success: false,\n message: \"Source node is not a component instance.\"\n };\n }\n\n // Get main component\n const mainComponent = await sourceInstance.getMainComponentAsync();\n if (!mainComponent) {\n return {\n success: false,\n message: \"Failed to get main component from source instance.\"\n };\n }\n\n return {\n success: true,\n sourceInstance,\n mainComponent,\n overrides: sourceInstance.overrides || []\n };\n}\n\n/**\n * Sets saved overrides to the selected component instance(s)\n * @param {InstanceNode[] | null} targetInstances - Array of instance nodes to set overrides to\n * @param {Object} sourceResult - Source instance data from getSourceInstanceData\n * @returns {Promise} - Result of the set operation\n */\nasync function setInstanceOverrides(targetInstances, sourceResult) {\n try {\n\n\n const { sourceInstance, mainComponent, overrides } = sourceResult;\n\n console.log(`Processing ${targetInstances.length} instances with ${overrides.length} overrides`);\n console.log(`Source instance: ${sourceInstance.id}, Main component: ${mainComponent.id}`);\n console.log(`Overrides:`, overrides);\n\n // Process all instances\n const results = [];\n let totalAppliedCount = 0;\n\n for (const targetInstance of targetInstances) {\n try {\n // // Skip if trying to apply to the source instance itself\n // if (targetInstance.id === sourceInstance.id) {\n // console.log(`Skipping source instance itself: ${targetInstance.id}`);\n // results.push({\n // success: false,\n // instanceId: targetInstance.id,\n // instanceName: targetInstance.name,\n // message: \"This is the source instance itself, skipping\"\n // });\n // continue;\n // }\n\n // Swap component\n try {\n targetInstance.swapComponent(mainComponent);\n console.log(`Swapped component for instance \"${targetInstance.name}\"`);\n } catch (error) {\n console.error(`Error swapping component for instance \"${targetInstance.name}\":`, error);\n results.push({\n success: false,\n instanceId: targetInstance.id,\n instanceName: targetInstance.name,\n message: `Error: ${error.message}`\n });\n }\n\n // Prepare overrides by replacing node IDs\n let appliedCount = 0;\n\n // Apply each override\n for (const override of overrides) {\n // Skip if no ID or overriddenFields\n if (!override.id || !override.overriddenFields || override.overriddenFields.length === 0) {\n continue;\n }\n\n // Replace source instance ID with target instance ID in the node path\n const overrideNodeId = override.id.replace(sourceInstance.id, targetInstance.id);\n const overrideNode = await figma.getNodeByIdAsync(overrideNodeId);\n\n if (!overrideNode) {\n console.log(`Override node not found: ${overrideNodeId}`);\n continue;\n }\n\n // Get source node to copy properties from\n const sourceNode = await figma.getNodeByIdAsync(override.id);\n if (!sourceNode) {\n console.log(`Source node not found: ${override.id}`);\n continue;\n }\n\n // Apply each overridden field\n let fieldApplied = false;\n for (const field of override.overriddenFields) {\n try {\n if (field === \"componentProperties\") {\n // Apply component properties\n if (sourceNode.componentProperties && overrideNode.componentProperties) {\n const properties = {};\n for (const key in sourceNode.componentProperties) {\n // if INSTANCE_SWAP use id, otherwise use value\n if (sourceNode.componentProperties[key].type === 'INSTANCE_SWAP') {\n properties[key] = sourceNode.componentProperties[key].value;\n \n } else {\n properties[key] = sourceNode.componentProperties[key].value;\n }\n }\n overrideNode.setProperties(properties);\n fieldApplied = true;\n }\n } else if (field === \"characters\" && overrideNode.type === \"TEXT\") {\n // For text nodes, need to load fonts first\n await figma.loadFontAsync(overrideNode.fontName);\n overrideNode.characters = sourceNode.characters;\n fieldApplied = true;\n } else if (field in overrideNode) {\n // Direct property assignment\n overrideNode[field] = sourceNode[field];\n fieldApplied = true;\n }\n } catch (fieldError) {\n console.error(`Error applying field ${field}:`, fieldError);\n }\n }\n\n if (fieldApplied) {\n appliedCount++;\n }\n }\n\n if (appliedCount > 0) {\n totalAppliedCount += appliedCount;\n results.push({\n success: true,\n instanceId: targetInstance.id,\n instanceName: targetInstance.name,\n appliedCount\n });\n console.log(`Applied ${appliedCount} overrides to \"${targetInstance.name}\"`);\n } else {\n results.push({\n success: false,\n instanceId: targetInstance.id,\n instanceName: targetInstance.name,\n message: \"No overrides were applied\"\n });\n }\n } catch (instanceError) {\n console.error(`Error processing instance \"${targetInstance.name}\":`, instanceError);\n results.push({\n success: false,\n instanceId: targetInstance.id,\n instanceName: targetInstance.name,\n message: `Error: ${instanceError.message}`\n });\n }\n }\n\n // Return results\n if (totalAppliedCount > 0) {\n const instanceCount = results.filter(r => r.success).length;\n const message = `Applied ${totalAppliedCount} overrides to ${instanceCount} instances`;\n figma.notify(message);\n return {\n success: true,\n message,\n totalCount: totalAppliedCount,\n results\n };\n } else {\n const message = \"No overrides applied to any instance\";\n figma.notify(message);\n return { success: false, message, results };\n }\n\n } catch (error) {\n console.error(\"Error in setInstanceOverrides:\", error);\n const message = `Error: ${error.message}`;\n figma.notify(message);\n return { success: false, message };\n }\n}\n\nasync function setLayoutMode(params) {\n const { nodeId, layoutMode = \"NONE\", layoutWrap = \"NO_WRAP\" } = params || {};\n\n // Get the target node\n const node = await figma.getNodeByIdAsync(nodeId);\n if (!node) {\n throw new Error(`Node with ID ${nodeId} not found`);\n }\n\n // Check if node is a frame or component that supports layoutMode\n if (\n node.type !== \"FRAME\" &&\n node.type !== \"COMPONENT\" &&\n node.type !== \"COMPONENT_SET\" &&\n node.type !== \"INSTANCE\"\n ) {\n throw new Error(`Node type ${node.type} does not support layoutMode`);\n }\n\n // Set layout mode\n node.layoutMode = layoutMode;\n\n // Set layoutWrap if applicable\n if (layoutMode !== \"NONE\") {\n node.layoutWrap = layoutWrap;\n }\n\n return {\n id: node.id,\n name: node.name,\n layoutMode: node.layoutMode,\n layoutWrap: node.layoutWrap,\n };\n}\n\nasync function setPadding(params) {\n const { nodeId, paddingTop, paddingRight, paddingBottom, paddingLeft } =\n params || {};\n\n // Get the target node\n const node = await figma.getNodeByIdAsync(nodeId);\n if (!node) {\n throw new Error(`Node with ID ${nodeId} not found`);\n }\n\n // Check if node is a frame or component that supports padding\n if (\n node.type !== \"FRAME\" &&\n node.type !== \"COMPONENT\" &&\n node.type !== \"COMPONENT_SET\" &&\n node.type !== \"INSTANCE\"\n ) {\n throw new Error(`Node type ${node.type} does not support padding`);\n }\n\n // Check if the node has auto-layout enabled\n if (node.layoutMode === \"NONE\") {\n throw new Error(\n \"Padding can only be set on auto-layout frames (layoutMode must not be NONE)\"\n );\n }\n\n // Set padding values if provided\n if (paddingTop !== undefined) node.paddingTop = paddingTop;\n if (paddingRight !== undefined) node.paddingRight = paddingRight;\n if (paddingBottom !== undefined) node.paddingBottom = paddingBottom;\n if (paddingLeft !== undefined) node.paddingLeft = paddingLeft;\n\n return {\n id: node.id,\n name: node.name,\n paddingTop: node.paddingTop,\n paddingRight: node.paddingRight,\n paddingBottom: node.paddingBottom,\n paddingLeft: node.paddingLeft,\n };\n}\n\nasync function setAxisAlign(params) {\n const { nodeId, primaryAxisAlignItems, counterAxisAlignItems } = params || {};\n\n // Get the target node\n const node = await figma.getNodeByIdAsync(nodeId);\n if (!node) {\n throw new Error(`Node with ID ${nodeId} not found`);\n }\n\n // Check if node is a frame or component that supports axis alignment\n if (\n node.type !== \"FRAME\" &&\n node.type !== \"COMPONENT\" &&\n node.type !== \"COMPONENT_SET\" &&\n node.type !== \"INSTANCE\"\n ) {\n throw new Error(`Node type ${node.type} does not support axis alignment`);\n }\n\n // Check if the node has auto-layout enabled\n if (node.layoutMode === \"NONE\") {\n throw new Error(\n \"Axis alignment can only be set on auto-layout frames (layoutMode must not be NONE)\"\n );\n }\n\n // Validate and set primaryAxisAlignItems if provided\n if (primaryAxisAlignItems !== undefined) {\n if (\n ![\"MIN\", \"MAX\", \"CENTER\", \"SPACE_BETWEEN\"].includes(primaryAxisAlignItems)\n ) {\n throw new Error(\n \"Invalid primaryAxisAlignItems value. Must be one of: MIN, MAX, CENTER, SPACE_BETWEEN\"\n );\n }\n node.primaryAxisAlignItems = primaryAxisAlignItems;\n }\n\n // Validate and set counterAxisAlignItems if provided\n if (counterAxisAlignItems !== undefined) {\n if (![\"MIN\", \"MAX\", \"CENTER\", \"BASELINE\"].includes(counterAxisAlignItems)) {\n throw new Error(\n \"Invalid counterAxisAlignItems value. Must be one of: MIN, MAX, CENTER, BASELINE\"\n );\n }\n // BASELINE is only valid for horizontal layout\n if (\n counterAxisAlignItems === \"BASELINE\" &&\n node.layoutMode !== \"HORIZONTAL\"\n ) {\n throw new Error(\n \"BASELINE alignment is only valid for horizontal auto-layout frames\"\n );\n }\n node.counterAxisAlignItems = counterAxisAlignItems;\n }\n\n return {\n id: node.id,\n name: node.name,\n primaryAxisAlignItems: node.primaryAxisAlignItems,\n counterAxisAlignItems: node.counterAxisAlignItems,\n layoutMode: node.layoutMode,\n };\n}\n\nasync function setLayoutSizing(params) {\n const { nodeId, layoutSizingHorizontal, layoutSizingVertical } = params || {};\n\n // Get the target node\n const node = await figma.getNodeByIdAsync(nodeId);\n if (!node) {\n throw new Error(`Node with ID ${nodeId} not found`);\n }\n\n // Check if node is a frame or component that supports layout sizing\n if (\n node.type !== \"FRAME\" &&\n node.type !== \"COMPONENT\" &&\n node.type !== \"COMPONENT_SET\" &&\n node.type !== \"INSTANCE\"\n ) {\n throw new Error(`Node type ${node.type} does not support layout sizing`);\n }\n\n // Check if the node has auto-layout enabled\n if (node.layoutMode === \"NONE\") {\n throw new Error(\n \"Layout sizing can only be set on auto-layout frames (layoutMode must not be NONE)\"\n );\n }\n\n // Validate and set layoutSizingHorizontal if provided\n if (layoutSizingHorizontal !== undefined) {\n if (![\"FIXED\", \"HUG\", \"FILL\"].includes(layoutSizingHorizontal)) {\n throw new Error(\n \"Invalid layoutSizingHorizontal value. Must be one of: FIXED, HUG, FILL\"\n );\n }\n // HUG is only valid on auto-layout frames and text nodes\n if (\n layoutSizingHorizontal === \"HUG\" &&\n ![\"FRAME\", \"TEXT\"].includes(node.type)\n ) {\n throw new Error(\n \"HUG sizing is only valid on auto-layout frames and text nodes\"\n );\n }\n // FILL is only valid on auto-layout children\n if (\n layoutSizingHorizontal === \"FILL\" &&\n (!node.parent || node.parent.layoutMode === \"NONE\")\n ) {\n throw new Error(\"FILL sizing is only valid on auto-layout children\");\n }\n node.layoutSizingHorizontal = layoutSizingHorizontal;\n }\n\n // Validate and set layoutSizingVertical if provided\n if (layoutSizingVertical !== undefined) {\n if (![\"FIXED\", \"HUG\", \"FILL\"].includes(layoutSizingVertical)) {\n throw new Error(\n \"Invalid layoutSizingVertical value. Must be one of: FIXED, HUG, FILL\"\n );\n }\n // HUG is only valid on auto-layout frames and text nodes\n if (\n layoutSizingVertical === \"HUG\" &&\n ![\"FRAME\", \"TEXT\"].includes(node.type)\n ) {\n throw new Error(\n \"HUG sizing is only valid on auto-layout frames and text nodes\"\n );\n }\n // FILL is only valid on auto-layout children\n if (\n layoutSizingVertical === \"FILL\" &&\n (!node.parent || node.parent.layoutMode === \"NONE\")\n ) {\n throw new Error(\"FILL sizing is only valid on auto-layout children\");\n }\n node.layoutSizingVertical = layoutSizingVertical;\n }\n\n return {\n id: node.id,\n name: node.name,\n layoutSizingHorizontal: node.layoutSizingHorizontal,\n layoutSizingVertical: node.layoutSizingVertical,\n layoutMode: node.layoutMode,\n };\n}\n\nasync function setItemSpacing(params) {\n const { nodeId, itemSpacing } = params || {};\n\n // Get the target node\n const node = await figma.getNodeByIdAsync(nodeId);\n if (!node) {\n throw new Error(`Node with ID ${nodeId} not found`);\n }\n\n // Check if node is a frame or component that supports item spacing\n if (\n node.type !== \"FRAME\" &&\n node.type !== \"COMPONENT\" &&\n node.type !== \"COMPONENT_SET\" &&\n node.type !== \"INSTANCE\"\n ) {\n throw new Error(`Node type ${node.type} does not support item spacing`);\n }\n\n // Check if the node has auto-layout enabled\n if (node.layoutMode === \"NONE\") {\n throw new Error(\n \"Item spacing can only be set on auto-layout frames (layoutMode must not be NONE)\"\n );\n }\n\n // Set item spacing\n if (itemSpacing !== undefined) {\n if (typeof itemSpacing !== \"number\") {\n throw new Error(\"Item spacing must be a number\");\n }\n node.itemSpacing = itemSpacing;\n }\n\n return {\n id: node.id,\n name: node.name,\n itemSpacing: node.itemSpacing,\n layoutMode: node.layoutMode,\n };\n}\n\nasync function setDefaultConnector(params) {\n const { connectorId } = params || {};\n \n // If connectorId is provided, search and set by that ID (do not check existing storage)\n if (connectorId) {\n // Get node by specified ID\n const node = await figma.getNodeByIdAsync(connectorId);\n if (!node) {\n throw new Error(`Connector node not found with ID: ${connectorId}`);\n }\n \n // Check node type\n if (node.type !== 'CONNECTOR') {\n throw new Error(`Node is not a connector: ${connectorId}`);\n }\n \n // Set the found connector as the default connector\n await figma.clientStorage.setAsync('defaultConnectorId', connectorId);\n \n return {\n success: true,\n message: `Default connector set to: ${connectorId}`,\n connectorId: connectorId\n };\n } \n // If connectorId is not provided, check existing storage\n else {\n // Check if there is an existing default connector in client storage\n try {\n const existingConnectorId = await figma.clientStorage.getAsync('defaultConnectorId');\n \n // If there is an existing connector ID, check if the node is still valid\n if (existingConnectorId) {\n try {\n const existingConnector = await figma.getNodeByIdAsync(existingConnectorId);\n \n // If the stored connector still exists and is of type CONNECTOR\n if (existingConnector && existingConnector.type === 'CONNECTOR') {\n return {\n success: true,\n message: `Default connector is already set to: ${existingConnectorId}`,\n connectorId: existingConnectorId,\n exists: true\n };\n }\n // The stored connector is no longer valid - find a new connector\n else {\n console.log(`Stored connector ID ${existingConnectorId} is no longer valid, finding a new connector...`);\n }\n } catch (error) {\n console.log(`Error finding stored connector: ${error.message}. Will try to set a new one.`);\n }\n }\n } catch (error) {\n console.log(`Error checking for existing connector: ${error.message}`);\n }\n \n // If there is no stored default connector or it is invalid, find one in the current page\n try {\n // Find CONNECTOR type nodes in the current page\n const currentPageConnectors = figma.currentPage.findAllWithCriteria({ types: ['CONNECTOR'] });\n \n if (currentPageConnectors && currentPageConnectors.length > 0) {\n // Use the first connector found\n const foundConnector = currentPageConnectors[0];\n const autoFoundId = foundConnector.id;\n \n // Set the found connector as the default connector\n await figma.clientStorage.setAsync('defaultConnectorId', autoFoundId);\n \n return {\n success: true,\n message: `Automatically found and set default connector to: ${autoFoundId}`,\n connectorId: autoFoundId,\n autoSelected: true\n };\n } else {\n // If no connector is found in the current page, show a guide message\n throw new Error('No connector found in the current page. Please create a connector in Figma first or specify a connector ID.');\n }\n } catch (error) {\n // Error occurred while running findAllWithCriteria\n throw new Error(`Failed to find a connector: ${error.message}`);\n }\n }\n}\n\nasync function createCursorNode(targetNodeId) {\n const svgString = `\n \n `;\n try {\n const targetNode = await figma.getNodeByIdAsync(targetNodeId);\n if (!targetNode) throw new Error(\"Target node not found\");\n\n // The targetNodeId has semicolons since it is a nested node.\n // So we need to get the parent node ID from the target node ID and check if we can appendChild to it or not.\n let parentNodeId = targetNodeId.includes(';') \n ? targetNodeId.split(';')[0] \n : targetNodeId;\n if (!parentNodeId) throw new Error(\"Could not determine parent node ID\");\n\n // Find the parent node to append cursor node as child\n let parentNode = await figma.getNodeByIdAsync(parentNodeId);\n if (!parentNode) throw new Error(\"Parent node not found\");\n\n // If the parent node is not eligible to appendChild, set the parentNode to the parent of the parentNode\n if (parentNode.type === 'INSTANCE' || parentNode.type === 'COMPONENT' || parentNode.type === 'COMPONENT_SET') {\n parentNode = parentNode.parent;\n if (!parentNode) throw new Error(\"Parent node not found\");\n }\n\n // Create the cursor node\n const importedNode = await figma.createNodeFromSvg(svgString);\n if (!importedNode || !importedNode.id) {\n throw new Error(\"Failed to create imported cursor node\");\n }\n importedNode.name = \"TTF_Connector / Mouse Cursor\";\n importedNode.resize(48, 48);\n\n const cursorNode = importedNode.findOne(node => node.type === 'VECTOR');\n if (cursorNode) {\n cursorNode.fills = [{\n type: 'SOLID',\n color: { r: 0, g: 0, b: 0 },\n opacity: 1\n }];\n cursorNode.strokes = [{\n type: 'SOLID',\n color: { r: 1, g: 1, b: 1 },\n opacity: 1\n }];\n cursorNode.strokeWeight = 2;\n cursorNode.strokeAlign = 'OUTSIDE';\n cursorNode.effects = [{\n type: \"DROP_SHADOW\",\n color: { r: 0, g: 0, b: 0, a: 0.3 },\n offset: { x: 1, y: 1 },\n radius: 2,\n spread: 0,\n visible: true,\n blendMode: \"NORMAL\"\n }];\n }\n\n // Append the cursor node to the parent node\n parentNode.appendChild(importedNode);\n\n // if the parentNode has auto-layout enabled, set the layoutPositioning to ABSOLUTE\n if ('layoutMode' in parentNode && parentNode.layoutMode !== 'NONE') {\n importedNode.layoutPositioning = 'ABSOLUTE';\n }\n\n // Adjust the importedNode's position to the targetNode's position\n if (\n targetNode.absoluteBoundingBox &&\n parentNode.absoluteBoundingBox\n ) {\n // if the targetNode has absoluteBoundingBox, set the importedNode's absoluteBoundingBox to the targetNode's absoluteBoundingBox\n console.log('targetNode.absoluteBoundingBox', targetNode.absoluteBoundingBox);\n console.log('parentNode.absoluteBoundingBox', parentNode.absoluteBoundingBox);\n importedNode.x = targetNode.absoluteBoundingBox.x - parentNode.absoluteBoundingBox.x + targetNode.absoluteBoundingBox.width / 2 - 48 / 2\n importedNode.y = targetNode.absoluteBoundingBox.y - parentNode.absoluteBoundingBox.y + targetNode.absoluteBoundingBox.height / 2 - 48 / 2;\n } else if (\n 'x' in targetNode && 'y' in targetNode && 'width' in targetNode && 'height' in targetNode) {\n // if the targetNode has x, y, width, height, calculate center based on relative position\n console.log('targetNode.x/y/width/height', targetNode.x, targetNode.y, targetNode.width, targetNode.height);\n importedNode.x = targetNode.x + targetNode.width / 2 - 48 / 2;\n importedNode.y = targetNode.y + targetNode.height / 2 - 48 / 2;\n } else {\n // Fallback: Place at top-left of target if possible, otherwise at (0,0) relative to parent\n if ('x' in targetNode && 'y' in targetNode) {\n console.log('Fallback to targetNode x/y');\n importedNode.x = targetNode.x;\n importedNode.y = targetNode.y;\n } else {\n console.log('Fallback to (0,0)');\n importedNode.x = 0;\n importedNode.y = 0;\n }\n }\n\n // get the importedNode ID and the importedNode\n console.log('importedNode', importedNode);\n\n\n return { id: importedNode.id, node: importedNode };\n \n } catch (error) {\n console.error(\"Error creating cursor from SVG:\", error);\n return { id: null, node: null, error: error.message };\n }\n}\n\nasync function createConnections(params) {\n if (!params || !params.connections || !Array.isArray(params.connections)) {\n throw new Error('Missing or invalid connections parameter');\n }\n \n const { connections } = params;\n \n // Command ID for progress tracking\n const commandId = generateCommandId();\n sendProgressUpdate(\n commandId,\n \"create_connections\",\n \"started\",\n 0,\n connections.length,\n 0,\n `Starting to create ${connections.length} connections`\n );\n \n // Get default connector ID from client storage\n const defaultConnectorId = await figma.clientStorage.getAsync('defaultConnectorId');\n if (!defaultConnectorId) {\n throw new Error('No default connector set. Please try one of the following options to create connections:\\n1. Create a connector in FigJam and copy/paste it to your current page, then run the \"set_default_connector\" command.\\n2. Select an existing connector on the current page, then run the \"set_default_connector\" command.');\n }\n \n // Get the default connector\n const defaultConnector = await figma.getNodeByIdAsync(defaultConnectorId);\n if (!defaultConnector) {\n throw new Error(`Default connector not found with ID: ${defaultConnectorId}`);\n }\n if (defaultConnector.type !== 'CONNECTOR') {\n throw new Error(`Node is not a connector: ${defaultConnectorId}`);\n }\n \n // Results array for connection creation\n const results = [];\n let processedCount = 0;\n const totalCount = connections.length;\n \n // Preload fonts (used for text if provided)\n let fontLoaded = false;\n \n for (let i = 0; i < connections.length; i++) {\n try {\n const { startNodeId: originalStartId, endNodeId: originalEndId, text } = connections[i];\n let startId = originalStartId;\n let endId = originalEndId;\n\n // Check and potentially replace start node ID\n if (startId.includes(';')) {\n console.log(`Nested start node detected: ${startId}. Creating cursor node.`);\n const cursorResult = await createCursorNode(startId);\n if (!cursorResult || !cursorResult.id) {\n throw new Error(`Failed to create cursor node for nested start node: ${startId}`);\n }\n startId = cursorResult.id; \n } \n \n const startNode = await figma.getNodeByIdAsync(startId);\n if (!startNode) throw new Error(`Start node not found with ID: ${startId}`);\n\n // Check and potentially replace end node ID\n if (endId.includes(';')) {\n console.log(`Nested end node detected: ${endId}. Creating cursor node.`);\n const cursorResult = await createCursorNode(endId);\n if (!cursorResult || !cursorResult.id) {\n throw new Error(`Failed to create cursor node for nested end node: ${endId}`);\n }\n endId = cursorResult.id;\n }\n const endNode = await figma.getNodeByIdAsync(endId);\n if (!endNode) throw new Error(`End node not found with ID: ${endId}`);\n\n \n // Clone the default connector\n const clonedConnector = defaultConnector.clone();\n \n // Update connector name using potentially replaced node names\n clonedConnector.name = `TTF_Connector/${startNode.id}/${endNode.id}`;\n \n // Set start and end points using potentially replaced IDs\n clonedConnector.connectorStart = {\n endpointNodeId: startId,\n magnet: 'AUTO'\n };\n \n clonedConnector.connectorEnd = {\n endpointNodeId: endId,\n magnet: 'AUTO'\n };\n \n // Add text (if provided)\n if (text) {\n try {\n // Try to load the necessary fonts\n try {\n // First check if default connector has font and use the same\n if (defaultConnector.text && defaultConnector.text.fontName) {\n const fontName = defaultConnector.text.fontName;\n await figma.loadFontAsync(fontName);\n clonedConnector.text.fontName = fontName;\n } else {\n // Try default Inter font\n await figma.loadFontAsync({ family: \"Inter\", style: \"Regular\" });\n }\n } catch (fontError) {\n // If first font load fails, try another font style\n try {\n await figma.loadFontAsync({ family: \"Inter\", style: \"Medium\" });\n } catch (mediumFontError) {\n // If second font fails, try system font\n try {\n await figma.loadFontAsync({ family: \"System\", style: \"Regular\" });\n } catch (systemFontError) {\n // If all font loading attempts fail, throw error\n throw new Error(`Failed to load any font: ${fontError.message}`);\n }\n }\n }\n \n // Set the text\n clonedConnector.text.characters = text;\n } catch (textError) {\n console.error(\"Error setting text:\", textError);\n // Continue with connection even if text setting fails\n results.push({\n id: clonedConnector.id,\n startNodeId: startNodeId,\n endNodeId: endNodeId,\n text: \"\",\n textError: textError.message\n });\n \n // Continue to next connection\n continue;\n }\n }\n \n // Add to results (using the *original* IDs for reference if needed)\n results.push({\n id: clonedConnector.id,\n originalStartNodeId: originalStartId,\n originalEndNodeId: originalEndId,\n usedStartNodeId: startId, // ID actually used for connection\n usedEndNodeId: endId, // ID actually used for connection\n text: text || \"\"\n });\n \n // Update progress\n processedCount++;\n sendProgressUpdate(\n commandId,\n \"create_connections\",\n \"in_progress\",\n processedCount / totalCount,\n totalCount,\n processedCount,\n `Created connection ${processedCount}/${totalCount}`\n );\n \n } catch (error) {\n console.error(\"Error creating connection\", error);\n // Continue processing remaining connections even if an error occurs\n processedCount++;\n sendProgressUpdate(\n commandId,\n \"create_connections\",\n \"in_progress\",\n processedCount / totalCount,\n totalCount,\n processedCount,\n `Error creating connection: ${error.message}`\n );\n \n results.push({\n error: error.message,\n connectionInfo: connections[i]\n });\n }\n }\n \n // Completion update\n sendProgressUpdate(\n commandId,\n \"create_connections\",\n \"completed\",\n 1,\n totalCount,\n totalCount,\n `Completed creating ${results.length} connections`\n );\n \n return {\n success: true,\n count: results.length,\n connections: results\n };\n}\n"]], "task_instance_info": {"created_time": "2025-08-20 23:58:36", "created_task_model": "DeepSeek-R1", "function_skeleton": "function uniqBy (arr, predicate) {}", "code_description": "This code segment functions to: Deduplicate elements in a collection by evaluating a custom identifier for each item and preserving only the first occurrence of each unique identifier value."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```javascript\n[TASK_BEGIN]\nfunction uniqBy(arr, predicate) {\n const seen = new Set();\n return arr.filter(item => {\n const key = predicate(item);\n if (seen.has(key)) {\n return false;\n }\n seen.add(key);\n return true;\n });\n}\n[TASK_END]\n```", "inference_time": "2025-08-20 23-59-21"}, "editdistance_info": {"edit_distance": 26.3736, "calculate_time": "2025-08-20 23:59:21", "true_code_clean": "function uniqBy(arr, predicate) {\n const cb = typeof predicate === \"function\" ? predicate : (o) => o[predicate];\n return [\n ...arr\n .reduce((map, item) => {\n const key = item === null || item === undefined ? item : cb(item);\n map.has(key) || map.set(key, item);\n return map;\n }, new Map())\n .values(),\n ];\n}", "predict_code_clean": "function uniqBy(arr, predicate) {\n const seen = new Set();\n return arr.filter(item => {\n const key = predicate(item);\n if (seen.has(key)) {\n return false;\n }\n seen.add(key);\n return true;\n });\n}"}} {"repo_name": "cursor-talk-to-figma-mcp", "file_name": "/cursor-talk-to-figma-mcp/src/cursor_mcp_plugin/code.js", "inference_info": {"prefix_code": "// This is the main code file for the Cursor MCP Figma plugin\n// It handles Figma API commands\n\n// Plugin state\nconst state = {\n serverPort: 3055, // Default port\n};\n\n\n// Helper function for progress updates\nfunction sendProgressUpdate(\n commandId,\n commandType,\n status,\n progress,\n totalItems,\n processedItems,\n message,\n payload = null\n) {\n const update = {\n type: \"command_progress\",\n commandId,\n commandType,\n status,\n progress,\n totalItems,\n processedItems,\n message,\n timestamp: Date.now(),\n };\n\n // Add optional chunk information if present\n if (payload) {\n if (\n payload.currentChunk !== undefined &&\n payload.totalChunks !== undefined\n ) {\n update.currentChunk = payload.currentChunk;\n update.totalChunks = payload.totalChunks;\n update.chunkSize = payload.chunkSize;\n }\n update.payload = payload;\n }\n\n // Send to UI\n figma.ui.postMessage(update);\n console.log(`Progress update: ${status} - ${progress}% - ${message}`);\n\n return update;\n}\n\n// Show UI\nfigma.showUI(__html__, { width: 350, height: 450 });\n\n// Plugin commands from UI\nfigma.ui.onmessage = async (msg) => {\n switch (msg.type) {\n case \"update-settings\":\n updateSettings(msg);\n break;\n case \"notify\":\n figma.notify(msg.message);\n break;\n case \"close-plugin\":\n figma.closePlugin();\n break;\n case \"execute-command\":\n // Execute commands received from UI (which gets them from WebSocket)\n try {\n const result = await handleCommand(msg.command, msg.params);\n // Send result back to UI\n figma.ui.postMessage({\n type: \"command-result\",\n id: msg.id,\n result,\n });\n } catch (error) {\n figma.ui.postMessage({\n type: \"command-error\",\n id: msg.id,\n error: error.message || \"Error executing command\",\n });\n }\n break;\n }\n};\n\n// Listen for plugin commands from menu\nfigma.on(\"run\", ({ command }) => {\n figma.ui.postMessage({ type: \"auto-connect\" });\n});\n\n// Update plugin settings\nfunction updateSettings(settings) {\n if (settings.serverPort) {\n state.serverPort = settings.serverPort;\n }\n\n figma.clientStorage.setAsync(\"settings\", {\n serverPort: state.serverPort,\n });\n}\n\n// Handle commands from UI\nasync function handleCommand(command, params) {\n switch (command) {\n case \"get_document_info\":\n return await getDocumentInfo();\n case \"get_selection\":\n return await getSelection();\n case \"get_node_info\":\n if (!params || !params.nodeId) {\n throw new Error(\"Missing nodeId parameter\");\n }\n return await getNodeInfo(params.nodeId);\n case \"get_nodes_info\":\n if (!params || !params.nodeIds || !Array.isArray(params.nodeIds)) {\n throw new Error(\"Missing or invalid nodeIds parameter\");\n }\n return await getNodesInfo(params.nodeIds);\n case \"read_my_design\":\n return await readMyDesign();\n case \"create_rectangle\":\n return await createRectangle(params);\n case \"create_frame\":\n return await createFrame(params);\n case \"create_text\":\n return await createText(params);\n case \"set_fill_color\":\n return await setFillColor(params);\n case \"set_stroke_color\":\n return await setStrokeColor(params);\n case \"move_node\":\n return await moveNode(params);\n case \"resize_node\":\n return await resizeNode(params);\n case \"delete_node\":\n return await deleteNode(params);\n case \"delete_multiple_nodes\":\n return await deleteMultipleNodes(params);\n case \"get_styles\":\n return await getStyles();\n case \"get_local_components\":\n return await getLocalComponents();\n // case \"get_team_components\":\n // return await getTeamComponents();\n case \"create_component_instance\":\n return await createComponentInstance(params);\n case \"export_node_as_image\":\n return await exportNodeAsImage(params);\n case \"set_corner_radius\":\n return await setCornerRadius(params);\n case \"set_text_content\":\n return await setTextContent(params);\n case \"clone_node\":\n return await cloneNode(params);\n case \"scan_text_nodes\":\n return await scanTextNodes(params);\n case \"set_multiple_text_contents\":\n return await setMultipleTextContents(params);\n case \"get_annotations\":\n return await getAnnotations(params);\n case \"set_annotation\":\n return await setAnnotation(params);\n case \"scan_nodes_by_types\":\n return await scanNodesByTypes(params);\n case \"set_multiple_annotations\":\n return await setMultipleAnnotations(params);\n case \"get_instance_overrides\":\n // Check if instanceNode parameter is provided\n if (params && params.instanceNodeId) {\n // Get the instance node by ID\n const instanceNode = await figma.getNodeByIdAsync(params.instanceNodeId);\n if (!instanceNode) {\n throw new Error(`Instance node not found with ID: ${params.instanceNodeId}`);\n }\n return await getInstanceOverrides(instanceNode);\n }\n // Call without instance node if not provided\n return await getInstanceOverrides();\n\n case \"set_instance_overrides\":\n // Check if instanceNodeIds parameter is provided\n if (params && params.targetNodeIds) {\n // Validate that targetNodeIds is an array\n if (!Array.isArray(params.targetNodeIds)) {\n throw new Error(\"targetNodeIds must be an array\");\n }\n\n // Get the instance nodes by IDs\n const targetNodes = await getValidTargetInstances(params.targetNodeIds);\n if (!targetNodes.success) {\n figma.notify(targetNodes.message);\n return { success: false, message: targetNodes.message };\n }\n\n if (params.sourceInstanceId) {\n\n // get source instance data\n let sourceInstanceData = null;\n sourceInstanceData = await getSourceInstanceData(params.sourceInstanceId);\n\n if (!sourceInstanceData.success) {\n figma.notify(sourceInstanceData.message);\n return { success: false, message: sourceInstanceData.message };\n }\n return await setInstanceOverrides(targetNodes.targetInstances, sourceInstanceData);\n } else {\n throw new Error(\"Missing sourceInstanceId parameter\");\n }\n }\n case \"set_layout_mode\":\n return await setLayoutMode(params);\n case \"set_padding\":\n return await setPadding(params);\n case \"set_axis_align\":\n return await setAxisAlign(params);\n case \"set_layout_sizing\":\n return await setLayoutSizing(params);\n case \"set_item_spacing\":\n return await setItemSpacing(params);\n case \"get_reactions\":\n if (!params || !params.nodeIds || !Array.isArray(params.nodeIds)) {\n throw new Error(\"Missing or invalid nodeIds parameter\");\n }\n return await getReactions(params.nodeIds); \n case \"set_default_connector\":\n return await setDefaultConnector(params);\n case \"create_connections\":\n return await createConnections(params);\n default:\n throw new Error(`Unknown command: ${command}`);\n }\n}\n\n// Command implementations\n\nasync function getDocumentInfo() {\n await figma.currentPage.loadAsync();\n const page = figma.currentPage;\n return {\n name: page.name,\n id: page.id,\n type: page.type,\n children: page.children.map((node) => ({\n id: node.id,\n name: node.name,\n type: node.type,\n })),\n currentPage: {\n id: page.id,\n name: page.name,\n childCount: page.children.length,\n },\n pages: [\n {\n id: page.id,\n name: page.name,\n childCount: page.children.length,\n },\n ],\n };\n}\n\nasync function getSelection() {\n return {\n selectionCount: figma.currentPage.selection.length,\n selection: figma.currentPage.selection.map((node) => ({\n id: node.id,\n name: node.name,\n type: node.type,\n visible: node.visible,\n })),\n };\n}\n\nfunction rgbaToHex(color) {\n var r = Math.round(color.r * 255);\n var g = Math.round(color.g * 255);\n var b = Math.round(color.b * 255);\n var a = color.a !== undefined ? Math.round(color.a * 255) : 255;\n\n if (a === 255) {\n return (\n \"#\" +\n [r, g, b]\n .map((x) => {\n return x.toString(16).padStart(2, \"0\");\n })\n .join(\"\")\n );\n }\n\n return (\n \"#\" +\n [r, g, b, a]\n .map((x) => {\n return x.toString(16).padStart(2, \"0\");\n })\n .join(\"\")\n );\n}\n\nfunction filterFigmaNode(node) {\n if (node.type === \"VECTOR\") {\n return null;\n }\n\n var filtered = {\n id: node.id,\n name: node.name,\n type: node.type,\n };\n\n if (node.fills && node.fills.length > 0) {\n filtered.fills = node.fills.map((fill) => {\n var processedFill = Object.assign({}, fill);\n delete processedFill.boundVariables;\n delete processedFill.imageRef;\n\n if (processedFill.gradientStops) {\n processedFill.gradientStops = processedFill.gradientStops.map(\n (stop) => {\n var processedStop = Object.assign({}, stop);\n if (processedStop.color) {\n processedStop.color = rgbaToHex(processedStop.color);\n }\n delete processedStop.boundVariables;\n return processedStop;\n }\n );\n }\n\n if (processedFill.color) {\n processedFill.color = rgbaToHex(processedFill.color);\n }\n\n return processedFill;\n });\n }\n\n if (node.strokes && node.strokes.length > 0) {\n filtered.strokes = node.strokes.map((stroke) => {\n var processedStroke = Object.assign({}, stroke);\n delete processedStroke.boundVariables;\n if (processedStroke.color) {\n processedStroke.color = rgbaToHex(processedStroke.color);\n }\n return processedStroke;\n });\n }\n\n if (node.cornerRadius !== undefined) {\n filtered.cornerRadius = node.cornerRadius;\n }\n\n if (node.absoluteBoundingBox) {\n filtered.absoluteBoundingBox = node.absoluteBoundingBox;\n }\n\n if (node.characters) {\n filtered.characters = node.characters;\n }\n\n if (node.style) {\n filtered.style = {\n fontFamily: node.style.fontFamily,\n fontStyle: node.style.fontStyle,\n fontWeight: node.style.fontWeight,\n fontSize: node.style.fontSize,\n textAlignHorizontal: node.style.textAlignHorizontal,\n letterSpacing: node.style.letterSpacing,\n lineHeightPx: node.style.lineHeightPx,\n };\n }\n\n if (node.children) {\n filtered.children = node.children\n .map((child) => {\n return filterFigmaNode(child);\n })\n .filter((child) => {\n return child !== null;\n });\n }\n\n return filtered;\n}\n\nasync function getNodeInfo(nodeId) {\n const node = await figma.getNodeByIdAsync(nodeId);\n\n if (!node) {\n throw new Error(`Node not found with ID: ${nodeId}`);\n }\n\n const response = await node.exportAsync({\n format: \"JSON_REST_V1\",\n });\n\n return filterFigmaNode(response.document);\n}\n\nasync function getNodesInfo(nodeIds) {\n try {\n // Load all nodes in parallel\n const nodes = await Promise.all(\n nodeIds.map((id) => figma.getNodeByIdAsync(id))\n );\n\n // Filter out any null values (nodes that weren't found)\n const validNodes = nodes.filter((node) => node !== null);\n\n // Export all valid nodes in parallel\n const responses = await Promise.all(\n validNodes.map(async (node) => {\n const response = await node.exportAsync({\n format: \"JSON_REST_V1\",\n });\n return {\n nodeId: node.id,\n document: filterFigmaNode(response.document),\n };\n })\n );\n\n return responses;\n } catch (error) {\n throw new Error(`Error getting nodes info: ${error.message}`);\n }\n}\n\nasync function getReactions(nodeIds) {\n try {\n const commandId = generateCommandId();\n sendProgressUpdate(\n commandId,\n \"get_reactions\",\n \"started\",\n 0,\n nodeIds.length,\n 0,\n `Starting deep search for reactions in ${nodeIds.length} nodes and their children`\n );\n\n // Function to find nodes with reactions from the node and all its children\n async function findNodesWithReactions(node, processedNodes = new Set(), depth = 0, results = []) {\n // Skip already processed nodes (prevent circular references)\n if (processedNodes.has(node.id)) {\n return results;\n }\n \n processedNodes.add(node.id);\n \n // Check if the current node has reactions\n let filteredReactions = [];\n if (node.reactions && node.reactions.length > 0) {\n // Filter out reactions with navigation === 'CHANGE_TO'\n filteredReactions = node.reactions.filter(r => {\n // Some reactions may have action or actions array\n if (r.action && r.action.navigation === 'CHANGE_TO') return false;\n if (Array.isArray(r.actions)) {\n // If any action in actions array is CHANGE_TO, exclude\n return !r.actions.some(a => a.navigation === 'CHANGE_TO');\n }\n return true;\n });\n }\n const hasFilteredReactions = filteredReactions.length > 0;\n \n // If the node has filtered reactions, add it to results and apply highlight effect\n if (hasFilteredReactions) {\n results.push({\n id: node.id,\n name: node.name,\n type: node.type,\n depth: depth,\n hasReactions: true,\n reactions: filteredReactions,\n path: getNodePath(node)\n });\n // Apply highlight effect (orange border)\n await highlightNodeWithAnimation(node);\n }\n \n // If node has children, recursively search them\n if (node.children) {\n for (const child of node.children) {\n await findNodesWithReactions(child, processedNodes, depth + 1, results);\n }\n }\n \n return results;\n }\n \n // Function to apply animated highlight effect to a node\n async function highlightNodeWithAnimation(node) {\n // Save original stroke properties\n const originalStrokeWeight = node.strokeWeight;\n const originalStrokes = node.strokes ? [...node.strokes] : [];\n \n try {\n // Apply orange border stroke\n node.strokeWeight = 4;\n node.strokes = [{\n type: 'SOLID',\n color: { r: 1, g: 0.5, b: 0 }, // Orange color\n opacity: 0.8\n }];\n \n // Set timeout for animation effect (restore to original after 1.5 seconds)\n setTimeout(() => {\n try {\n // Restore original stroke properties\n node.strokeWeight = originalStrokeWeight;\n node.strokes = originalStrokes;\n } catch (restoreError) {\n console.error(`Error restoring node stroke: ${restoreError.message}`);\n }\n }, 1500);\n } catch (highlightError) {\n console.error(`Error highlighting node: ${highlightError.message}`);\n // Continue even if highlighting fails\n }\n }\n \n // Get node hierarchy path as a string\n function getNodePath(node) {\n const path = [];\n let current = node;\n \n while (current && current.parent) {\n path.unshift(current.name);\n current = current.parent;\n }\n \n return path.join(' > ');\n }\n\n // Array to store all results\n let allResults = [];\n let processedCount = 0;\n const totalCount = nodeIds.length;\n \n // Iterate through each node and its children to search for reactions\n for (let i = 0; i < nodeIds.length; i++) {\n try {\n const nodeId = nodeIds[i];\n const node = await figma.getNodeByIdAsync(nodeId);\n \n if (!node) {\n processedCount++;\n sendProgressUpdate(\n commandId,\n \"get_reactions\",\n \"in_progress\",\n processedCount / totalCount,\n totalCount,\n processedCount,\n `Node not found: ${nodeId}`\n );\n continue;\n }\n \n // Search for reactions in the node and its children\n const processedNodes = new Set();\n const nodeResults = await findNodesWithReactions(node, processedNodes);\n \n // Add results\n allResults = allResults.concat(nodeResults);\n \n // Update progress\n processedCount++;\n sendProgressUpdate(\n commandId,\n \"get_reactions\",\n \"in_progress\",\n processedCount / totalCount,\n totalCount,\n processedCount,\n `Processed node ${processedCount}/${totalCount}, found ${nodeResults.length} nodes with reactions`\n );\n } catch (error) {\n processedCount++;\n sendProgressUpdate(\n commandId,\n \"get_reactions\",\n \"in_progress\",\n processedCount / totalCount,\n totalCount,\n processedCount,\n `Error processing node: ${error.message}`\n );\n }\n }\n\n // Completion update\n sendProgressUpdate(\n commandId,\n \"get_reactions\",\n \"completed\",\n 1,\n totalCount,\n totalCount,\n `Completed deep search: found ${allResults.length} nodes with reactions.`\n );\n\n return {\n nodesCount: nodeIds.length,\n nodesWithReactions: allResults.length,\n nodes: allResults\n };\n } catch (error) {\n throw new Error(`Failed to get reactions: ${error.message}`);\n }\n}\n\nasync function readMyDesign() {\n try {\n // Load all selected nodes in parallel\n const nodes = await Promise.all(\n figma.currentPage.selection.map((node) => figma.getNodeByIdAsync(node.id))\n );\n\n // Filter out any null values (nodes that weren't found)\n const validNodes = nodes.filter((node) => node !== null);\n\n // Export all valid nodes in parallel\n const responses = await Promise.all(\n validNodes.map(async (node) => {\n const response = await node.exportAsync({\n format: \"JSON_REST_V1\",\n });\n return {\n nodeId: node.id,\n document: filterFigmaNode(response.document),\n };\n })\n );\n\n return responses;\n } catch (error) {\n throw new Error(`Error getting nodes info: ${error.message}`);\n }\n}\n\nasync function createRectangle(params) {\n const {\n x = 0,\n y = 0,\n width = 100,\n height = 100,\n name = \"Rectangle\",\n parentId,\n } = params || {};\n\n const rect = figma.createRectangle();\n rect.x = x;\n rect.y = y;\n rect.resize(width, height);\n rect.name = name;\n\n // If parentId is provided, append to that node, otherwise append to current page\n if (parentId) {\n const parentNode = await figma.getNodeByIdAsync(parentId);\n if (!parentNode) {\n throw new Error(`Parent node not found with ID: ${parentId}`);\n }\n if (!(\"appendChild\" in parentNode)) {\n throw new Error(`Parent node does not support children: ${parentId}`);\n }\n parentNode.appendChild(rect);\n } else {\n figma.currentPage.appendChild(rect);\n }\n\n return {\n id: rect.id,\n name: rect.name,\n x: rect.x,\n y: rect.y,\n width: rect.width,\n height: rect.height,\n parentId: rect.parent ? rect.parent.id : undefined,\n };\n}\n\nasync function createFrame(params) {\n const {\n x = 0,\n y = 0,\n width = 100,\n height = 100,\n name = \"Frame\",\n parentId,\n fillColor,\n strokeColor,\n strokeWeight,\n layoutMode = \"NONE\",\n layoutWrap = \"NO_WRAP\",\n paddingTop = 10,\n paddingRight = 10,\n paddingBottom = 10,\n paddingLeft = 10,\n primaryAxisAlignItems = \"MIN\",\n counterAxisAlignItems = \"MIN\",\n layoutSizingHorizontal = \"FIXED\",\n layoutSizingVertical = \"FIXED\",\n itemSpacing = 0,\n } = params || {};\n\n const frame = figma.createFrame();\n frame.x = x;\n frame.y = y;\n frame.resize(width, height);\n frame.name = name;\n\n // Set layout mode if provided\n if (layoutMode !== \"NONE\") {\n frame.layoutMode = layoutMode;\n frame.layoutWrap = layoutWrap;\n\n // Set padding values only when layoutMode is not NONE\n frame.paddingTop = paddingTop;\n frame.paddingRight = paddingRight;\n frame.paddingBottom = paddingBottom;\n frame.paddingLeft = paddingLeft;\n\n // Set axis alignment only when layoutMode is not NONE\n frame.primaryAxisAlignItems = primaryAxisAlignItems;\n frame.counterAxisAlignItems = counterAxisAlignItems;\n\n // Set layout sizing only when layoutMode is not NONE\n frame.layoutSizingHorizontal = layoutSizingHorizontal;\n frame.layoutSizingVertical = layoutSizingVertical;\n\n // Set item spacing only when layoutMode is not NONE\n frame.itemSpacing = itemSpacing;\n }\n\n // Set fill color if provided\n if (fillColor) {\n const paintStyle = {\n type: \"SOLID\",\n color: {\n r: parseFloat(fillColor.r) || 0,\n g: parseFloat(fillColor.g) || 0,\n b: parseFloat(fillColor.b) || 0,\n },\n opacity: parseFloat(fillColor.a) || 1,\n };\n frame.fills = [paintStyle];\n }\n\n // Set stroke color and weight if provided\n if (strokeColor) {\n const strokeStyle = {\n type: \"SOLID\",\n color: {\n r: parseFloat(strokeColor.r) || 0,\n g: parseFloat(strokeColor.g) || 0,\n b: parseFloat(strokeColor.b) || 0,\n },\n opacity: parseFloat(strokeColor.a) || 1,\n };\n frame.strokes = [strokeStyle];\n }\n\n // Set stroke weight if provided\n if (strokeWeight !== undefined) {\n frame.strokeWeight = strokeWeight;\n }\n\n // If parentId is provided, append to that node, otherwise append to current page\n if (parentId) {\n const parentNode = await figma.getNodeByIdAsync(parentId);\n if (!parentNode) {\n throw new Error(`Parent node not found with ID: ${parentId}`);\n }\n if (!(\"appendChild\" in parentNode)) {\n throw new Error(`Parent node does not support children: ${parentId}`);\n }\n parentNode.appendChild(frame);\n } else {\n figma.currentPage.appendChild(frame);\n }\n\n return {\n id: frame.id,\n name: frame.name,\n x: frame.x,\n y: frame.y,\n width: frame.width,\n height: frame.height,\n fills: frame.fills,\n strokes: frame.strokes,\n strokeWeight: frame.strokeWeight,\n layoutMode: frame.layoutMode,\n layoutWrap: frame.layoutWrap,\n parentId: frame.parent ? frame.parent.id : undefined,\n };\n}\n\nasync function createText(params) {\n const {\n x = 0,\n y = 0,\n text = \"Text\",\n fontSize = 14,\n fontWeight = 400,\n fontColor = { r: 0, g: 0, b: 0, a: 1 }, // Default to black\n name = \"\",\n parentId,\n } = params || {};\n\n // Map common font weights to Figma font styles\n const getFontStyle = (weight) => {\n switch (weight) {\n case 100:\n return \"Thin\";\n case 200:\n return \"Extra Light\";\n case 300:\n return \"Light\";\n case 400:\n return \"Regular\";\n case 500:\n return \"Medium\";\n case 600:\n return \"Semi Bold\";\n case 700:\n return \"Bold\";\n case 800:\n return \"Extra Bold\";\n case 900:\n return \"Black\";\n default:\n return \"Regular\";\n }\n };\n\n const textNode = figma.createText();\n textNode.x = x;\n textNode.y = y;\n textNode.name = name || text;\n try {\n await figma.loadFontAsync({\n family: \"Inter\",\n style: getFontStyle(fontWeight),\n });\n textNode.fontName = { family: \"Inter\", style: getFontStyle(fontWeight) };\n textNode.fontSize = parseInt(fontSize);\n } catch (error) {\n console.error(\"Error setting font size\", error);\n }\n setCharacters(textNode, text);\n\n // Set text color\n const paintStyle = {\n type: \"SOLID\",\n color: {\n r: parseFloat(fontColor.r) || 0,\n g: parseFloat(fontColor.g) || 0,\n b: parseFloat(fontColor.b) || 0,\n },\n opacity: parseFloat(fontColor.a) || 1,\n };\n textNode.fills = [paintStyle];\n\n // If parentId is provided, append to that node, otherwise append to current page\n if (parentId) {\n const parentNode = await figma.getNodeByIdAsync(parentId);\n if (!parentNode) {\n throw new Error(`Parent node not found with ID: ${parentId}`);\n }\n if (!(\"appendChild\" in parentNode)) {\n throw new Error(`Parent node does not support children: ${parentId}`);\n }\n parentNode.appendChild(textNode);\n } else {\n figma.currentPage.appendChild(textNode);\n }\n\n return {\n id: textNode.id,\n name: textNode.name,\n x: textNode.x,\n y: textNode.y,\n width: textNode.width,\n height: textNode.height,\n characters: textNode.characters,\n fontSize: textNode.fontSize,\n fontWeight: fontWeight,\n fontColor: fontColor,\n fontName: textNode.fontName,\n fills: textNode.fills,\n parentId: textNode.parent ? textNode.parent.id : undefined,\n };\n}\n\nasync function setFillColor(params) {\n console.log(\"setFillColor\", params);\n const {\n nodeId,\n color: { r, g, b, a },\n } = params || {};\n\n if (!nodeId) {\n throw new Error(\"Missing nodeId parameter\");\n }\n\n const node = await figma.getNodeByIdAsync(nodeId);\n if (!node) {\n throw new Error(`Node not found with ID: ${nodeId}`);\n }\n\n if (!(\"fills\" in node)) {\n throw new Error(`Node does not support fills: ${nodeId}`);\n }\n\n // Create RGBA color\n const rgbColor = {\n r: parseFloat(r) || 0,\n g: parseFloat(g) || 0,\n b: parseFloat(b) || 0,\n a: parseFloat(a) || 1,\n };\n\n // Set fill\n const paintStyle = {\n type: \"SOLID\",\n color: {\n r: parseFloat(rgbColor.r),\n g: parseFloat(rgbColor.g),\n b: parseFloat(rgbColor.b),\n },\n opacity: parseFloat(rgbColor.a),\n };\n\n console.log(\"paintStyle\", paintStyle);\n\n node.fills = [paintStyle];\n\n return {\n id: node.id,\n name: node.name,\n fills: [paintStyle],\n };\n}\n\nasync function setStrokeColor(params) {\n const {\n nodeId,\n color: { r, g, b, a },\n weight = 1,\n } = params || {};\n\n if (!nodeId) {\n throw new Error(\"Missing nodeId parameter\");\n }\n\n const node = await figma.getNodeByIdAsync(nodeId);\n if (!node) {\n throw new Error(`Node not found with ID: ${nodeId}`);\n }\n\n if (!(\"strokes\" in node)) {\n throw new Error(`Node does not support strokes: ${nodeId}`);\n }\n\n // Create RGBA color\n const rgbColor = {\n r: r !== undefined ? r : 0,\n g: g !== undefined ? g : 0,\n b: b !== undefined ? b : 0,\n a: a !== undefined ? a : 1,\n };\n\n // Set stroke\n const paintStyle = {\n type: \"SOLID\",\n color: {\n r: rgbColor.r,\n g: rgbColor.g,\n b: rgbColor.b,\n },\n opacity: rgbColor.a,\n };\n\n node.strokes = [paintStyle];\n\n // Set stroke weight if available\n if (\"strokeWeight\" in node) {\n node.strokeWeight = weight;\n }\n\n return {\n id: node.id,\n name: node.name,\n strokes: node.strokes,\n strokeWeight: \"strokeWeight\" in node ? node.strokeWeight : undefined,\n };\n}\n\nasync function moveNode(params) {\n const { nodeId, x, y } = params || {};\n\n if (!nodeId) {\n throw new Error(\"Missing nodeId parameter\");\n }\n\n if (x === undefined || y === undefined) {\n throw new Error(\"Missing x or y parameters\");\n }\n\n const node = await figma.getNodeByIdAsync(nodeId);\n if (!node) {\n throw new Error(`Node not found with ID: ${nodeId}`);\n }\n\n if (!(\"x\" in node) || !(\"y\" in node)) {\n throw new Error(`Node does not support position: ${nodeId}`);\n }\n\n node.x = x;\n node.y = y;\n\n return {\n id: node.id,\n name: node.name,\n x: node.x,\n y: node.y,\n };\n}\n\nasync function resizeNode(params) {\n const { nodeId, width, height } = params || {};\n\n if (!nodeId) {\n throw new Error(\"Missing nodeId parameter\");\n }\n\n if (width === undefined || height === undefined) {\n throw new Error(\"Missing width or height parameters\");\n }\n\n const node = await figma.getNodeByIdAsync(nodeId);\n if (!node) {\n throw new Error(`Node not found with ID: ${nodeId}`);\n }\n\n if (!(\"resize\" in node)) {\n throw new Error(`Node does not support resizing: ${nodeId}`);\n }\n\n node.resize(width, height);\n\n return {\n id: node.id,\n name: node.name,\n width: node.width,\n height: node.height,\n };\n}\n\nasync function deleteNode(params) {\n const { nodeId } = params || {};\n\n if (!nodeId) {\n throw new Error(\"Missing nodeId parameter\");\n }\n\n const node = await figma.getNodeByIdAsync(nodeId);\n if (!node) {\n throw new Error(`Node not found with ID: ${nodeId}`);\n }\n\n // Save node info before deleting\n const nodeInfo = {\n id: node.id,\n name: node.name,\n type: node.type,\n };\n\n node.remove();\n\n return nodeInfo;\n}\n\nasync function getStyles() {\n const styles = {\n colors: await figma.getLocalPaintStylesAsync(),\n texts: await figma.getLocalTextStylesAsync(),\n effects: await figma.getLocalEffectStylesAsync(),\n grids: await figma.getLocalGridStylesAsync(),\n };\n\n return {\n colors: styles.colors.map((style) => ({\n id: style.id,\n name: style.name,\n key: style.key,\n paint: style.paints[0],\n })),\n texts: styles.texts.map((style) => ({\n id: style.id,\n name: style.name,\n key: style.key,\n fontSize: style.fontSize,\n fontName: style.fontName,\n })),\n effects: styles.effects.map((style) => ({\n id: style.id,\n name: style.name,\n key: style.key,\n })),\n grids: styles.grids.map((style) => ({\n id: style.id,\n name: style.name,\n key: style.key,\n })),\n };\n}\n\nasync function getLocalComponents() {\n await figma.loadAllPagesAsync();\n\n const components = figma.root.findAllWithCriteria({\n types: [\"COMPONENT\"],\n });\n\n return {\n count: components.length,\n components: components.map((component) => ({\n id: component.id,\n name: component.name,\n key: \"key\" in component ? component.key : null,\n })),\n };\n}\n\n// async function getTeamComponents() {\n// try {\n// const teamComponents =\n// await figma.teamLibrary.getAvailableComponentsAsync();\n\n// return {\n// count: teamComponents.length,\n// components: teamComponents.map((component) => ({\n// key: component.key,\n// name: component.name,\n// description: component.description,\n// libraryName: component.libraryName,\n// })),\n// };\n// } catch (error) {\n// throw new Error(`Error getting team components: ${error.message}`);\n// }\n// }\n\nasync function createComponentInstance(params) {\n const { componentKey, x = 0, y = 0 } = params || {};\n\n if (!componentKey) {\n throw new Error(\"Missing componentKey parameter\");\n }\n\n try {\n const component = await figma.importComponentByKeyAsync(componentKey);\n const instance = component.createInstance();\n\n instance.x = x;\n instance.y = y;\n\n figma.currentPage.appendChild(instance);\n\n return {\n id: instance.id,\n name: instance.name,\n x: instance.x,\n y: instance.y,\n width: instance.width,\n height: instance.height,\n componentId: instance.componentId,\n };\n } catch (error) {\n throw new Error(`Error creating component instance: ${error.message}`);\n }\n}\n\nasync function exportNodeAsImage(params) {\n const { nodeId, scale = 1 } = params || {};\n\n const format = \"PNG\";\n\n if (!nodeId) {\n throw new Error(\"Missing nodeId parameter\");\n }\n\n const node = await figma.getNodeByIdAsync(nodeId);\n if (!node) {\n throw new Error(`Node not found with ID: ${nodeId}`);\n }\n\n if (!(\"exportAsync\" in node)) {\n throw new Error(`Node does not support exporting: ${nodeId}`);\n }\n\n try {\n const settings = {\n format: format,\n constraint: { type: \"SCALE\", value: scale },\n };\n\n const bytes = await node.exportAsync(settings);\n\n let mimeType;\n switch (format) {\n case \"PNG\":\n mimeType = \"image/png\";\n break;\n case \"JPG\":\n mimeType = \"image/jpeg\";\n break;\n case \"SVG\":\n mimeType = \"image/svg+xml\";\n break;\n case \"PDF\":\n mimeType = \"application/pdf\";\n break;\n default:\n mimeType = \"application/octet-stream\";\n }\n\n // Proper way to convert Uint8Array to base64\n const base64 = customBase64Encode(bytes);\n // const imageData = `data:${mimeType};base64,${base64}`;\n\n return {\n nodeId,\n format,\n scale,\n mimeType,\n imageData: base64,\n };\n } catch (error) {\n throw new Error(`Error exporting node as image: ${error.message}`);\n }\n}\nfunction customBase64Encode(bytes) {\n const chars =\n \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n let base64 = \"\";\n\n const byteLength = bytes.byteLength;\n const byteRemainder = byteLength % 3;\n const mainLength = byteLength - byteRemainder;\n\n let a, b, c, d;\n let chunk;\n\n // Main loop deals with bytes in chunks of 3\n for (let i = 0; i < mainLength; i = i + 3) {\n // Combine the three bytes into a single integer\n chunk = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2];\n\n // Use bitmasks to extract 6-bit segments from the triplet\n a = (chunk & 16515072) >> 18; // 16515072 = (2^6 - 1) << 18\n b = (chunk & 258048) >> 12; // 258048 = (2^6 - 1) << 12\n c = (chunk & 4032) >> 6; // 4032 = (2^6 - 1) << 6\n d = chunk & 63; // 63 = 2^6 - 1\n\n // Convert the raw binary segments to the appropriate ASCII encoding\n base64 += chars[a] + chars[b] + chars[c] + chars[d];\n }\n\n // Deal with the remaining bytes and padding\n if (byteRemainder === 1) {\n chunk = bytes[mainLength];\n\n a = (chunk & 252) >> 2; // 252 = (2^6 - 1) << 2\n\n // Set the 4 least significant bits to zero\n b = (chunk & 3) << 4; // 3 = 2^2 - 1\n\n base64 += chars[a] + chars[b] + \"==\";\n } else if (byteRemainder === 2) {\n chunk = (bytes[mainLength] << 8) | bytes[mainLength + 1];\n\n a = (chunk & 64512) >> 10; // 64512 = (2^6 - 1) << 10\n b = (chunk & 1008) >> 4; // 1008 = (2^6 - 1) << 4\n\n // Set the 2 least significant bits to zero\n c = (chunk & 15) << 2; // 15 = 2^4 - 1\n\n base64 += chars[a] + chars[b] + chars[c] + \"=\";\n }\n\n return base64;\n}\n\nasync function setCornerRadius(params) {\n const { nodeId, radius, corners } = params || {};\n\n if (!nodeId) {\n throw new Error(\"Missing nodeId parameter\");\n }\n\n if (radius === undefined) {\n throw new Error(\"Missing radius parameter\");\n }\n\n const node = await figma.getNodeByIdAsync(nodeId);\n if (!node) {\n throw new Error(`Node not found with ID: ${nodeId}`);\n }\n\n // Check if node supports corner radius\n if (!(\"cornerRadius\" in node)) {\n throw new Error(`Node does not support corner radius: ${nodeId}`);\n }\n\n // If corners array is provided, set individual corner radii\n if (corners && Array.isArray(corners) && corners.length === 4) {\n if (\"topLeftRadius\" in node) {\n // Node supports individual corner radii\n if (corners[0]) node.topLeftRadius = radius;\n if (corners[1]) node.topRightRadius = radius;\n if (corners[2]) node.bottomRightRadius = radius;\n if (corners[3]) node.bottomLeftRadius = radius;\n } else {\n // Node only supports uniform corner radius\n node.cornerRadius = radius;\n }\n } else {\n // Set uniform corner radius\n node.cornerRadius = radius;\n }\n\n return {\n id: node.id,\n name: node.name,\n cornerRadius: \"cornerRadius\" in node ? node.cornerRadius : undefined,\n topLeftRadius: \"topLeftRadius\" in node ? node.topLeftRadius : undefined,\n topRightRadius: \"topRightRadius\" in node ? node.topRightRadius : undefined,\n bottomRightRadius:\n \"bottomRightRadius\" in node ? node.bottomRightRadius : undefined,\n bottomLeftRadius:\n \"bottomLeftRadius\" in node ? node.bottomLeftRadius : undefined,\n };\n}\n\nasync function setTextContent(params) {\n const { nodeId, text } = params || {};\n\n if (!nodeId) {\n throw new Error(\"Missing nodeId parameter\");\n }\n\n if (text === undefined) {\n throw new Error(\"Missing text parameter\");\n }\n\n const node = await figma.getNodeByIdAsync(nodeId);\n if (!node) {\n throw new Error(`Node not found with ID: ${nodeId}`);\n }\n\n if (node.type !== \"TEXT\") {\n throw new Error(`Node is not a text node: ${nodeId}`);\n }\n\n try {\n await figma.loadFontAsync(node.fontName);\n\n await setCharacters(node, text);\n\n return {\n id: node.id,\n name: node.name,\n characters: node.characters,\n fontName: node.fontName,\n };\n } catch (error) {\n throw new Error(`Error setting text content: ${error.message}`);\n }\n}\n\n// Initialize settings on load\n(async function initializePlugin() {\n try {\n const savedSettings = await figma.clientStorage.getAsync(\"settings\");\n if (savedSettings) {\n if (savedSettings.serverPort) {\n state.serverPort = savedSettings.serverPort;\n }\n }\n\n // Send initial settings to UI\n figma.ui.postMessage({\n type: \"init-settings\",\n settings: {\n serverPort: state.serverPort,\n },\n });\n } catch (error) {\n console.error(\"Error loading settings:\", error);\n }\n})();\n\nfunction uniqBy(arr, predicate) {\n const cb = typeof predicate === \"function\" ? predicate : (o) => o[predicate];\n return [\n ...arr\n .reduce((map, item) => {\n const key = item === null || item === undefined ? item : cb(item);\n\n map.has(key) || map.set(key, item);\n\n return map;\n }, new Map())\n .values(),\n ];\n}\nconst setCharacters = async (node, characters, options) => {\n const fallbackFont = (options && options.fallbackFont) || {\n family: \"Inter\",\n style: \"Regular\",\n };\n try {\n if (node.fontName === figma.mixed) {\n if (options && options.smartStrategy === \"prevail\") {\n const fontHashTree = {};\n for (let i = 1; i < node.characters.length; i++) {\n const charFont = node.getRangeFontName(i - 1, i);\n const key = `${charFont.family}::${charFont.style}`;\n fontHashTree[key] = fontHashTree[key] ? fontHashTree[key] + 1 : 1;\n }\n const prevailedTreeItem = Object.entries(fontHashTree).sort(\n (a, b) => b[1] - a[1]\n )[0];\n const [family, style] = prevailedTreeItem[0].split(\"::\");\n const prevailedFont = {\n family,\n style,\n };\n await figma.loadFontAsync(prevailedFont);\n node.fontName = prevailedFont;\n } else if (options && options.smartStrategy === \"strict\") {\n return setCharactersWithStrictMatchFont(node, characters, fallbackFont);\n } else if (options && options.smartStrategy === \"experimental\") {\n return setCharactersWithSmartMatchFont(node, characters, fallbackFont);\n } else {\n const firstCharFont = node.getRangeFontName(0, 1);\n await figma.loadFontAsync(firstCharFont);\n node.fontName = firstCharFont;\n }\n } else {\n await figma.loadFontAsync({\n family: node.fontName.family,\n style: node.fontName.style,\n });\n }\n } catch (err) {\n console.warn(\n `Failed to load \"${node.fontName[\"family\"]} ${node.fontName[\"style\"]}\" font and replaced with fallback \"${fallbackFont.family} ${fallbackFont.style}\"`,\n err\n );\n await figma.loadFontAsync(fallbackFont);\n node.fontName = fallbackFont;\n }\n try {\n node.characters = characters;\n return true;\n } catch (err) {\n console.warn(`Failed to set characters. Skipped.`, err);\n return false;\n }\n};\n\nconst setCharactersWithStrictMatchFont = async (\n node,\n characters,\n fallbackFont\n) => {\n const fontHashTree = {};\n for (let i = 1; i < node.characters.length; i++) {\n const startIdx = i - 1;\n const startCharFont = node.getRangeFontName(startIdx, i);\n const startCharFontVal = `${startCharFont.family}::${startCharFont.style}`;\n while (i < node.characters.length) {\n i++;\n const charFont = node.getRangeFontName(i - 1, i);\n if (startCharFontVal !== `${charFont.family}::${charFont.style}`) {\n break;\n }\n }\n fontHashTree[`${startIdx}_${i}`] = startCharFontVal;\n }\n await figma.loadFontAsync(fallbackFont);\n node.fontName = fallbackFont;\n node.characters = characters;\n console.log(fontHashTree);\n await Promise.all(\n Object.keys(fontHashTree).map(async (range) => {\n console.log(range, fontHashTree[range]);\n const [start, end] = range.split(\"_\");\n const [family, style] = fontHashTree[range].split(\"::\");\n const matchedFont = {\n family,\n style,\n };\n await figma.loadFontAsync(matchedFont);\n return node.setRangeFontName(Number(start), Number(end), matchedFont);\n })\n );\n return true;\n};\n\nconst getDelimiterPos = (str, delimiter, startIdx = 0, endIdx = str.length) => {\n const indices = [];\n let temp = startIdx;\n for (let i = startIdx; i < endIdx; i++) {\n if (\n str[i] === delimiter &&\n i + startIdx !== endIdx &&\n temp !== i + startIdx\n ) {\n indices.push([temp, i + startIdx]);\n temp = i + startIdx + 1;\n }\n }\n temp !== endIdx && indices.push([temp, endIdx]);\n return indices.filter(Boolean);\n};\n\nconst buildLinearOrder = (node) => {\n const fontTree = [];\n const newLinesPos = getDelimiterPos(node.characters, \"\\n\");\n newLinesPos.forEach(([newLinesRangeStart, newLinesRangeEnd], n) => {\n const newLinesRangeFont = node.getRangeFontName(\n newLinesRangeStart,\n newLinesRangeEnd\n );\n if (newLinesRangeFont === figma.mixed) {\n const spacesPos = getDelimiterPos(\n node.characters,\n \" \",\n newLinesRangeStart,\n newLinesRangeEnd\n );\n spacesPos.forEach(([spacesRangeStart, spacesRangeEnd], s) => {\n const spacesRangeFont = node.getRangeFontName(\n spacesRangeStart,\n spacesRangeEnd\n );\n if (spacesRangeFont === figma.mixed) {\n const spacesRangeFont = node.getRangeFontName(\n spacesRangeStart,\n spacesRangeStart[0]\n );\n fontTree.push({\n start: spacesRangeStart,\n delimiter: \" \",\n family: spacesRangeFont.family,\n style: spacesRangeFont.style,\n });\n } else {\n fontTree.push({\n start: spacesRangeStart,\n delimiter: \" \",\n family: spacesRangeFont.family,\n style: spacesRangeFont.style,\n });\n }\n });\n } else {\n fontTree.push({\n start: newLinesRangeStart,\n delimiter: \"\\n\",\n family: newLinesRangeFont.family,\n style: newLinesRangeFont.style,\n });\n }\n });\n return fontTree\n .sort((a, b) => +a.start - +b.start)\n .map(({ family, style, delimiter }) => ({ family, style, delimiter }));\n};\n\nconst setCharactersWithSmartMatchFont = async (\n node,\n characters,\n fallbackFont\n) => {\n const rangeTree = buildLinearOrder(node);\n const fontsToLoad = uniqBy(\n rangeTree,\n ({ family, style }) => `${family}::${style}`\n ).map(({ family, style }) => ({\n family,\n style,\n }));\n\n await Promise.all([...fontsToLoad, fallbackFont].map(figma.loadFontAsync));\n\n node.fontName = fallbackFont;\n node.characters = characters;\n\n let prevPos = 0;\n rangeTree.forEach(({ family, style, delimiter }) => {\n if (prevPos < node.characters.length) {\n const delimeterPos = node.characters.indexOf(delimiter, prevPos);\n const endPos =\n delimeterPos > prevPos ? delimeterPos : node.characters.length;\n const matchedFont = {\n family,\n style,\n };\n node.setRangeFontName(prevPos, endPos, matchedFont);\n prevPos = endPos + 1;\n }\n });\n return true;\n};\n\n// Add the cloneNode function implementation\nasync function cloneNode(params) {\n const { nodeId, x, y } = params || {};\n\n if (!nodeId) {\n throw new Error(\"Missing nodeId parameter\");\n }\n\n const node = await figma.getNodeByIdAsync(nodeId);\n if (!node) {\n throw new Error(`Node not found with ID: ${nodeId}`);\n }\n\n // Clone the node\n const clone = node.clone();\n\n // If x and y are provided, move the clone to that position\n if (x !== undefined && y !== undefined) {\n if (!(\"x\" in clone) || !(\"y\" in clone)) {\n throw new Error(`Cloned node does not support position: ${nodeId}`);\n }\n clone.x = x;\n clone.y = y;\n }\n\n // Add the clone to the same parent as the original node\n if (node.parent) {\n node.parent.appendChild(clone);\n } else {\n figma.currentPage.appendChild(clone);\n }\n\n return {\n id: clone.id,\n name: clone.name,\n x: \"x\" in clone ? clone.x : undefined,\n y: \"y\" in clone ? clone.y : undefined,\n width: \"width\" in clone ? clone.width : undefined,\n height: \"height\" in clone ? clone.height : undefined,\n };\n}\n\nasync function scanTextNodes(params) {\n console.log(`Starting to scan text nodes from node ID: ${params.nodeId}`);\n const {\n nodeId,\n useChunking = true,\n chunkSize = 10,\n commandId = generateCommandId(),\n } = params || {};\n\n const node = await figma.getNodeByIdAsync(nodeId);\n\n if (!node) {\n console.error(`Node with ID ${nodeId} not found`);\n // Send error progress update\n sendProgressUpdate(\n commandId,\n \"scan_text_nodes\",\n \"error\",\n 0,\n 0,\n 0,\n `Node with ID ${nodeId} not found`,\n { error: `Node not found: ${nodeId}` }\n );\n throw new Error(`Node with ID ${nodeId} not found`);\n }\n\n // If chunking is not enabled, use the original implementation\n if (!useChunking) {\n const textNodes = [];\n try {\n // Send started progress update\n sendProgressUpdate(\n commandId,\n \"scan_text_nodes\",\n \"started\",\n 0,\n 1, // Not known yet how many nodes there are\n 0,\n `Starting scan of node \"${node.name || nodeId}\" without chunking`,\n null\n );\n\n await findTextNodes(node, [], 0, textNodes);\n\n // Send completed progress update\n sendProgressUpdate(\n commandId,\n \"scan_text_nodes\",\n \"completed\",\n 100,\n textNodes.length,\n textNodes.length,\n `Scan complete. Found ${textNodes.length} text nodes.`,\n { textNodes }\n );\n\n return {\n success: true,\n message: `Scanned ${textNodes.length} text nodes.`,\n count: textNodes.length,\n textNodes: textNodes,\n commandId,\n };\n } catch (error) {\n console.error(\"Error scanning text nodes:\", error);\n\n // Send error progress update\n sendProgressUpdate(\n commandId,\n \"scan_text_nodes\",\n \"error\",\n 0,\n 0,\n 0,\n `Error scanning text nodes: ${error.message}`,\n { error: error.message }\n );\n\n throw new Error(`Error scanning text nodes: ${error.message}`);\n }\n }\n\n // Chunked implementation\n console.log(`Using chunked scanning with chunk size: ${chunkSize}`);\n\n // First, collect all nodes to process (without processing them yet)\n const nodesToProcess = [];\n\n // Send started progress update\n sendProgressUpdate(\n commandId,\n \"scan_text_nodes\",\n \"started\",\n 0,\n 0, // Not known yet how many nodes there are\n 0,\n `Starting chunked scan of node \"${node.name || nodeId}\"`,\n { chunkSize }\n );\n\n await collectNodesToProcess(node, [], 0, nodesToProcess);\n\n const totalNodes = nodesToProcess.length;\n console.log(`Found ${totalNodes} total nodes to process`);\n\n // Calculate number of chunks needed\n const totalChunks = Math.ceil(totalNodes / chunkSize);\n console.log(`Will process in ${totalChunks} chunks`);\n\n // Send update after node collection\n sendProgressUpdate(\n commandId,\n \"scan_text_nodes\",\n \"in_progress\",\n 5, // 5% progress for collection phase\n totalNodes,\n 0,\n `Found ${totalNodes} nodes to scan. Will process in ${totalChunks} chunks.`,\n {\n totalNodes,\n totalChunks,\n chunkSize,\n }\n );\n\n // Process nodes in chunks\n const allTextNodes = [];\n let processedNodes = 0;\n let chunksProcessed = 0;\n\n for (let i = 0; i < totalNodes; i += chunkSize) {\n const chunkEnd = Math.min(i + chunkSize, totalNodes);\n console.log(\n `Processing chunk ${chunksProcessed + 1}/${totalChunks} (nodes ${i} to ${chunkEnd - 1\n })`\n );\n\n // Send update before processing chunk\n sendProgressUpdate(\n commandId,\n \"scan_text_nodes\",\n \"in_progress\",\n Math.round(5 + (chunksProcessed / totalChunks) * 90), // 5-95% for processing\n totalNodes,\n processedNodes,\n `Processing chunk ${chunksProcessed + 1}/${totalChunks}`,\n {\n currentChunk: chunksProcessed + 1,\n totalChunks,\n textNodesFound: allTextNodes.length,\n }\n );\n\n const chunkNodes = nodesToProcess.slice(i, chunkEnd);\n const chunkTextNodes = [];\n\n // Process each node in this chunk\n for (const nodeInfo of chunkNodes) {\n if (nodeInfo.node.type === \"TEXT\") {\n try {\n const textNodeInfo = await processTextNode(\n nodeInfo.node,\n nodeInfo.parentPath,\n nodeInfo.depth\n );\n if (textNodeInfo) {\n chunkTextNodes.push(textNodeInfo);\n }\n } catch (error) {\n console.error(`Error processing text node: ${error.message}`);\n // Continue with other nodes\n }\n }\n\n // Brief delay to allow UI updates and prevent freezing\n await delay(5);\n }\n\n // Add results from this chunk\n allTextNodes.push(...chunkTextNodes);\n processedNodes += chunkNodes.length;\n chunksProcessed++;\n\n // Send update after processing chunk\n sendProgressUpdate(\n commandId,\n \"scan_text_nodes\",\n \"in_progress\",\n Math.round(5 + (chunksProcessed / totalChunks) * 90), // 5-95% for processing\n totalNodes,\n processedNodes,\n `Processed chunk ${chunksProcessed}/${totalChunks}. Found ${allTextNodes.length} text nodes so far.`,\n {\n currentChunk: chunksProcessed,\n totalChunks,\n processedNodes,\n textNodesFound: allTextNodes.length,\n chunkResult: chunkTextNodes,\n }\n );\n\n // Small delay between chunks to prevent UI freezing\n if (i + chunkSize < totalNodes) {\n await delay(50);\n }\n }\n\n // Send completed progress update\n sendProgressUpdate(\n commandId,\n \"scan_text_nodes\",\n \"completed\",\n 100,\n totalNodes,\n processedNodes,\n `Scan complete. Found ${allTextNodes.length} text nodes.`,\n {\n textNodes: allTextNodes,\n processedNodes,\n chunks: chunksProcessed,\n }\n );\n\n return {\n success: true,\n message: `Chunked scan complete. Found ${allTextNodes.length} text nodes.`,\n totalNodes: allTextNodes.length,\n processedNodes: processedNodes,\n chunks: chunksProcessed,\n textNodes: allTextNodes,\n commandId,\n };\n}\n\n// Helper function to collect all nodes that need to be processed\nasync function collectNodesToProcess(\n node,\n parentPath = [],\n depth = 0,\n nodesToProcess = []\n) {\n // Skip invisible nodes\n if (node.visible === false) return;\n\n // Get the path to this node\n const nodePath = [...parentPath, node.name || `Unnamed ${node.type}`];\n\n // Add this node to the processing list\n nodesToProcess.push({\n node: node,\n parentPath: nodePath,\n depth: depth,\n });\n\n // Recursively add children\n if (\"children\" in node) {\n for (const child of node.children) {\n await collectNodesToProcess(child, nodePath, depth + 1, nodesToProcess);\n }\n }\n}\n\n// Process a single text node\nasync function processTextNode(node, parentPath, depth) {\n if (node.type !== \"TEXT\") return null;\n\n try {\n // Safely extract font information\n let fontFamily = \"\";\n let fontStyle = \"\";\n\n if (node.fontName) {\n if (typeof node.fontName === \"object\") {\n if (\"family\" in node.fontName) fontFamily = node.fontName.family;\n if (\"style\" in node.fontName) fontStyle = node.fontName.style;\n }\n }\n\n // Create a safe representation of the text node\n const safeTextNode = {\n id: node.id,\n name: node.name || \"Text\",\n type: node.type,\n characters: node.characters,\n fontSize: typeof node.fontSize === \"number\" ? node.fontSize : 0,\n fontFamily: fontFamily,\n fontStyle: fontStyle,\n x: typeof node.x === \"number\" ? node.x : 0,\n y: typeof node.y === \"number\" ? node.y : 0,\n width: typeof node.width === \"number\" ? node.width : 0,\n height: typeof node.height === \"number\" ? node.height : 0,\n path: parentPath.join(\" > \"),\n depth: depth,\n };\n\n // Highlight the node briefly (optional visual feedback)\n try {\n const originalFills = JSON.parse(JSON.stringify(node.fills));\n node.fills = [\n {\n type: \"SOLID\",\n color: { r: 1, g: 0.5, b: 0 },\n opacity: 0.3,\n },\n ];\n\n // Brief delay for the highlight to be visible\n await delay(100);\n\n try {\n node.fills = originalFills;\n } catch (err) {\n console.error(\"Error resetting fills:\", err);\n }\n } catch (highlightErr) {\n console.error(\"Error highlighting text node:\", highlightErr);\n // Continue anyway, highlighting is just visual feedback\n }\n\n return safeTextNode;\n } catch (nodeErr) {\n console.error(\"Error processing text node:\", nodeErr);\n return null;\n }\n}\n\n// A delay function that returns a promise\nfunction delay(ms) {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n// Keep the original findTextNodes for backward compatibility\nasync function findTextNodes(node, parentPath = [], depth = 0, textNodes = []) {\n // Skip invisible nodes\n if (node.visible === false) return;\n\n // Get the path to this node including its name\n const nodePath = [...parentPath, node.name || `Unnamed ${node.type}`];\n\n if (node.type === \"TEXT\") {\n try {\n // Safely extract font information to avoid Symbol serialization issues\n let fontFamily = \"\";\n let fontStyle = \"\";\n\n if (node.fontName) {\n if (typeof node.fontName === \"object\") {\n if (\"family\" in node.fontName) fontFamily = node.fontName.family;\n if (\"style\" in node.fontName) fontStyle = node.fontName.style;\n }\n }\n\n // Create a safe representation of the text node with only serializable properties\n const safeTextNode = {\n id: node.id,\n name: node.name || \"Text\",\n type: node.type,\n characters: node.characters,\n fontSize: typeof node.fontSize === \"number\" ? node.fontSize : 0,\n fontFamily: fontFamily,\n fontStyle: fontStyle,\n x: typeof node.x === \"number\" ? node.x : 0,\n y: typeof node.y === \"number\" ? node.y : 0,\n width: typeof node.width === \"number\" ? node.width : 0,\n height: typeof node.height === \"number\" ? node.height : 0,\n path: nodePath.join(\" > \"),\n depth: depth,\n };\n\n // Only highlight the node if it's not being done via API\n try {\n // Safe way to create a temporary highlight without causing serialization issues\n const originalFills = JSON.parse(JSON.stringify(node.fills));\n node.fills = [\n {\n type: \"SOLID\",\n color: { r: 1, g: 0.5, b: 0 },\n opacity: 0.3,\n },\n ];\n\n // Promise-based delay instead of setTimeout\n await delay(500);\n\n try {\n node.fills = originalFills;\n } catch (err) {\n console.error(\"Error resetting fills:\", err);\n }\n } catch (highlightErr) {\n console.error(\"Error highlighting text node:\", highlightErr);\n // Continue anyway, highlighting is just visual feedback\n }\n\n textNodes.push(safeTextNode);\n } catch (nodeErr) {\n console.error(\"Error processing text node:\", nodeErr);\n // Skip this node but continue with others\n }\n }\n\n // Recursively process children of container nodes\n if (\"children\" in node) {\n for (const child of node.children) {\n await findTextNodes(child, nodePath, depth + 1, textNodes);\n }\n }\n}\n\n// Replace text in a specific node\nasync function setMultipleTextContents(params) {\n const { nodeId, text } = params || {};\n const commandId = params.commandId || generateCommandId();\n\n if (!nodeId || !text || !Array.isArray(text)) {\n const errorMsg = \"Missing required parameters: nodeId and text array\";\n\n // Send error progress update\n sendProgressUpdate(\n commandId,\n \"set_multiple_text_contents\",\n \"error\",\n 0,\n 0,\n 0,\n errorMsg,\n { error: errorMsg }\n );\n\n throw new Error(errorMsg);\n }\n\n console.log(\n `Starting text replacement for node: ${nodeId} with ${text.length} text replacements`\n );\n\n // Send started progress update\n sendProgressUpdate(\n commandId,\n \"set_multiple_text_contents\",\n \"started\",\n 0,\n text.length,\n 0,\n `Starting text replacement for ${text.length} nodes`,\n { totalReplacements: text.length }\n );\n\n // Define the results array and counters\n const results = [];\n let successCount = 0;\n let failureCount = 0;\n\n // Split text replacements into chunks of 5\n const CHUNK_SIZE = 5;\n const chunks = [];\n\n for (let i = 0; i < text.length; i += CHUNK_SIZE) {\n chunks.push(text.slice(i, i + CHUNK_SIZE));\n }\n\n console.log(`Split ${text.length} replacements into ${chunks.length} chunks`);\n\n // Send chunking info update\n sendProgressUpdate(\n commandId,\n \"set_multiple_text_contents\",\n \"in_progress\",\n 5, // 5% progress for planning phase\n text.length,\n 0,\n `Preparing to replace text in ${text.length} nodes using ${chunks.length} chunks`,\n {\n totalReplacements: text.length,\n chunks: chunks.length,\n chunkSize: CHUNK_SIZE,\n }\n );\n\n // Process each chunk sequentially\n for (let chunkIndex = 0; chunkIndex < chunks.length; chunkIndex++) {\n const chunk = chunks[chunkIndex];\n console.log(\n `Processing chunk ${chunkIndex + 1}/${chunks.length} with ${chunk.length\n } replacements`\n );\n\n // Send chunk processing start update\n sendProgressUpdate(\n commandId,\n \"set_multiple_text_contents\",\n \"in_progress\",\n Math.round(5 + (chunkIndex / chunks.length) * 90), // 5-95% for processing\n text.length,\n successCount + failureCount,\n `Processing text replacements chunk ${chunkIndex + 1}/${chunks.length}`,\n {\n currentChunk: chunkIndex + 1,\n totalChunks: chunks.length,\n successCount,\n failureCount,\n }\n );\n\n // Process replacements within a chunk in parallel\n const chunkPromises = chunk.map(async (replacement) => {\n if (!replacement.nodeId || replacement.text === undefined) {\n console.error(`Missing nodeId or text for replacement`);\n return {\n success: false,\n nodeId: replacement.nodeId || \"unknown\",\n error: \"Missing nodeId or text in replacement entry\",\n };\n }\n\n try {\n console.log(\n `Attempting to replace text in node: ${replacement.nodeId}`\n );\n\n // Get the text node to update (just to check it exists and get original text)\n const textNode = await figma.getNodeByIdAsync(replacement.nodeId);\n\n if (!textNode) {\n console.error(`Text node not found: ${replacement.nodeId}`);\n return {\n success: false,\n nodeId: replacement.nodeId,\n error: `Node not found: ${replacement.nodeId}`,\n };\n }\n\n if (textNode.type !== \"TEXT\") {\n console.error(\n `Node is not a text node: ${replacement.nodeId} (type: ${textNode.type})`\n );\n return {\n success: false,\n nodeId: replacement.nodeId,\n error: `Node is not a text node: ${replacement.nodeId} (type: ${textNode.type})`,\n };\n }\n\n // Save original text for the result\n const originalText = textNode.characters;\n console.log(`Original text: \"${originalText}\"`);\n console.log(`Will translate to: \"${replacement.text}\"`);\n\n // Highlight the node before changing text\n let originalFills;\n try {\n // Save original fills for restoration later\n originalFills = JSON.parse(JSON.stringify(textNode.fills));\n // Apply highlight color (orange with 30% opacity)\n textNode.fills = [\n {\n type: \"SOLID\",\n color: { r: 1, g: 0.5, b: 0 },\n opacity: 0.3,\n },\n ];\n } catch (highlightErr) {\n console.error(\n `Error highlighting text node: ${highlightErr.message}`\n );\n // Continue anyway, highlighting is just visual feedback\n }\n\n // Use the existing setTextContent function to handle font loading and text setting\n await setTextContent({\n nodeId: replacement.nodeId,\n text: replacement.text,\n });\n\n // Keep highlight for a moment after text change, then restore original fills\n if (originalFills) {\n try {\n // Use delay function for consistent timing\n await delay(500);\n textNode.fills = originalFills;\n } catch (restoreErr) {\n console.error(`Error restoring fills: ${restoreErr.message}`);\n }\n }\n\n console.log(\n `Successfully replaced text in node: ${replacement.nodeId}`\n );\n return {\n success: true,\n nodeId: replacement.nodeId,\n originalText: originalText,\n translatedText: replacement.text,\n };\n } catch (error) {\n console.error(\n `Error replacing text in node ${replacement.nodeId}: ${error.message}`\n );\n return {\n success: false,\n nodeId: replacement.nodeId,\n error: `Error applying replacement: ${error.message}`,\n };\n }\n });\n\n // Wait for all replacements in this chunk to complete\n const chunkResults = await Promise.all(chunkPromises);\n\n // Process results for this chunk\n chunkResults.forEach((result) => {\n if (result.success) {\n successCount++;\n } else {\n failureCount++;\n }\n results.push(result);\n });\n\n // Send chunk processing complete update with partial results\n sendProgressUpdate(\n commandId,\n \"set_multiple_text_contents\",\n \"in_progress\",\n Math.round(5 + ((chunkIndex + 1) / chunks.length) * 90), // 5-95% for processing\n text.length,\n successCount + failureCount,\n `Completed chunk ${chunkIndex + 1}/${chunks.length\n }. ${successCount} successful, ${failureCount} failed so far.`,\n {\n currentChunk: chunkIndex + 1,\n totalChunks: chunks.length,\n successCount,\n failureCount,\n chunkResults: chunkResults,\n }\n );\n\n // Add a small delay between chunks to avoid overloading Figma\n if (chunkIndex < chunks.length - 1) {\n console.log(\"Pausing between chunks to avoid overloading Figma...\");\n await delay(1000); // 1 second delay between chunks\n }\n }\n\n console.log(\n `Replacement complete: ${successCount} successful, ${failureCount} failed`\n );\n\n // Send completed progress update\n sendProgressUpdate(\n commandId,\n \"set_multiple_text_contents\",\n \"completed\",\n 100,\n text.length,\n successCount + failureCount,\n `Text replacement complete: ${successCount} successful, ${failureCount} failed`,\n {\n totalReplacements: text.length,\n replacementsApplied: successCount,\n replacementsFailed: failureCount,\n completedInChunks: chunks.length,\n results: results,\n }\n );\n\n return {\n success: successCount > 0,\n nodeId: nodeId,\n replacementsApplied: successCount,\n replacementsFailed: failureCount,\n totalReplacements: text.length,\n results: results,\n completedInChunks: chunks.length,\n commandId,\n };\n}\n\n// Function to generate simple UUIDs for command IDs\nfunction generateCommandId() {\n return (\n \"cmd_\" +\n Math.random().toString(36).substring(2, 15) +\n Math.random().toString(36).substring(2, 15)\n );\n}\n\nasync function getAnnotations(params) {\n try {\n const { nodeId, includeCategories = true } = params;\n\n // Get categories first if needed\n let categoriesMap = {};\n if (includeCategories) {\n const categories = await figma.annotations.getAnnotationCategoriesAsync();\n categoriesMap = categories.reduce((map, category) => {\n map[category.id] = {\n id: category.id,\n label: category.label,\n color: category.color,\n isPreset: category.isPreset,\n };\n return map;\n }, {});\n }\n\n if (nodeId) {\n // Get annotations for a specific node\n const node = await figma.getNodeByIdAsync(nodeId);\n if (!node) {\n throw new Error(`Node not found: ${nodeId}`);\n }\n\n if (!(\"annotations\" in node)) {\n throw new Error(`Node type ${node.type} does not support annotations`);\n }\n\n const result = {\n nodeId: node.id,\n name: node.name,\n annotations: node.annotations || [],\n };\n\n if (includeCategories) {\n result.categories = Object.values(categoriesMap);\n }\n\n return result;\n } else {\n // Get all annotations in the current page\n const annotations = [];\n const processNode = async (node) => {\n if (\n \"annotations\" in node &&\n node.annotations &&\n node.annotations.length > 0\n ) {\n annotations.push({\n nodeId: node.id,\n name: node.name,\n annotations: node.annotations,\n });\n }\n if (\"children\" in node) {\n for (const child of node.children) {\n await processNode(child);\n }\n }\n };\n\n // Start from current page\n await processNode(figma.currentPage);\n\n const result = {\n annotatedNodes: annotations,\n };\n\n if (includeCategories) {\n result.categories = Object.values(categoriesMap);\n }\n\n return result;\n }\n } catch (error) {\n console.error(\"Error in getAnnotations:\", error);\n throw error;\n }\n}\n\nasync function setAnnotation(params) {\n try {\n console.log(\"=== setAnnotation Debug Start ===\");\n console.log(\"Input params:\", JSON.stringify(params, null, 2));\n\n const { nodeId, annotationId, labelMarkdown, categoryId, properties } =\n params;\n\n // Validate required parameters\n if (!nodeId) {\n console.error(\"Validation failed: Missing nodeId\");\n return { success: false, error: \"Missing nodeId\" };\n }\n\n if (!labelMarkdown) {\n console.error(\"Validation failed: Missing labelMarkdown\");\n return { success: false, error: \"Missing labelMarkdown\" };\n }\n\n console.log(\"Attempting to get node:\", nodeId);\n // Get and validate node\n const node = await figma.getNodeByIdAsync(nodeId);\n console.log(\"Node lookup result:\", {\n id: nodeId,\n found: !!node,\n type: node ? node.type : undefined,\n name: node ? node.name : undefined,\n hasAnnotations: node ? \"annotations\" in node : false,\n });\n\n if (!node) {\n console.error(\"Node lookup failed:\", nodeId);\n return { success: false, error: `Node not found: ${nodeId}` };\n }\n\n // Validate node supports annotations\n if (!(\"annotations\" in node)) {\n console.error(\"Node annotation support check failed:\", {\n nodeType: node.type,\n nodeId: node.id,\n });\n return {\n success: false,\n error: `Node type ${node.type} does not support annotations`,\n };\n }\n\n // Create the annotation object\n const newAnnotation = {\n labelMarkdown,\n };\n\n // Validate and add categoryId if provided\n if (categoryId) {\n console.log(\"Adding categoryId to annotation:\", categoryId);\n newAnnotation.categoryId = categoryId;\n }\n\n // Validate and add properties if provided\n if (properties && Array.isArray(properties) && properties.length > 0) {\n console.log(\n \"Adding properties to annotation:\",\n JSON.stringify(properties, null, 2)\n );\n newAnnotation.properties = properties;\n }\n\n // Log current annotations before update\n console.log(\"Current node annotations:\", node.annotations);\n\n // Overwrite annotations\n console.log(\n \"Setting new annotation:\",\n JSON.stringify(newAnnotation, null, 2)\n );\n node.annotations = [newAnnotation];\n\n // Verify the update\n console.log(\"Updated node annotations:\", node.annotations);\n console.log(\"=== setAnnotation Debug End ===\");\n\n return {\n success: true,\n nodeId: node.id,\n name: node.name,\n annotations: node.annotations,\n };\n } catch (error) {\n console.error(\"=== setAnnotation Error ===\");\n console.error(\"Error details:\", {\n message: error.message,\n stack: error.stack,\n params: JSON.stringify(params, null, 2),\n });\n return { success: false, error: error.message };\n }\n}\n\n/**\n * Scan for nodes with specific types within a node\n * @param {Object} params - Parameters object\n * @param {string} params.nodeId - ID of the node to scan within\n * @param {Array} params.types - Array of node types to find (e.g. ['COMPONENT', 'FRAME'])\n * @returns {Object} - Object containing found nodes\n */\n", "suffix_code": "\n\n/**\n * Helper function to recursively find nodes with specific types\n * @param {SceneNode} node - The root node to start searching from\n * @param {Array} types - Array of node types to find\n * @param {Array} matchingNodes - Array to store found nodes\n */\nasync function findNodesByTypes(node, types, matchingNodes = []) {\n // Skip invisible nodes\n if (node.visible === false) return;\n\n // Check if this node is one of the specified types\n if (types.includes(node.type)) {\n // Create a minimal representation with just ID, type and bbox\n matchingNodes.push({\n id: node.id,\n name: node.name || `Unnamed ${node.type}`,\n type: node.type,\n // Basic bounding box info\n bbox: {\n x: typeof node.x === \"number\" ? node.x : 0,\n y: typeof node.y === \"number\" ? node.y : 0,\n width: typeof node.width === \"number\" ? node.width : 0,\n height: typeof node.height === \"number\" ? node.height : 0,\n },\n });\n }\n\n // Recursively process children of container nodes\n if (\"children\" in node) {\n for (const child of node.children) {\n await findNodesByTypes(child, types, matchingNodes);\n }\n }\n}\n\n// Set multiple annotations with async progress updates\nasync function setMultipleAnnotations(params) {\n console.log(\"=== setMultipleAnnotations Debug Start ===\");\n console.log(\"Input params:\", JSON.stringify(params, null, 2));\n\n const { nodeId, annotations } = params;\n\n if (!annotations || annotations.length === 0) {\n console.error(\"Validation failed: No annotations provided\");\n return { success: false, error: \"No annotations provided\" };\n }\n\n console.log(\n `Processing ${annotations.length} annotations for node ${nodeId}`\n );\n\n const results = [];\n let successCount = 0;\n let failureCount = 0;\n\n // Process annotations sequentially\n for (let i = 0; i < annotations.length; i++) {\n const annotation = annotations[i];\n console.log(\n `\\nProcessing annotation ${i + 1}/${annotations.length}:`,\n JSON.stringify(annotation, null, 2)\n );\n\n try {\n console.log(\"Calling setAnnotation with params:\", {\n nodeId: annotation.nodeId,\n labelMarkdown: annotation.labelMarkdown,\n categoryId: annotation.categoryId,\n properties: annotation.properties,\n });\n\n const result = await setAnnotation({\n nodeId: annotation.nodeId,\n labelMarkdown: annotation.labelMarkdown,\n categoryId: annotation.categoryId,\n properties: annotation.properties,\n });\n\n console.log(\"setAnnotation result:\", JSON.stringify(result, null, 2));\n\n if (result.success) {\n successCount++;\n results.push({ success: true, nodeId: annotation.nodeId });\n console.log(`✓ Annotation ${i + 1} applied successfully`);\n } else {\n failureCount++;\n results.push({\n success: false,\n nodeId: annotation.nodeId,\n error: result.error,\n });\n console.error(`✗ Annotation ${i + 1} failed:`, result.error);\n }\n } catch (error) {\n failureCount++;\n const errorResult = {\n success: false,\n nodeId: annotation.nodeId,\n error: error.message,\n };\n results.push(errorResult);\n console.error(`✗ Annotation ${i + 1} failed with error:`, error);\n console.error(\"Error details:\", {\n message: error.message,\n stack: error.stack,\n });\n }\n }\n\n const summary = {\n success: successCount > 0,\n annotationsApplied: successCount,\n annotationsFailed: failureCount,\n totalAnnotations: annotations.length,\n results: results,\n };\n\n console.log(\"\\n=== setMultipleAnnotations Summary ===\");\n console.log(JSON.stringify(summary, null, 2));\n console.log(\"=== setMultipleAnnotations Debug End ===\");\n\n return summary;\n}\n\nasync function deleteMultipleNodes(params) {\n const { nodeIds } = params || {};\n const commandId = generateCommandId();\n\n if (!nodeIds || !Array.isArray(nodeIds) || nodeIds.length === 0) {\n const errorMsg = \"Missing or invalid nodeIds parameter\";\n sendProgressUpdate(\n commandId,\n \"delete_multiple_nodes\",\n \"error\",\n 0,\n 0,\n 0,\n errorMsg,\n { error: errorMsg }\n );\n throw new Error(errorMsg);\n }\n\n console.log(`Starting deletion of ${nodeIds.length} nodes`);\n\n // Send started progress update\n sendProgressUpdate(\n commandId,\n \"delete_multiple_nodes\",\n \"started\",\n 0,\n nodeIds.length,\n 0,\n `Starting deletion of ${nodeIds.length} nodes`,\n { totalNodes: nodeIds.length }\n );\n\n const results = [];\n let successCount = 0;\n let failureCount = 0;\n\n // Process nodes in chunks of 5 to avoid overwhelming Figma\n const CHUNK_SIZE = 5;\n const chunks = [];\n\n for (let i = 0; i < nodeIds.length; i += CHUNK_SIZE) {\n chunks.push(nodeIds.slice(i, i + CHUNK_SIZE));\n }\n\n console.log(`Split ${nodeIds.length} deletions into ${chunks.length} chunks`);\n\n // Send chunking info update\n sendProgressUpdate(\n commandId,\n \"delete_multiple_nodes\",\n \"in_progress\",\n 5,\n nodeIds.length,\n 0,\n `Preparing to delete ${nodeIds.length} nodes using ${chunks.length} chunks`,\n {\n totalNodes: nodeIds.length,\n chunks: chunks.length,\n chunkSize: CHUNK_SIZE,\n }\n );\n\n // Process each chunk sequentially\n for (let chunkIndex = 0; chunkIndex < chunks.length; chunkIndex++) {\n const chunk = chunks[chunkIndex];\n console.log(\n `Processing chunk ${chunkIndex + 1}/${chunks.length} with ${chunk.length\n } nodes`\n );\n\n // Send chunk processing start update\n sendProgressUpdate(\n commandId,\n \"delete_multiple_nodes\",\n \"in_progress\",\n Math.round(5 + (chunkIndex / chunks.length) * 90),\n nodeIds.length,\n successCount + failureCount,\n `Processing deletion chunk ${chunkIndex + 1}/${chunks.length}`,\n {\n currentChunk: chunkIndex + 1,\n totalChunks: chunks.length,\n successCount,\n failureCount,\n }\n );\n\n // Process deletions within a chunk in parallel\n const chunkPromises = chunk.map(async (nodeId) => {\n try {\n const node = await figma.getNodeByIdAsync(nodeId);\n\n if (!node) {\n console.error(`Node not found: ${nodeId}`);\n return {\n success: false,\n nodeId: nodeId,\n error: `Node not found: ${nodeId}`,\n };\n }\n\n // Save node info before deleting\n const nodeInfo = {\n id: node.id,\n name: node.name,\n type: node.type,\n };\n\n // Delete the node\n node.remove();\n\n console.log(`Successfully deleted node: ${nodeId}`);\n return {\n success: true,\n nodeId: nodeId,\n nodeInfo: nodeInfo,\n };\n } catch (error) {\n console.error(`Error deleting node ${nodeId}: ${error.message}`);\n return {\n success: false,\n nodeId: nodeId,\n error: error.message,\n };\n }\n });\n\n // Wait for all deletions in this chunk to complete\n const chunkResults = await Promise.all(chunkPromises);\n\n // Process results for this chunk\n chunkResults.forEach((result) => {\n if (result.success) {\n successCount++;\n } else {\n failureCount++;\n }\n results.push(result);\n });\n\n // Send chunk processing complete update\n sendProgressUpdate(\n commandId,\n \"delete_multiple_nodes\",\n \"in_progress\",\n Math.round(5 + ((chunkIndex + 1) / chunks.length) * 90),\n nodeIds.length,\n successCount + failureCount,\n `Completed chunk ${chunkIndex + 1}/${chunks.length\n }. ${successCount} successful, ${failureCount} failed so far.`,\n {\n currentChunk: chunkIndex + 1,\n totalChunks: chunks.length,\n successCount,\n failureCount,\n chunkResults: chunkResults,\n }\n );\n\n // Add a small delay between chunks\n if (chunkIndex < chunks.length - 1) {\n console.log(\"Pausing between chunks...\");\n await delay(1000);\n }\n }\n\n console.log(\n `Deletion complete: ${successCount} successful, ${failureCount} failed`\n );\n\n // Send completed progress update\n sendProgressUpdate(\n commandId,\n \"delete_multiple_nodes\",\n \"completed\",\n 100,\n nodeIds.length,\n successCount + failureCount,\n `Node deletion complete: ${successCount} successful, ${failureCount} failed`,\n {\n totalNodes: nodeIds.length,\n nodesDeleted: successCount,\n nodesFailed: failureCount,\n completedInChunks: chunks.length,\n results: results,\n }\n );\n\n return {\n success: successCount > 0,\n nodesDeleted: successCount,\n nodesFailed: failureCount,\n totalNodes: nodeIds.length,\n results: results,\n completedInChunks: chunks.length,\n commandId,\n };\n}\n\n// Implementation for getInstanceOverrides function\nasync function getInstanceOverrides(instanceNode = null) {\n console.log(\"=== getInstanceOverrides called ===\");\n\n let sourceInstance = null;\n\n // Check if an instance node was passed directly\n if (instanceNode) {\n console.log(\"Using provided instance node\");\n\n // Validate that the provided node is an instance\n if (instanceNode.type !== \"INSTANCE\") {\n console.error(\"Provided node is not an instance\");\n figma.notify(\"Provided node is not a component instance\");\n return { success: false, message: \"Provided node is not a component instance\" };\n }\n\n sourceInstance = instanceNode;\n } else {\n // No node provided, use selection\n console.log(\"No node provided, using current selection\");\n\n // Get the current selection\n const selection = figma.currentPage.selection;\n\n // Check if there's anything selected\n if (selection.length === 0) {\n console.log(\"No nodes selected\");\n figma.notify(\"Please select at least one instance\");\n return { success: false, message: \"No nodes selected\" };\n }\n\n // Filter for instances in the selection\n const instances = selection.filter(node => node.type === \"INSTANCE\");\n\n if (instances.length === 0) {\n console.log(\"No instances found in selection\");\n figma.notify(\"Please select at least one component instance\");\n return { success: false, message: \"No instances found in selection\" };\n }\n\n // Take the first instance from the selection\n sourceInstance = instances[0];\n }\n\n try {\n console.log(`Getting instance information:`);\n console.log(sourceInstance);\n\n // Get component overrides and main component\n const overrides = sourceInstance.overrides || [];\n console.log(` Raw Overrides:`, overrides);\n\n // Get main component\n const mainComponent = await sourceInstance.getMainComponentAsync();\n if (!mainComponent) {\n console.error(\"Failed to get main component\");\n figma.notify(\"Failed to get main component\");\n return { success: false, message: \"Failed to get main component\" };\n }\n\n // return data to MCP server\n const returnData = {\n success: true,\n message: `Got component information from \"${sourceInstance.name}\" for overrides.length: ${overrides.length}`,\n sourceInstanceId: sourceInstance.id,\n mainComponentId: mainComponent.id,\n overridesCount: overrides.length\n };\n\n console.log(\"Data to return to MCP server:\", returnData);\n figma.notify(`Got component information from \"${sourceInstance.name}\"`);\n\n return returnData;\n } catch (error) {\n console.error(\"Error in getInstanceOverrides:\", error);\n figma.notify(`Error: ${error.message}`);\n return {\n success: false,\n message: `Error: ${error.message}`\n };\n }\n}\n\n/**\n * Helper function to validate and get target instances\n * @param {string[]} targetNodeIds - Array of instance node IDs\n * @returns {instanceNode[]} targetInstances - Array of target instances\n */\nasync function getValidTargetInstances(targetNodeIds) {\n let targetInstances = [];\n\n // Handle array of instances or single instance\n if (Array.isArray(targetNodeIds)) {\n if (targetNodeIds.length === 0) {\n return { success: false, message: \"No instances provided\" };\n }\n for (const targetNodeId of targetNodeIds) {\n const targetNode = await figma.getNodeByIdAsync(targetNodeId);\n if (targetNode && targetNode.type === \"INSTANCE\") {\n targetInstances.push(targetNode);\n }\n }\n if (targetInstances.length === 0) {\n return { success: false, message: \"No valid instances provided\" };\n }\n } else {\n return { success: false, message: \"Invalid target node IDs provided\" };\n }\n\n\n return { success: true, message: \"Valid target instances provided\", targetInstances };\n}\n\n/**\n * Helper function to validate and get saved override data\n * @param {string} sourceInstanceId - Source instance ID\n * @returns {Promise} - Validation result with source instance data or error\n */\nasync function getSourceInstanceData(sourceInstanceId) {\n if (!sourceInstanceId) {\n return { success: false, message: \"Missing source instance ID\" };\n }\n\n // Get source instance by ID\n const sourceInstance = await figma.getNodeByIdAsync(sourceInstanceId);\n if (!sourceInstance) {\n return {\n success: false,\n message: \"Source instance not found. The original instance may have been deleted.\"\n };\n }\n\n // Verify it's an instance\n if (sourceInstance.type !== \"INSTANCE\") {\n return {\n success: false,\n message: \"Source node is not a component instance.\"\n };\n }\n\n // Get main component\n const mainComponent = await sourceInstance.getMainComponentAsync();\n if (!mainComponent) {\n return {\n success: false,\n message: \"Failed to get main component from source instance.\"\n };\n }\n\n return {\n success: true,\n sourceInstance,\n mainComponent,\n overrides: sourceInstance.overrides || []\n };\n}\n\n/**\n * Sets saved overrides to the selected component instance(s)\n * @param {InstanceNode[] | null} targetInstances - Array of instance nodes to set overrides to\n * @param {Object} sourceResult - Source instance data from getSourceInstanceData\n * @returns {Promise} - Result of the set operation\n */\nasync function setInstanceOverrides(targetInstances, sourceResult) {\n try {\n\n\n const { sourceInstance, mainComponent, overrides } = sourceResult;\n\n console.log(`Processing ${targetInstances.length} instances with ${overrides.length} overrides`);\n console.log(`Source instance: ${sourceInstance.id}, Main component: ${mainComponent.id}`);\n console.log(`Overrides:`, overrides);\n\n // Process all instances\n const results = [];\n let totalAppliedCount = 0;\n\n for (const targetInstance of targetInstances) {\n try {\n // // Skip if trying to apply to the source instance itself\n // if (targetInstance.id === sourceInstance.id) {\n // console.log(`Skipping source instance itself: ${targetInstance.id}`);\n // results.push({\n // success: false,\n // instanceId: targetInstance.id,\n // instanceName: targetInstance.name,\n // message: \"This is the source instance itself, skipping\"\n // });\n // continue;\n // }\n\n // Swap component\n try {\n targetInstance.swapComponent(mainComponent);\n console.log(`Swapped component for instance \"${targetInstance.name}\"`);\n } catch (error) {\n console.error(`Error swapping component for instance \"${targetInstance.name}\":`, error);\n results.push({\n success: false,\n instanceId: targetInstance.id,\n instanceName: targetInstance.name,\n message: `Error: ${error.message}`\n });\n }\n\n // Prepare overrides by replacing node IDs\n let appliedCount = 0;\n\n // Apply each override\n for (const override of overrides) {\n // Skip if no ID or overriddenFields\n if (!override.id || !override.overriddenFields || override.overriddenFields.length === 0) {\n continue;\n }\n\n // Replace source instance ID with target instance ID in the node path\n const overrideNodeId = override.id.replace(sourceInstance.id, targetInstance.id);\n const overrideNode = await figma.getNodeByIdAsync(overrideNodeId);\n\n if (!overrideNode) {\n console.log(`Override node not found: ${overrideNodeId}`);\n continue;\n }\n\n // Get source node to copy properties from\n const sourceNode = await figma.getNodeByIdAsync(override.id);\n if (!sourceNode) {\n console.log(`Source node not found: ${override.id}`);\n continue;\n }\n\n // Apply each overridden field\n let fieldApplied = false;\n for (const field of override.overriddenFields) {\n try {\n if (field === \"componentProperties\") {\n // Apply component properties\n if (sourceNode.componentProperties && overrideNode.componentProperties) {\n const properties = {};\n for (const key in sourceNode.componentProperties) {\n // if INSTANCE_SWAP use id, otherwise use value\n if (sourceNode.componentProperties[key].type === 'INSTANCE_SWAP') {\n properties[key] = sourceNode.componentProperties[key].value;\n \n } else {\n properties[key] = sourceNode.componentProperties[key].value;\n }\n }\n overrideNode.setProperties(properties);\n fieldApplied = true;\n }\n } else if (field === \"characters\" && overrideNode.type === \"TEXT\") {\n // For text nodes, need to load fonts first\n await figma.loadFontAsync(overrideNode.fontName);\n overrideNode.characters = sourceNode.characters;\n fieldApplied = true;\n } else if (field in overrideNode) {\n // Direct property assignment\n overrideNode[field] = sourceNode[field];\n fieldApplied = true;\n }\n } catch (fieldError) {\n console.error(`Error applying field ${field}:`, fieldError);\n }\n }\n\n if (fieldApplied) {\n appliedCount++;\n }\n }\n\n if (appliedCount > 0) {\n totalAppliedCount += appliedCount;\n results.push({\n success: true,\n instanceId: targetInstance.id,\n instanceName: targetInstance.name,\n appliedCount\n });\n console.log(`Applied ${appliedCount} overrides to \"${targetInstance.name}\"`);\n } else {\n results.push({\n success: false,\n instanceId: targetInstance.id,\n instanceName: targetInstance.name,\n message: \"No overrides were applied\"\n });\n }\n } catch (instanceError) {\n console.error(`Error processing instance \"${targetInstance.name}\":`, instanceError);\n results.push({\n success: false,\n instanceId: targetInstance.id,\n instanceName: targetInstance.name,\n message: `Error: ${instanceError.message}`\n });\n }\n }\n\n // Return results\n if (totalAppliedCount > 0) {\n const instanceCount = results.filter(r => r.success).length;\n const message = `Applied ${totalAppliedCount} overrides to ${instanceCount} instances`;\n figma.notify(message);\n return {\n success: true,\n message,\n totalCount: totalAppliedCount,\n results\n };\n } else {\n const message = \"No overrides applied to any instance\";\n figma.notify(message);\n return { success: false, message, results };\n }\n\n } catch (error) {\n console.error(\"Error in setInstanceOverrides:\", error);\n const message = `Error: ${error.message}`;\n figma.notify(message);\n return { success: false, message };\n }\n}\n\nasync function setLayoutMode(params) {\n const { nodeId, layoutMode = \"NONE\", layoutWrap = \"NO_WRAP\" } = params || {};\n\n // Get the target node\n const node = await figma.getNodeByIdAsync(nodeId);\n if (!node) {\n throw new Error(`Node with ID ${nodeId} not found`);\n }\n\n // Check if node is a frame or component that supports layoutMode\n if (\n node.type !== \"FRAME\" &&\n node.type !== \"COMPONENT\" &&\n node.type !== \"COMPONENT_SET\" &&\n node.type !== \"INSTANCE\"\n ) {\n throw new Error(`Node type ${node.type} does not support layoutMode`);\n }\n\n // Set layout mode\n node.layoutMode = layoutMode;\n\n // Set layoutWrap if applicable\n if (layoutMode !== \"NONE\") {\n node.layoutWrap = layoutWrap;\n }\n\n return {\n id: node.id,\n name: node.name,\n layoutMode: node.layoutMode,\n layoutWrap: node.layoutWrap,\n };\n}\n\nasync function setPadding(params) {\n const { nodeId, paddingTop, paddingRight, paddingBottom, paddingLeft } =\n params || {};\n\n // Get the target node\n const node = await figma.getNodeByIdAsync(nodeId);\n if (!node) {\n throw new Error(`Node with ID ${nodeId} not found`);\n }\n\n // Check if node is a frame or component that supports padding\n if (\n node.type !== \"FRAME\" &&\n node.type !== \"COMPONENT\" &&\n node.type !== \"COMPONENT_SET\" &&\n node.type !== \"INSTANCE\"\n ) {\n throw new Error(`Node type ${node.type} does not support padding`);\n }\n\n // Check if the node has auto-layout enabled\n if (node.layoutMode === \"NONE\") {\n throw new Error(\n \"Padding can only be set on auto-layout frames (layoutMode must not be NONE)\"\n );\n }\n\n // Set padding values if provided\n if (paddingTop !== undefined) node.paddingTop = paddingTop;\n if (paddingRight !== undefined) node.paddingRight = paddingRight;\n if (paddingBottom !== undefined) node.paddingBottom = paddingBottom;\n if (paddingLeft !== undefined) node.paddingLeft = paddingLeft;\n\n return {\n id: node.id,\n name: node.name,\n paddingTop: node.paddingTop,\n paddingRight: node.paddingRight,\n paddingBottom: node.paddingBottom,\n paddingLeft: node.paddingLeft,\n };\n}\n\nasync function setAxisAlign(params) {\n const { nodeId, primaryAxisAlignItems, counterAxisAlignItems } = params || {};\n\n // Get the target node\n const node = await figma.getNodeByIdAsync(nodeId);\n if (!node) {\n throw new Error(`Node with ID ${nodeId} not found`);\n }\n\n // Check if node is a frame or component that supports axis alignment\n if (\n node.type !== \"FRAME\" &&\n node.type !== \"COMPONENT\" &&\n node.type !== \"COMPONENT_SET\" &&\n node.type !== \"INSTANCE\"\n ) {\n throw new Error(`Node type ${node.type} does not support axis alignment`);\n }\n\n // Check if the node has auto-layout enabled\n if (node.layoutMode === \"NONE\") {\n throw new Error(\n \"Axis alignment can only be set on auto-layout frames (layoutMode must not be NONE)\"\n );\n }\n\n // Validate and set primaryAxisAlignItems if provided\n if (primaryAxisAlignItems !== undefined) {\n if (\n ![\"MIN\", \"MAX\", \"CENTER\", \"SPACE_BETWEEN\"].includes(primaryAxisAlignItems)\n ) {\n throw new Error(\n \"Invalid primaryAxisAlignItems value. Must be one of: MIN, MAX, CENTER, SPACE_BETWEEN\"\n );\n }\n node.primaryAxisAlignItems = primaryAxisAlignItems;\n }\n\n // Validate and set counterAxisAlignItems if provided\n if (counterAxisAlignItems !== undefined) {\n if (![\"MIN\", \"MAX\", \"CENTER\", \"BASELINE\"].includes(counterAxisAlignItems)) {\n throw new Error(\n \"Invalid counterAxisAlignItems value. Must be one of: MIN, MAX, CENTER, BASELINE\"\n );\n }\n // BASELINE is only valid for horizontal layout\n if (\n counterAxisAlignItems === \"BASELINE\" &&\n node.layoutMode !== \"HORIZONTAL\"\n ) {\n throw new Error(\n \"BASELINE alignment is only valid for horizontal auto-layout frames\"\n );\n }\n node.counterAxisAlignItems = counterAxisAlignItems;\n }\n\n return {\n id: node.id,\n name: node.name,\n primaryAxisAlignItems: node.primaryAxisAlignItems,\n counterAxisAlignItems: node.counterAxisAlignItems,\n layoutMode: node.layoutMode,\n };\n}\n\nasync function setLayoutSizing(params) {\n const { nodeId, layoutSizingHorizontal, layoutSizingVertical } = params || {};\n\n // Get the target node\n const node = await figma.getNodeByIdAsync(nodeId);\n if (!node) {\n throw new Error(`Node with ID ${nodeId} not found`);\n }\n\n // Check if node is a frame or component that supports layout sizing\n if (\n node.type !== \"FRAME\" &&\n node.type !== \"COMPONENT\" &&\n node.type !== \"COMPONENT_SET\" &&\n node.type !== \"INSTANCE\"\n ) {\n throw new Error(`Node type ${node.type} does not support layout sizing`);\n }\n\n // Check if the node has auto-layout enabled\n if (node.layoutMode === \"NONE\") {\n throw new Error(\n \"Layout sizing can only be set on auto-layout frames (layoutMode must not be NONE)\"\n );\n }\n\n // Validate and set layoutSizingHorizontal if provided\n if (layoutSizingHorizontal !== undefined) {\n if (![\"FIXED\", \"HUG\", \"FILL\"].includes(layoutSizingHorizontal)) {\n throw new Error(\n \"Invalid layoutSizingHorizontal value. Must be one of: FIXED, HUG, FILL\"\n );\n }\n // HUG is only valid on auto-layout frames and text nodes\n if (\n layoutSizingHorizontal === \"HUG\" &&\n ![\"FRAME\", \"TEXT\"].includes(node.type)\n ) {\n throw new Error(\n \"HUG sizing is only valid on auto-layout frames and text nodes\"\n );\n }\n // FILL is only valid on auto-layout children\n if (\n layoutSizingHorizontal === \"FILL\" &&\n (!node.parent || node.parent.layoutMode === \"NONE\")\n ) {\n throw new Error(\"FILL sizing is only valid on auto-layout children\");\n }\n node.layoutSizingHorizontal = layoutSizingHorizontal;\n }\n\n // Validate and set layoutSizingVertical if provided\n if (layoutSizingVertical !== undefined) {\n if (![\"FIXED\", \"HUG\", \"FILL\"].includes(layoutSizingVertical)) {\n throw new Error(\n \"Invalid layoutSizingVertical value. Must be one of: FIXED, HUG, FILL\"\n );\n }\n // HUG is only valid on auto-layout frames and text nodes\n if (\n layoutSizingVertical === \"HUG\" &&\n ![\"FRAME\", \"TEXT\"].includes(node.type)\n ) {\n throw new Error(\n \"HUG sizing is only valid on auto-layout frames and text nodes\"\n );\n }\n // FILL is only valid on auto-layout children\n if (\n layoutSizingVertical === \"FILL\" &&\n (!node.parent || node.parent.layoutMode === \"NONE\")\n ) {\n throw new Error(\"FILL sizing is only valid on auto-layout children\");\n }\n node.layoutSizingVertical = layoutSizingVertical;\n }\n\n return {\n id: node.id,\n name: node.name,\n layoutSizingHorizontal: node.layoutSizingHorizontal,\n layoutSizingVertical: node.layoutSizingVertical,\n layoutMode: node.layoutMode,\n };\n}\n\nasync function setItemSpacing(params) {\n const { nodeId, itemSpacing } = params || {};\n\n // Get the target node\n const node = await figma.getNodeByIdAsync(nodeId);\n if (!node) {\n throw new Error(`Node with ID ${nodeId} not found`);\n }\n\n // Check if node is a frame or component that supports item spacing\n if (\n node.type !== \"FRAME\" &&\n node.type !== \"COMPONENT\" &&\n node.type !== \"COMPONENT_SET\" &&\n node.type !== \"INSTANCE\"\n ) {\n throw new Error(`Node type ${node.type} does not support item spacing`);\n }\n\n // Check if the node has auto-layout enabled\n if (node.layoutMode === \"NONE\") {\n throw new Error(\n \"Item spacing can only be set on auto-layout frames (layoutMode must not be NONE)\"\n );\n }\n\n // Set item spacing\n if (itemSpacing !== undefined) {\n if (typeof itemSpacing !== \"number\") {\n throw new Error(\"Item spacing must be a number\");\n }\n node.itemSpacing = itemSpacing;\n }\n\n return {\n id: node.id,\n name: node.name,\n itemSpacing: node.itemSpacing,\n layoutMode: node.layoutMode,\n };\n}\n\nasync function setDefaultConnector(params) {\n const { connectorId } = params || {};\n \n // If connectorId is provided, search and set by that ID (do not check existing storage)\n if (connectorId) {\n // Get node by specified ID\n const node = await figma.getNodeByIdAsync(connectorId);\n if (!node) {\n throw new Error(`Connector node not found with ID: ${connectorId}`);\n }\n \n // Check node type\n if (node.type !== 'CONNECTOR') {\n throw new Error(`Node is not a connector: ${connectorId}`);\n }\n \n // Set the found connector as the default connector\n await figma.clientStorage.setAsync('defaultConnectorId', connectorId);\n \n return {\n success: true,\n message: `Default connector set to: ${connectorId}`,\n connectorId: connectorId\n };\n } \n // If connectorId is not provided, check existing storage\n else {\n // Check if there is an existing default connector in client storage\n try {\n const existingConnectorId = await figma.clientStorage.getAsync('defaultConnectorId');\n \n // If there is an existing connector ID, check if the node is still valid\n if (existingConnectorId) {\n try {\n const existingConnector = await figma.getNodeByIdAsync(existingConnectorId);\n \n // If the stored connector still exists and is of type CONNECTOR\n if (existingConnector && existingConnector.type === 'CONNECTOR') {\n return {\n success: true,\n message: `Default connector is already set to: ${existingConnectorId}`,\n connectorId: existingConnectorId,\n exists: true\n };\n }\n // The stored connector is no longer valid - find a new connector\n else {\n console.log(`Stored connector ID ${existingConnectorId} is no longer valid, finding a new connector...`);\n }\n } catch (error) {\n console.log(`Error finding stored connector: ${error.message}. Will try to set a new one.`);\n }\n }\n } catch (error) {\n console.log(`Error checking for existing connector: ${error.message}`);\n }\n \n // If there is no stored default connector or it is invalid, find one in the current page\n try {\n // Find CONNECTOR type nodes in the current page\n const currentPageConnectors = figma.currentPage.findAllWithCriteria({ types: ['CONNECTOR'] });\n \n if (currentPageConnectors && currentPageConnectors.length > 0) {\n // Use the first connector found\n const foundConnector = currentPageConnectors[0];\n const autoFoundId = foundConnector.id;\n \n // Set the found connector as the default connector\n await figma.clientStorage.setAsync('defaultConnectorId', autoFoundId);\n \n return {\n success: true,\n message: `Automatically found and set default connector to: ${autoFoundId}`,\n connectorId: autoFoundId,\n autoSelected: true\n };\n } else {\n // If no connector is found in the current page, show a guide message\n throw new Error('No connector found in the current page. Please create a connector in Figma first or specify a connector ID.');\n }\n } catch (error) {\n // Error occurred while running findAllWithCriteria\n throw new Error(`Failed to find a connector: ${error.message}`);\n }\n }\n}\n\nasync function createCursorNode(targetNodeId) {\n const svgString = `\n \n `;\n try {\n const targetNode = await figma.getNodeByIdAsync(targetNodeId);\n if (!targetNode) throw new Error(\"Target node not found\");\n\n // The targetNodeId has semicolons since it is a nested node.\n // So we need to get the parent node ID from the target node ID and check if we can appendChild to it or not.\n let parentNodeId = targetNodeId.includes(';') \n ? targetNodeId.split(';')[0] \n : targetNodeId;\n if (!parentNodeId) throw new Error(\"Could not determine parent node ID\");\n\n // Find the parent node to append cursor node as child\n let parentNode = await figma.getNodeByIdAsync(parentNodeId);\n if (!parentNode) throw new Error(\"Parent node not found\");\n\n // If the parent node is not eligible to appendChild, set the parentNode to the parent of the parentNode\n if (parentNode.type === 'INSTANCE' || parentNode.type === 'COMPONENT' || parentNode.type === 'COMPONENT_SET') {\n parentNode = parentNode.parent;\n if (!parentNode) throw new Error(\"Parent node not found\");\n }\n\n // Create the cursor node\n const importedNode = await figma.createNodeFromSvg(svgString);\n if (!importedNode || !importedNode.id) {\n throw new Error(\"Failed to create imported cursor node\");\n }\n importedNode.name = \"TTF_Connector / Mouse Cursor\";\n importedNode.resize(48, 48);\n\n const cursorNode = importedNode.findOne(node => node.type === 'VECTOR');\n if (cursorNode) {\n cursorNode.fills = [{\n type: 'SOLID',\n color: { r: 0, g: 0, b: 0 },\n opacity: 1\n }];\n cursorNode.strokes = [{\n type: 'SOLID',\n color: { r: 1, g: 1, b: 1 },\n opacity: 1\n }];\n cursorNode.strokeWeight = 2;\n cursorNode.strokeAlign = 'OUTSIDE';\n cursorNode.effects = [{\n type: \"DROP_SHADOW\",\n color: { r: 0, g: 0, b: 0, a: 0.3 },\n offset: { x: 1, y: 1 },\n radius: 2,\n spread: 0,\n visible: true,\n blendMode: \"NORMAL\"\n }];\n }\n\n // Append the cursor node to the parent node\n parentNode.appendChild(importedNode);\n\n // if the parentNode has auto-layout enabled, set the layoutPositioning to ABSOLUTE\n if ('layoutMode' in parentNode && parentNode.layoutMode !== 'NONE') {\n importedNode.layoutPositioning = 'ABSOLUTE';\n }\n\n // Adjust the importedNode's position to the targetNode's position\n if (\n targetNode.absoluteBoundingBox &&\n parentNode.absoluteBoundingBox\n ) {\n // if the targetNode has absoluteBoundingBox, set the importedNode's absoluteBoundingBox to the targetNode's absoluteBoundingBox\n console.log('targetNode.absoluteBoundingBox', targetNode.absoluteBoundingBox);\n console.log('parentNode.absoluteBoundingBox', parentNode.absoluteBoundingBox);\n importedNode.x = targetNode.absoluteBoundingBox.x - parentNode.absoluteBoundingBox.x + targetNode.absoluteBoundingBox.width / 2 - 48 / 2\n importedNode.y = targetNode.absoluteBoundingBox.y - parentNode.absoluteBoundingBox.y + targetNode.absoluteBoundingBox.height / 2 - 48 / 2;\n } else if (\n 'x' in targetNode && 'y' in targetNode && 'width' in targetNode && 'height' in targetNode) {\n // if the targetNode has x, y, width, height, calculate center based on relative position\n console.log('targetNode.x/y/width/height', targetNode.x, targetNode.y, targetNode.width, targetNode.height);\n importedNode.x = targetNode.x + targetNode.width / 2 - 48 / 2;\n importedNode.y = targetNode.y + targetNode.height / 2 - 48 / 2;\n } else {\n // Fallback: Place at top-left of target if possible, otherwise at (0,0) relative to parent\n if ('x' in targetNode && 'y' in targetNode) {\n console.log('Fallback to targetNode x/y');\n importedNode.x = targetNode.x;\n importedNode.y = targetNode.y;\n } else {\n console.log('Fallback to (0,0)');\n importedNode.x = 0;\n importedNode.y = 0;\n }\n }\n\n // get the importedNode ID and the importedNode\n console.log('importedNode', importedNode);\n\n\n return { id: importedNode.id, node: importedNode };\n \n } catch (error) {\n console.error(\"Error creating cursor from SVG:\", error);\n return { id: null, node: null, error: error.message };\n }\n}\n\nasync function createConnections(params) {\n if (!params || !params.connections || !Array.isArray(params.connections)) {\n throw new Error('Missing or invalid connections parameter');\n }\n \n const { connections } = params;\n \n // Command ID for progress tracking\n const commandId = generateCommandId();\n sendProgressUpdate(\n commandId,\n \"create_connections\",\n \"started\",\n 0,\n connections.length,\n 0,\n `Starting to create ${connections.length} connections`\n );\n \n // Get default connector ID from client storage\n const defaultConnectorId = await figma.clientStorage.getAsync('defaultConnectorId');\n if (!defaultConnectorId) {\n throw new Error('No default connector set. Please try one of the following options to create connections:\\n1. Create a connector in FigJam and copy/paste it to your current page, then run the \"set_default_connector\" command.\\n2. Select an existing connector on the current page, then run the \"set_default_connector\" command.');\n }\n \n // Get the default connector\n const defaultConnector = await figma.getNodeByIdAsync(defaultConnectorId);\n if (!defaultConnector) {\n throw new Error(`Default connector not found with ID: ${defaultConnectorId}`);\n }\n if (defaultConnector.type !== 'CONNECTOR') {\n throw new Error(`Node is not a connector: ${defaultConnectorId}`);\n }\n \n // Results array for connection creation\n const results = [];\n let processedCount = 0;\n const totalCount = connections.length;\n \n // Preload fonts (used for text if provided)\n let fontLoaded = false;\n \n for (let i = 0; i < connections.length; i++) {\n try {\n const { startNodeId: originalStartId, endNodeId: originalEndId, text } = connections[i];\n let startId = originalStartId;\n let endId = originalEndId;\n\n // Check and potentially replace start node ID\n if (startId.includes(';')) {\n console.log(`Nested start node detected: ${startId}. Creating cursor node.`);\n const cursorResult = await createCursorNode(startId);\n if (!cursorResult || !cursorResult.id) {\n throw new Error(`Failed to create cursor node for nested start node: ${startId}`);\n }\n startId = cursorResult.id; \n } \n \n const startNode = await figma.getNodeByIdAsync(startId);\n if (!startNode) throw new Error(`Start node not found with ID: ${startId}`);\n\n // Check and potentially replace end node ID\n if (endId.includes(';')) {\n console.log(`Nested end node detected: ${endId}. Creating cursor node.`);\n const cursorResult = await createCursorNode(endId);\n if (!cursorResult || !cursorResult.id) {\n throw new Error(`Failed to create cursor node for nested end node: ${endId}`);\n }\n endId = cursorResult.id;\n }\n const endNode = await figma.getNodeByIdAsync(endId);\n if (!endNode) throw new Error(`End node not found with ID: ${endId}`);\n\n \n // Clone the default connector\n const clonedConnector = defaultConnector.clone();\n \n // Update connector name using potentially replaced node names\n clonedConnector.name = `TTF_Connector/${startNode.id}/${endNode.id}`;\n \n // Set start and end points using potentially replaced IDs\n clonedConnector.connectorStart = {\n endpointNodeId: startId,\n magnet: 'AUTO'\n };\n \n clonedConnector.connectorEnd = {\n endpointNodeId: endId,\n magnet: 'AUTO'\n };\n \n // Add text (if provided)\n if (text) {\n try {\n // Try to load the necessary fonts\n try {\n // First check if default connector has font and use the same\n if (defaultConnector.text && defaultConnector.text.fontName) {\n const fontName = defaultConnector.text.fontName;\n await figma.loadFontAsync(fontName);\n clonedConnector.text.fontName = fontName;\n } else {\n // Try default Inter font\n await figma.loadFontAsync({ family: \"Inter\", style: \"Regular\" });\n }\n } catch (fontError) {\n // If first font load fails, try another font style\n try {\n await figma.loadFontAsync({ family: \"Inter\", style: \"Medium\" });\n } catch (mediumFontError) {\n // If second font fails, try system font\n try {\n await figma.loadFontAsync({ family: \"System\", style: \"Regular\" });\n } catch (systemFontError) {\n // If all font loading attempts fail, throw error\n throw new Error(`Failed to load any font: ${fontError.message}`);\n }\n }\n }\n \n // Set the text\n clonedConnector.text.characters = text;\n } catch (textError) {\n console.error(\"Error setting text:\", textError);\n // Continue with connection even if text setting fails\n results.push({\n id: clonedConnector.id,\n startNodeId: startNodeId,\n endNodeId: endNodeId,\n text: \"\",\n textError: textError.message\n });\n \n // Continue to next connection\n continue;\n }\n }\n \n // Add to results (using the *original* IDs for reference if needed)\n results.push({\n id: clonedConnector.id,\n originalStartNodeId: originalStartId,\n originalEndNodeId: originalEndId,\n usedStartNodeId: startId, // ID actually used for connection\n usedEndNodeId: endId, // ID actually used for connection\n text: text || \"\"\n });\n \n // Update progress\n processedCount++;\n sendProgressUpdate(\n commandId,\n \"create_connections\",\n \"in_progress\",\n processedCount / totalCount,\n totalCount,\n processedCount,\n `Created connection ${processedCount}/${totalCount}`\n );\n \n } catch (error) {\n console.error(\"Error creating connection\", error);\n // Continue processing remaining connections even if an error occurs\n processedCount++;\n sendProgressUpdate(\n commandId,\n \"create_connections\",\n \"in_progress\",\n processedCount / totalCount,\n totalCount,\n processedCount,\n `Error creating connection: ${error.message}`\n );\n \n results.push({\n error: error.message,\n connectionInfo: connections[i]\n });\n }\n }\n \n // Completion update\n sendProgressUpdate(\n commandId,\n \"create_connections\",\n \"completed\",\n 1,\n totalCount,\n totalCount,\n `Completed creating ${results.length} connections`\n );\n \n return {\n success: true,\n count: results.length,\n connections: results\n };\n}\n", "middle_code": "async function scanNodesByTypes(params) {\n console.log(`Starting to scan nodes by types from node ID: ${params.nodeId}`);\n const { nodeId, types = [] } = params || {};\n if (!types || types.length === 0) {\n throw new Error(\"No types specified to search for\");\n }\n const node = await figma.getNodeByIdAsync(nodeId);\n if (!node) {\n throw new Error(`Node with ID ${nodeId} not found`);\n }\n const matchingNodes = [];\n const commandId = generateCommandId();\n sendProgressUpdate(\n commandId,\n \"scan_nodes_by_types\",\n \"started\",\n 0,\n 1,\n 0,\n `Starting scan of node \"${node.name || nodeId}\" for types: ${types.join(\n \", \"\n )}`,\n null\n );\n await findNodesByTypes(node, types, matchingNodes);\n sendProgressUpdate(\n commandId,\n \"scan_nodes_by_types\",\n \"completed\",\n 100,\n matchingNodes.length,\n matchingNodes.length,\n `Scan complete. Found ${matchingNodes.length} matching nodes.`,\n { matchingNodes }\n );\n return {\n success: true,\n message: `Found ${matchingNodes.length} matching nodes.`,\n count: matchingNodes.length,\n matchingNodes: matchingNodes,\n searchedTypes: types,\n };\n}", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "javascript", "sub_task_type": null}, "context_code": [["/cursor-talk-to-figma-mcp/src/cursor_mcp_plugin/setcharacters.js", "function uniqBy(arr, predicate) {\n const cb = typeof predicate === \"function\" ? predicate : (o) => o[predicate];\n return [\n ...arr\n .reduce((map, item) => {\n const key = item === null || item === undefined ? item : cb(item);\n\n map.has(key) || map.set(key, item);\n\n return map;\n }, new Map())\n .values(),\n ];\n}\nexport const setCharacters = async (node, characters, options) => {\n const fallbackFont = options?.fallbackFont || {\n family: \"Roboto\",\n style: \"Regular\",\n };\n try {\n if (node.fontName === figma.mixed) {\n if (options?.smartStrategy === \"prevail\") {\n const fontHashTree = {};\n for (let i = 1; i < node.characters.length; i++) {\n const charFont = node.getRangeFontName(i - 1, i);\n const key = `${charFont.family}::${charFont.style}`;\n fontHashTree[key] = fontHashTree[key] ? fontHashTree[key] + 1 : 1;\n }\n const prevailedTreeItem = Object.entries(fontHashTree).sort(\n (a, b) => b[1] - a[1]\n )[0];\n const [family, style] = prevailedTreeItem[0].split(\"::\");\n const prevailedFont = {\n family,\n style,\n };\n await figma.loadFontAsync(prevailedFont);\n node.fontName = prevailedFont;\n } else if (options?.smartStrategy === \"strict\") {\n return setCharactersWithStrictMatchFont(node, characters, fallbackFont);\n } else if (options?.smartStrategy === \"experimental\") {\n return setCharactersWithSmartMatchFont(node, characters, fallbackFont);\n } else {\n const firstCharFont = node.getRangeFontName(0, 1);\n await figma.loadFontAsync(firstCharFont);\n node.fontName = firstCharFont;\n }\n } else {\n await figma.loadFontAsync({\n family: node.fontName.family,\n style: node.fontName.style,\n });\n }\n } catch (err) {\n console.warn(\n `Failed to load \"${node.fontName[\"family\"]} ${node.fontName[\"style\"]}\" font and replaced with fallback \"${fallbackFont.family} ${fallbackFont.style}\"`,\n err\n );\n await figma.loadFontAsync(fallbackFont);\n node.fontName = fallbackFont;\n }\n try {\n node.characters = characters;\n return true;\n } catch (err) {\n console.warn(`Failed to set characters. Skipped.`, err);\n return false;\n }\n};\n\nconst setCharactersWithStrictMatchFont = async (\n node,\n characters,\n fallbackFont\n) => {\n const fontHashTree = {};\n for (let i = 1; i < node.characters.length; i++) {\n const startIdx = i - 1;\n const startCharFont = node.getRangeFontName(startIdx, i);\n const startCharFontVal = `${startCharFont.family}::${startCharFont.style}`;\n while (i < node.characters.length) {\n i++;\n const charFont = node.getRangeFontName(i - 1, i);\n if (startCharFontVal !== `${charFont.family}::${charFont.style}`) {\n break;\n }\n }\n fontHashTree[`${startIdx}_${i}`] = startCharFontVal;\n }\n await figma.loadFontAsync(fallbackFont);\n node.fontName = fallbackFont;\n node.characters = characters;\n console.log(fontHashTree);\n await Promise.all(\n Object.keys(fontHashTree).map(async (range) => {\n console.log(range, fontHashTree[range]);\n const [start, end] = range.split(\"_\");\n const [family, style] = fontHashTree[range].split(\"::\");\n const matchedFont = {\n family,\n style,\n };\n await figma.loadFontAsync(matchedFont);\n return node.setRangeFontName(Number(start), Number(end), matchedFont);\n })\n );\n return true;\n};\n\nconst getDelimiterPos = (str, delimiter, startIdx = 0, endIdx = str.length) => {\n const indices = [];\n let temp = startIdx;\n for (let i = startIdx; i < endIdx; i++) {\n if (\n str[i] === delimiter &&\n i + startIdx !== endIdx &&\n temp !== i + startIdx\n ) {\n indices.push([temp, i + startIdx]);\n temp = i + startIdx + 1;\n }\n }\n temp !== endIdx && indices.push([temp, endIdx]);\n return indices.filter(Boolean);\n};\n\nconst buildLinearOrder = (node) => {\n const fontTree = [];\n const newLinesPos = getDelimiterPos(node.characters, \"\\n\");\n newLinesPos.forEach(([newLinesRangeStart, newLinesRangeEnd], n) => {\n const newLinesRangeFont = node.getRangeFontName(\n newLinesRangeStart,\n newLinesRangeEnd\n );\n if (newLinesRangeFont === figma.mixed) {\n const spacesPos = getDelimiterPos(\n node.characters,\n \" \",\n newLinesRangeStart,\n newLinesRangeEnd\n );\n spacesPos.forEach(([spacesRangeStart, spacesRangeEnd], s) => {\n const spacesRangeFont = node.getRangeFontName(\n spacesRangeStart,\n spacesRangeEnd\n );\n if (spacesRangeFont === figma.mixed) {\n const spacesRangeFont = node.getRangeFontName(\n spacesRangeStart,\n spacesRangeStart[0]\n );\n fontTree.push({\n start: spacesRangeStart,\n delimiter: \" \",\n family: spacesRangeFont.family,\n style: spacesRangeFont.style,\n });\n } else {\n fontTree.push({\n start: spacesRangeStart,\n delimiter: \" \",\n family: spacesRangeFont.family,\n style: spacesRangeFont.style,\n });\n }\n });\n } else {\n fontTree.push({\n start: newLinesRangeStart,\n delimiter: \"\\n\",\n family: newLinesRangeFont.family,\n style: newLinesRangeFont.style,\n });\n }\n });\n return fontTree\n .sort((a, b) => +a.start - +b.start)\n .map(({ family, style, delimiter }) => ({ family, style, delimiter }));\n};\n\nconst setCharactersWithSmartMatchFont = async (\n node,\n characters,\n fallbackFont\n) => {\n const rangeTree = buildLinearOrder(node);\n const fontsToLoad = uniqBy(\n rangeTree,\n ({ family, style }) => `${family}::${style}`\n ).map(({ family, style }) => ({\n family,\n style,\n }));\n\n await Promise.all([...fontsToLoad, fallbackFont].map(figma.loadFontAsync));\n\n node.fontName = fallbackFont;\n node.characters = characters;\n\n let prevPos = 0;\n rangeTree.forEach(({ family, style, delimiter }) => {\n if (prevPos < node.characters.length) {\n const delimeterPos = node.characters.indexOf(delimiter, prevPos);\n const endPos =\n delimeterPos > prevPos ? delimeterPos : node.characters.length;\n const matchedFont = {\n family,\n style,\n };\n node.setRangeFontName(prevPos, endPos, matchedFont);\n prevPos = endPos + 1;\n }\n });\n return true;\n};\n"]], "task_instance_info": {"created_time": "2025-08-20 23:58:36", "created_task_model": "DeepSeek-R1", "function_skeleton": "async function scanNodesByTypes (params) {}", "code_description": "This code segment functions to: Traverse hierarchical node structures to identify elements matching specified criteria, recursively examine nested elements, and track search progress through status updates while filtering results based on predetermined classification parameters."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```javascript\n[TASK_BEGIN]\nasync function scanNodesByTypes(params) {\n const { nodeId, types = [] } = params || {};\n\n if (!nodeId) {\n throw new Error(\"Missing nodeId parameter\");\n }\n\n if (!types || !Array.isArray(types) || types.length === 0) {\n throw new Error(\"Missing or invalid types parameter\");\n }\n\n const node = await figma.getNodeByIdAsync(nodeId);\n if (!node) {\n throw new Error(`Node not found with ID: ${nodeId}`);\n }\n\n const matchingNodes = [];\n await findNodesByTypes(node, types, matchingNodes);\n\n return {\n nodeId: node.id,\n nodeName: node.name,\n matchedCount: matchingNodes.length,\n matchedTypes: types,\n matchedNodes: matchingNodes\n };\n}\n[TASK_END]\n```", "inference_time": "2025-08-20 23-59-21"}, "editdistance_info": {"edit_distance": 31.6327, "calculate_time": "2025-08-20 23:59:21", "true_code_clean": "async function scanNodesByTypes(params) {\n console.log(`Starting to scan nodes by types from node ID: ${params.nodeId}`);\n const { nodeId, types = [] } = params || {};\n if (!types || types.length === 0) {\n throw new Error(\"No types specified to search for\");\n }\n const node = await figma.getNodeByIdAsync(nodeId);\n if (!node) {\n throw new Error(`Node with ID ${nodeId} not found`);\n }\n const matchingNodes = [];\n const commandId = generateCommandId();\n sendProgressUpdate(\n commandId,\n \"scan_nodes_by_types\",\n \"started\",\n 0,\n 1,\n 0,\n `Starting scan of node \"${node.name || nodeId}\" for types: ${types.join(\n \", \"\n )}`,\n null\n );\n await findNodesByTypes(node, types, matchingNodes);\n sendProgressUpdate(\n commandId,\n \"scan_nodes_by_types\",\n \"completed\",\n 100,\n matchingNodes.length,\n matchingNodes.length,\n `Scan complete. Found ${matchingNodes.length} matching nodes.`,\n { matchingNodes }\n );\n return {\n success: true,\n message: `Found ${matchingNodes.length} matching nodes.`,\n count: matchingNodes.length,\n matchingNodes: matchingNodes,\n searchedTypes: types,\n };\n}", "predict_code_clean": "async function scanNodesByTypes(params) {\n const { nodeId, types = [] } = params || {};\n if (!nodeId) {\n throw new Error(\"Missing nodeId parameter\");\n }\n if (!types || !Array.isArray(types) || types.length === 0) {\n throw new Error(\"Missing or invalid types parameter\");\n }\n const node = await figma.getNodeByIdAsync(nodeId);\n if (!node) {\n throw new Error(`Node not found with ID: ${nodeId}`);\n }\n const matchingNodes = [];\n await findNodesByTypes(node, types, matchingNodes);\n return {\n nodeId: node.id,\n nodeName: node.name,\n matchedCount: matchingNodes.length,\n matchedTypes: types,\n matchedNodes: matchingNodes\n };\n}"}} {"repo_name": "cursor-talk-to-figma-mcp", "file_name": "/cursor-talk-to-figma-mcp/src/cursor_mcp_plugin/code.js", "inference_info": {"prefix_code": "// This is the main code file for the Cursor MCP Figma plugin\n// It handles Figma API commands\n\n// Plugin state\nconst state = {\n serverPort: 3055, // Default port\n};\n\n\n// Helper function for progress updates\nfunction sendProgressUpdate(\n commandId,\n commandType,\n status,\n progress,\n totalItems,\n processedItems,\n message,\n payload = null\n) {\n const update = {\n type: \"command_progress\",\n commandId,\n commandType,\n status,\n progress,\n totalItems,\n processedItems,\n message,\n timestamp: Date.now(),\n };\n\n // Add optional chunk information if present\n if (payload) {\n if (\n payload.currentChunk !== undefined &&\n payload.totalChunks !== undefined\n ) {\n update.currentChunk = payload.currentChunk;\n update.totalChunks = payload.totalChunks;\n update.chunkSize = payload.chunkSize;\n }\n update.payload = payload;\n }\n\n // Send to UI\n figma.ui.postMessage(update);\n console.log(`Progress update: ${status} - ${progress}% - ${message}`);\n\n return update;\n}\n\n// Show UI\nfigma.showUI(__html__, { width: 350, height: 450 });\n\n// Plugin commands from UI\nfigma.ui.onmessage = async (msg) => {\n switch (msg.type) {\n case \"update-settings\":\n updateSettings(msg);\n break;\n case \"notify\":\n figma.notify(msg.message);\n break;\n case \"close-plugin\":\n figma.closePlugin();\n break;\n case \"execute-command\":\n // Execute commands received from UI (which gets them from WebSocket)\n try {\n const result = await handleCommand(msg.command, msg.params);\n // Send result back to UI\n figma.ui.postMessage({\n type: \"command-result\",\n id: msg.id,\n result,\n });\n } catch (error) {\n figma.ui.postMessage({\n type: \"command-error\",\n id: msg.id,\n error: error.message || \"Error executing command\",\n });\n }\n break;\n }\n};\n\n// Listen for plugin commands from menu\nfigma.on(\"run\", ({ command }) => {\n figma.ui.postMessage({ type: \"auto-connect\" });\n});\n\n// Update plugin settings\nfunction updateSettings(settings) {\n if (settings.serverPort) {\n state.serverPort = settings.serverPort;\n }\n\n figma.clientStorage.setAsync(\"settings\", {\n serverPort: state.serverPort,\n });\n}\n\n// Handle commands from UI\nasync function handleCommand(command, params) {\n switch (command) {\n case \"get_document_info\":\n return await getDocumentInfo();\n case \"get_selection\":\n return await getSelection();\n case \"get_node_info\":\n if (!params || !params.nodeId) {\n throw new Error(\"Missing nodeId parameter\");\n }\n return await getNodeInfo(params.nodeId);\n case \"get_nodes_info\":\n if (!params || !params.nodeIds || !Array.isArray(params.nodeIds)) {\n throw new Error(\"Missing or invalid nodeIds parameter\");\n }\n return await getNodesInfo(params.nodeIds);\n case \"read_my_design\":\n return await readMyDesign();\n case \"create_rectangle\":\n return await createRectangle(params);\n case \"create_frame\":\n return await createFrame(params);\n case \"create_text\":\n return await createText(params);\n case \"set_fill_color\":\n return await setFillColor(params);\n case \"set_stroke_color\":\n return await setStrokeColor(params);\n case \"move_node\":\n return await moveNode(params);\n case \"resize_node\":\n return await resizeNode(params);\n case \"delete_node\":\n return await deleteNode(params);\n case \"delete_multiple_nodes\":\n return await deleteMultipleNodes(params);\n case \"get_styles\":\n return await getStyles();\n case \"get_local_components\":\n return await getLocalComponents();\n // case \"get_team_components\":\n // return await getTeamComponents();\n case \"create_component_instance\":\n return await createComponentInstance(params);\n case \"export_node_as_image\":\n return await exportNodeAsImage(params);\n case \"set_corner_radius\":\n return await setCornerRadius(params);\n case \"set_text_content\":\n return await setTextContent(params);\n case \"clone_node\":\n return await cloneNode(params);\n case \"scan_text_nodes\":\n return await scanTextNodes(params);\n case \"set_multiple_text_contents\":\n return await setMultipleTextContents(params);\n case \"get_annotations\":\n return await getAnnotations(params);\n case \"set_annotation\":\n return await setAnnotation(params);\n case \"scan_nodes_by_types\":\n return await scanNodesByTypes(params);\n case \"set_multiple_annotations\":\n return await setMultipleAnnotations(params);\n case \"get_instance_overrides\":\n // Check if instanceNode parameter is provided\n if (params && params.instanceNodeId) {\n // Get the instance node by ID\n const instanceNode = await figma.getNodeByIdAsync(params.instanceNodeId);\n if (!instanceNode) {\n throw new Error(`Instance node not found with ID: ${params.instanceNodeId}`);\n }\n return await getInstanceOverrides(instanceNode);\n }\n // Call without instance node if not provided\n return await getInstanceOverrides();\n\n case \"set_instance_overrides\":\n // Check if instanceNodeIds parameter is provided\n if (params && params.targetNodeIds) {\n // Validate that targetNodeIds is an array\n if (!Array.isArray(params.targetNodeIds)) {\n throw new Error(\"targetNodeIds must be an array\");\n }\n\n // Get the instance nodes by IDs\n const targetNodes = await getValidTargetInstances(params.targetNodeIds);\n if (!targetNodes.success) {\n figma.notify(targetNodes.message);\n return { success: false, message: targetNodes.message };\n }\n\n if (params.sourceInstanceId) {\n\n // get source instance data\n let sourceInstanceData = null;\n sourceInstanceData = await getSourceInstanceData(params.sourceInstanceId);\n\n if (!sourceInstanceData.success) {\n figma.notify(sourceInstanceData.message);\n return { success: false, message: sourceInstanceData.message };\n }\n return await setInstanceOverrides(targetNodes.targetInstances, sourceInstanceData);\n } else {\n throw new Error(\"Missing sourceInstanceId parameter\");\n }\n }\n case \"set_layout_mode\":\n return await setLayoutMode(params);\n case \"set_padding\":\n return await setPadding(params);\n case \"set_axis_align\":\n return await setAxisAlign(params);\n case \"set_layout_sizing\":\n return await setLayoutSizing(params);\n case \"set_item_spacing\":\n return await setItemSpacing(params);\n case \"get_reactions\":\n if (!params || !params.nodeIds || !Array.isArray(params.nodeIds)) {\n throw new Error(\"Missing or invalid nodeIds parameter\");\n }\n return await getReactions(params.nodeIds); \n case \"set_default_connector\":\n return await setDefaultConnector(params);\n case \"create_connections\":\n return await createConnections(params);\n default:\n throw new Error(`Unknown command: ${command}`);\n }\n}\n\n// Command implementations\n\nasync function getDocumentInfo() {\n await figma.currentPage.loadAsync();\n const page = figma.currentPage;\n return {\n name: page.name,\n id: page.id,\n type: page.type,\n children: page.children.map((node) => ({\n id: node.id,\n name: node.name,\n type: node.type,\n })),\n currentPage: {\n id: page.id,\n name: page.name,\n childCount: page.children.length,\n },\n pages: [\n {\n id: page.id,\n name: page.name,\n childCount: page.children.length,\n },\n ],\n };\n}\n\nasync function getSelection() {\n return {\n selectionCount: figma.currentPage.selection.length,\n selection: figma.currentPage.selection.map((node) => ({\n id: node.id,\n name: node.name,\n type: node.type,\n visible: node.visible,\n })),\n };\n}\n\nfunction rgbaToHex(color) {\n var r = Math.round(color.r * 255);\n var g = Math.round(color.g * 255);\n var b = Math.round(color.b * 255);\n var a = color.a !== undefined ? Math.round(color.a * 255) : 255;\n\n if (a === 255) {\n return (\n \"#\" +\n [r, g, b]\n .map((x) => {\n return x.toString(16).padStart(2, \"0\");\n })\n .join(\"\")\n );\n }\n\n return (\n \"#\" +\n [r, g, b, a]\n .map((x) => {\n return x.toString(16).padStart(2, \"0\");\n })\n .join(\"\")\n );\n}\n\nfunction filterFigmaNode(node) {\n if (node.type === \"VECTOR\") {\n return null;\n }\n\n var filtered = {\n id: node.id,\n name: node.name,\n type: node.type,\n };\n\n if (node.fills && node.fills.length > 0) {\n filtered.fills = node.fills.map((fill) => {\n var processedFill = Object.assign({}, fill);\n delete processedFill.boundVariables;\n delete processedFill.imageRef;\n\n if (processedFill.gradientStops) {\n processedFill.gradientStops = processedFill.gradientStops.map(\n (stop) => {\n var processedStop = Object.assign({}, stop);\n if (processedStop.color) {\n processedStop.color = rgbaToHex(processedStop.color);\n }\n delete processedStop.boundVariables;\n return processedStop;\n }\n );\n }\n\n if (processedFill.color) {\n processedFill.color = rgbaToHex(processedFill.color);\n }\n\n return processedFill;\n });\n }\n\n if (node.strokes && node.strokes.length > 0) {\n filtered.strokes = node.strokes.map((stroke) => {\n var processedStroke = Object.assign({}, stroke);\n delete processedStroke.boundVariables;\n if (processedStroke.color) {\n processedStroke.color = rgbaToHex(processedStroke.color);\n }\n return processedStroke;\n });\n }\n\n if (node.cornerRadius !== undefined) {\n filtered.cornerRadius = node.cornerRadius;\n }\n\n if (node.absoluteBoundingBox) {\n filtered.absoluteBoundingBox = node.absoluteBoundingBox;\n }\n\n if (node.characters) {\n filtered.characters = node.characters;\n }\n\n if (node.style) {\n filtered.style = {\n fontFamily: node.style.fontFamily,\n fontStyle: node.style.fontStyle,\n fontWeight: node.style.fontWeight,\n fontSize: node.style.fontSize,\n textAlignHorizontal: node.style.textAlignHorizontal,\n letterSpacing: node.style.letterSpacing,\n lineHeightPx: node.style.lineHeightPx,\n };\n }\n\n if (node.children) {\n filtered.children = node.children\n .map((child) => {\n return filterFigmaNode(child);\n })\n .filter((child) => {\n return child !== null;\n });\n }\n\n return filtered;\n}\n\nasync function getNodeInfo(nodeId) {\n const node = await figma.getNodeByIdAsync(nodeId);\n\n if (!node) {\n throw new Error(`Node not found with ID: ${nodeId}`);\n }\n\n const response = await node.exportAsync({\n format: \"JSON_REST_V1\",\n });\n\n return filterFigmaNode(response.document);\n}\n\nasync function getNodesInfo(nodeIds) {\n try {\n // Load all nodes in parallel\n const nodes = await Promise.all(\n nodeIds.map((id) => figma.getNodeByIdAsync(id))\n );\n\n // Filter out any null values (nodes that weren't found)\n const validNodes = nodes.filter((node) => node !== null);\n\n // Export all valid nodes in parallel\n const responses = await Promise.all(\n validNodes.map(async (node) => {\n const response = await node.exportAsync({\n format: \"JSON_REST_V1\",\n });\n return {\n nodeId: node.id,\n document: filterFigmaNode(response.document),\n };\n })\n );\n\n return responses;\n } catch (error) {\n throw new Error(`Error getting nodes info: ${error.message}`);\n }\n}\n\nasync function getReactions(nodeIds) {\n try {\n const commandId = generateCommandId();\n sendProgressUpdate(\n commandId,\n \"get_reactions\",\n \"started\",\n 0,\n nodeIds.length,\n 0,\n `Starting deep search for reactions in ${nodeIds.length} nodes and their children`\n );\n\n // Function to find nodes with reactions from the node and all its children\n async function findNodesWithReactions(node, processedNodes = new Set(), depth = 0, results = []) {\n // Skip already processed nodes (prevent circular references)\n if (processedNodes.has(node.id)) {\n return results;\n }\n \n processedNodes.add(node.id);\n \n // Check if the current node has reactions\n let filteredReactions = [];\n if (node.reactions && node.reactions.length > 0) {\n // Filter out reactions with navigation === 'CHANGE_TO'\n filteredReactions = node.reactions.filter(r => {\n // Some reactions may have action or actions array\n if (r.action && r.action.navigation === 'CHANGE_TO') return false;\n if (Array.isArray(r.actions)) {\n // If any action in actions array is CHANGE_TO, exclude\n return !r.actions.some(a => a.navigation === 'CHANGE_TO');\n }\n return true;\n });\n }\n const hasFilteredReactions = filteredReactions.length > 0;\n \n // If the node has filtered reactions, add it to results and apply highlight effect\n if (hasFilteredReactions) {\n results.push({\n id: node.id,\n name: node.name,\n type: node.type,\n depth: depth,\n hasReactions: true,\n reactions: filteredReactions,\n path: getNodePath(node)\n });\n // Apply highlight effect (orange border)\n await highlightNodeWithAnimation(node);\n }\n \n // If node has children, recursively search them\n if (node.children) {\n for (const child of node.children) {\n await findNodesWithReactions(child, processedNodes, depth + 1, results);\n }\n }\n \n return results;\n }\n \n // Function to apply animated highlight effect to a node\n async function highlightNodeWithAnimation(node) {\n // Save original stroke properties\n const originalStrokeWeight = node.strokeWeight;\n const originalStrokes = node.strokes ? [...node.strokes] : [];\n \n try {\n // Apply orange border stroke\n node.strokeWeight = 4;\n node.strokes = [{\n type: 'SOLID',\n color: { r: 1, g: 0.5, b: 0 }, // Orange color\n opacity: 0.8\n }];\n \n // Set timeout for animation effect (restore to original after 1.5 seconds)\n setTimeout(() => {\n try {\n // Restore original stroke properties\n node.strokeWeight = originalStrokeWeight;\n node.strokes = originalStrokes;\n } catch (restoreError) {\n console.error(`Error restoring node stroke: ${restoreError.message}`);\n }\n }, 1500);\n } catch (highlightError) {\n console.error(`Error highlighting node: ${highlightError.message}`);\n // Continue even if highlighting fails\n }\n }\n \n // Get node hierarchy path as a string\n function getNodePath(node) {\n const path = [];\n let current = node;\n \n while (current && current.parent) {\n path.unshift(current.name);\n current = current.parent;\n }\n \n return path.join(' > ');\n }\n\n // Array to store all results\n let allResults = [];\n let processedCount = 0;\n const totalCount = nodeIds.length;\n \n // Iterate through each node and its children to search for reactions\n for (let i = 0; i < nodeIds.length; i++) {\n try {\n const nodeId = nodeIds[i];\n const node = await figma.getNodeByIdAsync(nodeId);\n \n if (!node) {\n processedCount++;\n sendProgressUpdate(\n commandId,\n \"get_reactions\",\n \"in_progress\",\n processedCount / totalCount,\n totalCount,\n processedCount,\n `Node not found: ${nodeId}`\n );\n continue;\n }\n \n // Search for reactions in the node and its children\n const processedNodes = new Set();\n const nodeResults = await findNodesWithReactions(node, processedNodes);\n \n // Add results\n allResults = allResults.concat(nodeResults);\n \n // Update progress\n processedCount++;\n sendProgressUpdate(\n commandId,\n \"get_reactions\",\n \"in_progress\",\n processedCount / totalCount,\n totalCount,\n processedCount,\n `Processed node ${processedCount}/${totalCount}, found ${nodeResults.length} nodes with reactions`\n );\n } catch (error) {\n processedCount++;\n sendProgressUpdate(\n commandId,\n \"get_reactions\",\n \"in_progress\",\n processedCount / totalCount,\n totalCount,\n processedCount,\n `Error processing node: ${error.message}`\n );\n }\n }\n\n // Completion update\n sendProgressUpdate(\n commandId,\n \"get_reactions\",\n \"completed\",\n 1,\n totalCount,\n totalCount,\n `Completed deep search: found ${allResults.length} nodes with reactions.`\n );\n\n return {\n nodesCount: nodeIds.length,\n nodesWithReactions: allResults.length,\n nodes: allResults\n };\n } catch (error) {\n throw new Error(`Failed to get reactions: ${error.message}`);\n }\n}\n\nasync function readMyDesign() {\n try {\n // Load all selected nodes in parallel\n const nodes = await Promise.all(\n figma.currentPage.selection.map((node) => figma.getNodeByIdAsync(node.id))\n );\n\n // Filter out any null values (nodes that weren't found)\n const validNodes = nodes.filter((node) => node !== null);\n\n // Export all valid nodes in parallel\n const responses = await Promise.all(\n validNodes.map(async (node) => {\n const response = await node.exportAsync({\n format: \"JSON_REST_V1\",\n });\n return {\n nodeId: node.id,\n document: filterFigmaNode(response.document),\n };\n })\n );\n\n return responses;\n } catch (error) {\n throw new Error(`Error getting nodes info: ${error.message}`);\n }\n}\n\nasync function createRectangle(params) {\n const {\n x = 0,\n y = 0,\n width = 100,\n height = 100,\n name = \"Rectangle\",\n parentId,\n } = params || {};\n\n const rect = figma.createRectangle();\n rect.x = x;\n rect.y = y;\n rect.resize(width, height);\n rect.name = name;\n\n // If parentId is provided, append to that node, otherwise append to current page\n if (parentId) {\n const parentNode = await figma.getNodeByIdAsync(parentId);\n if (!parentNode) {\n throw new Error(`Parent node not found with ID: ${parentId}`);\n }\n if (!(\"appendChild\" in parentNode)) {\n throw new Error(`Parent node does not support children: ${parentId}`);\n }\n parentNode.appendChild(rect);\n } else {\n figma.currentPage.appendChild(rect);\n }\n\n return {\n id: rect.id,\n name: rect.name,\n x: rect.x,\n y: rect.y,\n width: rect.width,\n height: rect.height,\n parentId: rect.parent ? rect.parent.id : undefined,\n };\n}\n\nasync function createFrame(params) {\n const {\n x = 0,\n y = 0,\n width = 100,\n height = 100,\n name = \"Frame\",\n parentId,\n fillColor,\n strokeColor,\n strokeWeight,\n layoutMode = \"NONE\",\n layoutWrap = \"NO_WRAP\",\n paddingTop = 10,\n paddingRight = 10,\n paddingBottom = 10,\n paddingLeft = 10,\n primaryAxisAlignItems = \"MIN\",\n counterAxisAlignItems = \"MIN\",\n layoutSizingHorizontal = \"FIXED\",\n layoutSizingVertical = \"FIXED\",\n itemSpacing = 0,\n } = params || {};\n\n const frame = figma.createFrame();\n frame.x = x;\n frame.y = y;\n frame.resize(width, height);\n frame.name = name;\n\n // Set layout mode if provided\n if (layoutMode !== \"NONE\") {\n frame.layoutMode = layoutMode;\n frame.layoutWrap = layoutWrap;\n\n // Set padding values only when layoutMode is not NONE\n frame.paddingTop = paddingTop;\n frame.paddingRight = paddingRight;\n frame.paddingBottom = paddingBottom;\n frame.paddingLeft = paddingLeft;\n\n // Set axis alignment only when layoutMode is not NONE\n frame.primaryAxisAlignItems = primaryAxisAlignItems;\n frame.counterAxisAlignItems = counterAxisAlignItems;\n\n // Set layout sizing only when layoutMode is not NONE\n frame.layoutSizingHorizontal = layoutSizingHorizontal;\n frame.layoutSizingVertical = layoutSizingVertical;\n\n // Set item spacing only when layoutMode is not NONE\n frame.itemSpacing = itemSpacing;\n }\n\n // Set fill color if provided\n if (fillColor) {\n const paintStyle = {\n type: \"SOLID\",\n color: {\n r: parseFloat(fillColor.r) || 0,\n g: parseFloat(fillColor.g) || 0,\n b: parseFloat(fillColor.b) || 0,\n },\n opacity: parseFloat(fillColor.a) || 1,\n };\n frame.fills = [paintStyle];\n }\n\n // Set stroke color and weight if provided\n if (strokeColor) {\n const strokeStyle = {\n type: \"SOLID\",\n color: {\n r: parseFloat(strokeColor.r) || 0,\n g: parseFloat(strokeColor.g) || 0,\n b: parseFloat(strokeColor.b) || 0,\n },\n opacity: parseFloat(strokeColor.a) || 1,\n };\n frame.strokes = [strokeStyle];\n }\n\n // Set stroke weight if provided\n if (strokeWeight !== undefined) {\n frame.strokeWeight = strokeWeight;\n }\n\n // If parentId is provided, append to that node, otherwise append to current page\n if (parentId) {\n const parentNode = await figma.getNodeByIdAsync(parentId);\n if (!parentNode) {\n throw new Error(`Parent node not found with ID: ${parentId}`);\n }\n if (!(\"appendChild\" in parentNode)) {\n throw new Error(`Parent node does not support children: ${parentId}`);\n }\n parentNode.appendChild(frame);\n } else {\n figma.currentPage.appendChild(frame);\n }\n\n return {\n id: frame.id,\n name: frame.name,\n x: frame.x,\n y: frame.y,\n width: frame.width,\n height: frame.height,\n fills: frame.fills,\n strokes: frame.strokes,\n strokeWeight: frame.strokeWeight,\n layoutMode: frame.layoutMode,\n layoutWrap: frame.layoutWrap,\n parentId: frame.parent ? frame.parent.id : undefined,\n };\n}\n\nasync function createText(params) {\n const {\n x = 0,\n y = 0,\n text = \"Text\",\n fontSize = 14,\n fontWeight = 400,\n fontColor = { r: 0, g: 0, b: 0, a: 1 }, // Default to black\n name = \"\",\n parentId,\n } = params || {};\n\n // Map common font weights to Figma font styles\n const getFontStyle = (weight) => {\n switch (weight) {\n case 100:\n return \"Thin\";\n case 200:\n return \"Extra Light\";\n case 300:\n return \"Light\";\n case 400:\n return \"Regular\";\n case 500:\n return \"Medium\";\n case 600:\n return \"Semi Bold\";\n case 700:\n return \"Bold\";\n case 800:\n return \"Extra Bold\";\n case 900:\n return \"Black\";\n default:\n return \"Regular\";\n }\n };\n\n const textNode = figma.createText();\n textNode.x = x;\n textNode.y = y;\n textNode.name = name || text;\n try {\n await figma.loadFontAsync({\n family: \"Inter\",\n style: getFontStyle(fontWeight),\n });\n textNode.fontName = { family: \"Inter\", style: getFontStyle(fontWeight) };\n textNode.fontSize = parseInt(fontSize);\n } catch (error) {\n console.error(\"Error setting font size\", error);\n }\n setCharacters(textNode, text);\n\n // Set text color\n const paintStyle = {\n type: \"SOLID\",\n color: {\n r: parseFloat(fontColor.r) || 0,\n g: parseFloat(fontColor.g) || 0,\n b: parseFloat(fontColor.b) || 0,\n },\n opacity: parseFloat(fontColor.a) || 1,\n };\n textNode.fills = [paintStyle];\n\n // If parentId is provided, append to that node, otherwise append to current page\n if (parentId) {\n const parentNode = await figma.getNodeByIdAsync(parentId);\n if (!parentNode) {\n throw new Error(`Parent node not found with ID: ${parentId}`);\n }\n if (!(\"appendChild\" in parentNode)) {\n throw new Error(`Parent node does not support children: ${parentId}`);\n }\n parentNode.appendChild(textNode);\n } else {\n figma.currentPage.appendChild(textNode);\n }\n\n return {\n id: textNode.id,\n name: textNode.name,\n x: textNode.x,\n y: textNode.y,\n width: textNode.width,\n height: textNode.height,\n characters: textNode.characters,\n fontSize: textNode.fontSize,\n fontWeight: fontWeight,\n fontColor: fontColor,\n fontName: textNode.fontName,\n fills: textNode.fills,\n parentId: textNode.parent ? textNode.parent.id : undefined,\n };\n}\n\nasync function setFillColor(params) {\n console.log(\"setFillColor\", params);\n const {\n nodeId,\n color: { r, g, b, a },\n } = params || {};\n\n if (!nodeId) {\n throw new Error(\"Missing nodeId parameter\");\n }\n\n const node = await figma.getNodeByIdAsync(nodeId);\n if (!node) {\n throw new Error(`Node not found with ID: ${nodeId}`);\n }\n\n if (!(\"fills\" in node)) {\n throw new Error(`Node does not support fills: ${nodeId}`);\n }\n\n // Create RGBA color\n const rgbColor = {\n r: parseFloat(r) || 0,\n g: parseFloat(g) || 0,\n b: parseFloat(b) || 0,\n a: parseFloat(a) || 1,\n };\n\n // Set fill\n const paintStyle = {\n type: \"SOLID\",\n color: {\n r: parseFloat(rgbColor.r),\n g: parseFloat(rgbColor.g),\n b: parseFloat(rgbColor.b),\n },\n opacity: parseFloat(rgbColor.a),\n };\n\n console.log(\"paintStyle\", paintStyle);\n\n node.fills = [paintStyle];\n\n return {\n id: node.id,\n name: node.name,\n fills: [paintStyle],\n };\n}\n\nasync function setStrokeColor(params) {\n const {\n nodeId,\n color: { r, g, b, a },\n weight = 1,\n } = params || {};\n\n if (!nodeId) {\n throw new Error(\"Missing nodeId parameter\");\n }\n\n const node = await figma.getNodeByIdAsync(nodeId);\n if (!node) {\n throw new Error(`Node not found with ID: ${nodeId}`);\n }\n\n if (!(\"strokes\" in node)) {\n throw new Error(`Node does not support strokes: ${nodeId}`);\n }\n\n // Create RGBA color\n const rgbColor = {\n r: r !== undefined ? r : 0,\n g: g !== undefined ? g : 0,\n b: b !== undefined ? b : 0,\n a: a !== undefined ? a : 1,\n };\n\n // Set stroke\n const paintStyle = {\n type: \"SOLID\",\n color: {\n r: rgbColor.r,\n g: rgbColor.g,\n b: rgbColor.b,\n },\n opacity: rgbColor.a,\n };\n\n node.strokes = [paintStyle];\n\n // Set stroke weight if available\n if (\"strokeWeight\" in node) {\n node.strokeWeight = weight;\n }\n\n return {\n id: node.id,\n name: node.name,\n strokes: node.strokes,\n strokeWeight: \"strokeWeight\" in node ? node.strokeWeight : undefined,\n };\n}\n\nasync function moveNode(params) {\n const { nodeId, x, y } = params || {};\n\n if (!nodeId) {\n throw new Error(\"Missing nodeId parameter\");\n }\n\n if (x === undefined || y === undefined) {\n throw new Error(\"Missing x or y parameters\");\n }\n\n const node = await figma.getNodeByIdAsync(nodeId);\n if (!node) {\n throw new Error(`Node not found with ID: ${nodeId}`);\n }\n\n if (!(\"x\" in node) || !(\"y\" in node)) {\n throw new Error(`Node does not support position: ${nodeId}`);\n }\n\n node.x = x;\n node.y = y;\n\n return {\n id: node.id,\n name: node.name,\n x: node.x,\n y: node.y,\n };\n}\n\nasync function resizeNode(params) {\n const { nodeId, width, height } = params || {};\n\n if (!nodeId) {\n throw new Error(\"Missing nodeId parameter\");\n }\n\n if (width === undefined || height === undefined) {\n throw new Error(\"Missing width or height parameters\");\n }\n\n const node = await figma.getNodeByIdAsync(nodeId);\n if (!node) {\n throw new Error(`Node not found with ID: ${nodeId}`);\n }\n\n if (!(\"resize\" in node)) {\n throw new Error(`Node does not support resizing: ${nodeId}`);\n }\n\n node.resize(width, height);\n\n return {\n id: node.id,\n name: node.name,\n width: node.width,\n height: node.height,\n };\n}\n\nasync function deleteNode(params) {\n const { nodeId } = params || {};\n\n if (!nodeId) {\n throw new Error(\"Missing nodeId parameter\");\n }\n\n const node = await figma.getNodeByIdAsync(nodeId);\n if (!node) {\n throw new Error(`Node not found with ID: ${nodeId}`);\n }\n\n // Save node info before deleting\n const nodeInfo = {\n id: node.id,\n name: node.name,\n type: node.type,\n };\n\n node.remove();\n\n return nodeInfo;\n}\n\nasync function getStyles() {\n const styles = {\n colors: await figma.getLocalPaintStylesAsync(),\n texts: await figma.getLocalTextStylesAsync(),\n effects: await figma.getLocalEffectStylesAsync(),\n grids: await figma.getLocalGridStylesAsync(),\n };\n\n return {\n colors: styles.colors.map((style) => ({\n id: style.id,\n name: style.name,\n key: style.key,\n paint: style.paints[0],\n })),\n texts: styles.texts.map((style) => ({\n id: style.id,\n name: style.name,\n key: style.key,\n fontSize: style.fontSize,\n fontName: style.fontName,\n })),\n effects: styles.effects.map((style) => ({\n id: style.id,\n name: style.name,\n key: style.key,\n })),\n grids: styles.grids.map((style) => ({\n id: style.id,\n name: style.name,\n key: style.key,\n })),\n };\n}\n\nasync function getLocalComponents() {\n await figma.loadAllPagesAsync();\n\n const components = figma.root.findAllWithCriteria({\n types: [\"COMPONENT\"],\n });\n\n return {\n count: components.length,\n components: components.map((component) => ({\n id: component.id,\n name: component.name,\n key: \"key\" in component ? component.key : null,\n })),\n };\n}\n\n// async function getTeamComponents() {\n// try {\n// const teamComponents =\n// await figma.teamLibrary.getAvailableComponentsAsync();\n\n// return {\n// count: teamComponents.length,\n// components: teamComponents.map((component) => ({\n// key: component.key,\n// name: component.name,\n// description: component.description,\n// libraryName: component.libraryName,\n// })),\n// };\n// } catch (error) {\n// throw new Error(`Error getting team components: ${error.message}`);\n// }\n// }\n\nasync function createComponentInstance(params) {\n const { componentKey, x = 0, y = 0 } = params || {};\n\n if (!componentKey) {\n throw new Error(\"Missing componentKey parameter\");\n }\n\n try {\n const component = await figma.importComponentByKeyAsync(componentKey);\n const instance = component.createInstance();\n\n instance.x = x;\n instance.y = y;\n\n figma.currentPage.appendChild(instance);\n\n return {\n id: instance.id,\n name: instance.name,\n x: instance.x,\n y: instance.y,\n width: instance.width,\n height: instance.height,\n componentId: instance.componentId,\n };\n } catch (error) {\n throw new Error(`Error creating component instance: ${error.message}`);\n }\n}\n\nasync function exportNodeAsImage(params) {\n const { nodeId, scale = 1 } = params || {};\n\n const format = \"PNG\";\n\n if (!nodeId) {\n throw new Error(\"Missing nodeId parameter\");\n }\n\n const node = await figma.getNodeByIdAsync(nodeId);\n if (!node) {\n throw new Error(`Node not found with ID: ${nodeId}`);\n }\n\n if (!(\"exportAsync\" in node)) {\n throw new Error(`Node does not support exporting: ${nodeId}`);\n }\n\n try {\n const settings = {\n format: format,\n constraint: { type: \"SCALE\", value: scale },\n };\n\n const bytes = await node.exportAsync(settings);\n\n let mimeType;\n switch (format) {\n case \"PNG\":\n mimeType = \"image/png\";\n break;\n case \"JPG\":\n mimeType = \"image/jpeg\";\n break;\n case \"SVG\":\n mimeType = \"image/svg+xml\";\n break;\n case \"PDF\":\n mimeType = \"application/pdf\";\n break;\n default:\n mimeType = \"application/octet-stream\";\n }\n\n // Proper way to convert Uint8Array to base64\n const base64 = customBase64Encode(bytes);\n // const imageData = `data:${mimeType};base64,${base64}`;\n\n return {\n nodeId,\n format,\n scale,\n mimeType,\n imageData: base64,\n };\n } catch (error) {\n throw new Error(`Error exporting node as image: ${error.message}`);\n }\n}\nfunction customBase64Encode(bytes) {\n const chars =\n \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n let base64 = \"\";\n\n const byteLength = bytes.byteLength;\n const byteRemainder = byteLength % 3;\n const mainLength = byteLength - byteRemainder;\n\n let a, b, c, d;\n let chunk;\n\n // Main loop deals with bytes in chunks of 3\n for (let i = 0; i < mainLength; i = i + 3) {\n // Combine the three bytes into a single integer\n chunk = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2];\n\n // Use bitmasks to extract 6-bit segments from the triplet\n a = (chunk & 16515072) >> 18; // 16515072 = (2^6 - 1) << 18\n b = (chunk & 258048) >> 12; // 258048 = (2^6 - 1) << 12\n c = (chunk & 4032) >> 6; // 4032 = (2^6 - 1) << 6\n d = chunk & 63; // 63 = 2^6 - 1\n\n // Convert the raw binary segments to the appropriate ASCII encoding\n base64 += chars[a] + chars[b] + chars[c] + chars[d];\n }\n\n // Deal with the remaining bytes and padding\n if (byteRemainder === 1) {\n chunk = bytes[mainLength];\n\n a = (chunk & 252) >> 2; // 252 = (2^6 - 1) << 2\n\n // Set the 4 least significant bits to zero\n b = (chunk & 3) << 4; // 3 = 2^2 - 1\n\n base64 += chars[a] + chars[b] + \"==\";\n } else if (byteRemainder === 2) {\n chunk = (bytes[mainLength] << 8) | bytes[mainLength + 1];\n\n a = (chunk & 64512) >> 10; // 64512 = (2^6 - 1) << 10\n b = (chunk & 1008) >> 4; // 1008 = (2^6 - 1) << 4\n\n // Set the 2 least significant bits to zero\n c = (chunk & 15) << 2; // 15 = 2^4 - 1\n\n base64 += chars[a] + chars[b] + chars[c] + \"=\";\n }\n\n return base64;\n}\n\nasync function setCornerRadius(params) {\n const { nodeId, radius, corners } = params || {};\n\n if (!nodeId) {\n throw new Error(\"Missing nodeId parameter\");\n }\n\n if (radius === undefined) {\n throw new Error(\"Missing radius parameter\");\n }\n\n const node = await figma.getNodeByIdAsync(nodeId);\n if (!node) {\n throw new Error(`Node not found with ID: ${nodeId}`);\n }\n\n // Check if node supports corner radius\n if (!(\"cornerRadius\" in node)) {\n throw new Error(`Node does not support corner radius: ${nodeId}`);\n }\n\n // If corners array is provided, set individual corner radii\n if (corners && Array.isArray(corners) && corners.length === 4) {\n if (\"topLeftRadius\" in node) {\n // Node supports individual corner radii\n if (corners[0]) node.topLeftRadius = radius;\n if (corners[1]) node.topRightRadius = radius;\n if (corners[2]) node.bottomRightRadius = radius;\n if (corners[3]) node.bottomLeftRadius = radius;\n } else {\n // Node only supports uniform corner radius\n node.cornerRadius = radius;\n }\n } else {\n // Set uniform corner radius\n node.cornerRadius = radius;\n }\n\n return {\n id: node.id,\n name: node.name,\n cornerRadius: \"cornerRadius\" in node ? node.cornerRadius : undefined,\n topLeftRadius: \"topLeftRadius\" in node ? node.topLeftRadius : undefined,\n topRightRadius: \"topRightRadius\" in node ? node.topRightRadius : undefined,\n bottomRightRadius:\n \"bottomRightRadius\" in node ? node.bottomRightRadius : undefined,\n bottomLeftRadius:\n \"bottomLeftRadius\" in node ? node.bottomLeftRadius : undefined,\n };\n}\n\nasync function setTextContent(params) {\n const { nodeId, text } = params || {};\n\n if (!nodeId) {\n throw new Error(\"Missing nodeId parameter\");\n }\n\n if (text === undefined) {\n throw new Error(\"Missing text parameter\");\n }\n\n const node = await figma.getNodeByIdAsync(nodeId);\n if (!node) {\n throw new Error(`Node not found with ID: ${nodeId}`);\n }\n\n if (node.type !== \"TEXT\") {\n throw new Error(`Node is not a text node: ${nodeId}`);\n }\n\n try {\n await figma.loadFontAsync(node.fontName);\n\n await setCharacters(node, text);\n\n return {\n id: node.id,\n name: node.name,\n characters: node.characters,\n fontName: node.fontName,\n };\n } catch (error) {\n throw new Error(`Error setting text content: ${error.message}`);\n }\n}\n\n// Initialize settings on load\n(async function initializePlugin() {\n try {\n const savedSettings = await figma.clientStorage.getAsync(\"settings\");\n if (savedSettings) {\n if (savedSettings.serverPort) {\n state.serverPort = savedSettings.serverPort;\n }\n }\n\n // Send initial settings to UI\n figma.ui.postMessage({\n type: \"init-settings\",\n settings: {\n serverPort: state.serverPort,\n },\n });\n } catch (error) {\n console.error(\"Error loading settings:\", error);\n }\n})();\n\nfunction uniqBy(arr, predicate) {\n const cb = typeof predicate === \"function\" ? predicate : (o) => o[predicate];\n return [\n ...arr\n .reduce((map, item) => {\n const key = item === null || item === undefined ? item : cb(item);\n\n map.has(key) || map.set(key, item);\n\n return map;\n }, new Map())\n .values(),\n ];\n}\nconst setCharacters = async (node, characters, options) => {\n const fallbackFont = (options && options.fallbackFont) || {\n family: \"Inter\",\n style: \"Regular\",\n };\n try {\n if (node.fontName === figma.mixed) {\n if (options && options.smartStrategy === \"prevail\") {\n const fontHashTree = {};\n for (let i = 1; i < node.characters.length; i++) {\n const charFont = node.getRangeFontName(i - 1, i);\n const key = `${charFont.family}::${charFont.style}`;\n fontHashTree[key] = fontHashTree[key] ? fontHashTree[key] + 1 : 1;\n }\n const prevailedTreeItem = Object.entries(fontHashTree).sort(\n (a, b) => b[1] - a[1]\n )[0];\n const [family, style] = prevailedTreeItem[0].split(\"::\");\n const prevailedFont = {\n family,\n style,\n };\n await figma.loadFontAsync(prevailedFont);\n node.fontName = prevailedFont;\n } else if (options && options.smartStrategy === \"strict\") {\n return setCharactersWithStrictMatchFont(node, characters, fallbackFont);\n } else if (options && options.smartStrategy === \"experimental\") {\n return setCharactersWithSmartMatchFont(node, characters, fallbackFont);\n } else {\n const firstCharFont = node.getRangeFontName(0, 1);\n await figma.loadFontAsync(firstCharFont);\n node.fontName = firstCharFont;\n }\n } else {\n await figma.loadFontAsync({\n family: node.fontName.family,\n style: node.fontName.style,\n });\n }\n } catch (err) {\n console.warn(\n `Failed to load \"${node.fontName[\"family\"]} ${node.fontName[\"style\"]}\" font and replaced with fallback \"${fallbackFont.family} ${fallbackFont.style}\"`,\n err\n );\n await figma.loadFontAsync(fallbackFont);\n node.fontName = fallbackFont;\n }\n try {\n node.characters = characters;\n return true;\n } catch (err) {\n console.warn(`Failed to set characters. Skipped.`, err);\n return false;\n }\n};\n\nconst setCharactersWithStrictMatchFont = async (\n node,\n characters,\n fallbackFont\n) => {\n const fontHashTree = {};\n for (let i = 1; i < node.characters.length; i++) {\n const startIdx = i - 1;\n const startCharFont = node.getRangeFontName(startIdx, i);\n const startCharFontVal = `${startCharFont.family}::${startCharFont.style}`;\n while (i < node.characters.length) {\n i++;\n const charFont = node.getRangeFontName(i - 1, i);\n if (startCharFontVal !== `${charFont.family}::${charFont.style}`) {\n break;\n }\n }\n fontHashTree[`${startIdx}_${i}`] = startCharFontVal;\n }\n await figma.loadFontAsync(fallbackFont);\n node.fontName = fallbackFont;\n node.characters = characters;\n console.log(fontHashTree);\n await Promise.all(\n Object.keys(fontHashTree).map(async (range) => {\n console.log(range, fontHashTree[range]);\n const [start, end] = range.split(\"_\");\n const [family, style] = fontHashTree[range].split(\"::\");\n const matchedFont = {\n family,\n style,\n };\n await figma.loadFontAsync(matchedFont);\n return node.setRangeFontName(Number(start), Number(end), matchedFont);\n })\n );\n return true;\n};\n\nconst getDelimiterPos = (str, delimiter, startIdx = 0, endIdx = str.length) => {\n const indices = [];\n let temp = startIdx;\n for (let i = startIdx; i < endIdx; i++) {\n if (\n str[i] === delimiter &&\n i + startIdx !== endIdx &&\n temp !== i + startIdx\n ) {\n indices.push([temp, i + startIdx]);\n temp = i + startIdx + 1;\n }\n }\n temp !== endIdx && indices.push([temp, endIdx]);\n return indices.filter(Boolean);\n};\n\nconst buildLinearOrder = (node) => {\n const fontTree = [];\n const newLinesPos = getDelimiterPos(node.characters, \"\\n\");\n newLinesPos.forEach(([newLinesRangeStart, newLinesRangeEnd], n) => {\n const newLinesRangeFont = node.getRangeFontName(\n newLinesRangeStart,\n newLinesRangeEnd\n );\n if (newLinesRangeFont === figma.mixed) {\n const spacesPos = getDelimiterPos(\n node.characters,\n \" \",\n newLinesRangeStart,\n newLinesRangeEnd\n );\n spacesPos.forEach(([spacesRangeStart, spacesRangeEnd], s) => {\n const spacesRangeFont = node.getRangeFontName(\n spacesRangeStart,\n spacesRangeEnd\n );\n if (spacesRangeFont === figma.mixed) {\n const spacesRangeFont = node.getRangeFontName(\n spacesRangeStart,\n spacesRangeStart[0]\n );\n fontTree.push({\n start: spacesRangeStart,\n delimiter: \" \",\n family: spacesRangeFont.family,\n style: spacesRangeFont.style,\n });\n } else {\n fontTree.push({\n start: spacesRangeStart,\n delimiter: \" \",\n family: spacesRangeFont.family,\n style: spacesRangeFont.style,\n });\n }\n });\n } else {\n fontTree.push({\n start: newLinesRangeStart,\n delimiter: \"\\n\",\n family: newLinesRangeFont.family,\n style: newLinesRangeFont.style,\n });\n }\n });\n return fontTree\n .sort((a, b) => +a.start - +b.start)\n .map(({ family, style, delimiter }) => ({ family, style, delimiter }));\n};\n\nconst setCharactersWithSmartMatchFont = async (\n node,\n characters,\n fallbackFont\n) => {\n const rangeTree = buildLinearOrder(node);\n const fontsToLoad = uniqBy(\n rangeTree,\n ({ family, style }) => `${family}::${style}`\n ).map(({ family, style }) => ({\n family,\n style,\n }));\n\n await Promise.all([...fontsToLoad, fallbackFont].map(figma.loadFontAsync));\n\n node.fontName = fallbackFont;\n node.characters = characters;\n\n let prevPos = 0;\n rangeTree.forEach(({ family, style, delimiter }) => {\n if (prevPos < node.characters.length) {\n const delimeterPos = node.characters.indexOf(delimiter, prevPos);\n const endPos =\n delimeterPos > prevPos ? delimeterPos : node.characters.length;\n const matchedFont = {\n family,\n style,\n };\n node.setRangeFontName(prevPos, endPos, matchedFont);\n prevPos = endPos + 1;\n }\n });\n return true;\n};\n\n// Add the cloneNode function implementation\nasync function cloneNode(params) {\n const { nodeId, x, y } = params || {};\n\n if (!nodeId) {\n throw new Error(\"Missing nodeId parameter\");\n }\n\n const node = await figma.getNodeByIdAsync(nodeId);\n if (!node) {\n throw new Error(`Node not found with ID: ${nodeId}`);\n }\n\n // Clone the node\n const clone = node.clone();\n\n // If x and y are provided, move the clone to that position\n if (x !== undefined && y !== undefined) {\n if (!(\"x\" in clone) || !(\"y\" in clone)) {\n throw new Error(`Cloned node does not support position: ${nodeId}`);\n }\n clone.x = x;\n clone.y = y;\n }\n\n // Add the clone to the same parent as the original node\n if (node.parent) {\n node.parent.appendChild(clone);\n } else {\n figma.currentPage.appendChild(clone);\n }\n\n return {\n id: clone.id,\n name: clone.name,\n x: \"x\" in clone ? clone.x : undefined,\n y: \"y\" in clone ? clone.y : undefined,\n width: \"width\" in clone ? clone.width : undefined,\n height: \"height\" in clone ? clone.height : undefined,\n };\n}\n\nasync function scanTextNodes(params) {\n console.log(`Starting to scan text nodes from node ID: ${params.nodeId}`);\n const {\n nodeId,\n useChunking = true,\n chunkSize = 10,\n commandId = generateCommandId(),\n } = params || {};\n\n const node = await figma.getNodeByIdAsync(nodeId);\n\n if (!node) {\n console.error(`Node with ID ${nodeId} not found`);\n // Send error progress update\n sendProgressUpdate(\n commandId,\n \"scan_text_nodes\",\n \"error\",\n 0,\n 0,\n 0,\n `Node with ID ${nodeId} not found`,\n { error: `Node not found: ${nodeId}` }\n );\n throw new Error(`Node with ID ${nodeId} not found`);\n }\n\n // If chunking is not enabled, use the original implementation\n if (!useChunking) {\n const textNodes = [];\n try {\n // Send started progress update\n sendProgressUpdate(\n commandId,\n \"scan_text_nodes\",\n \"started\",\n 0,\n 1, // Not known yet how many nodes there are\n 0,\n `Starting scan of node \"${node.name || nodeId}\" without chunking`,\n null\n );\n\n await findTextNodes(node, [], 0, textNodes);\n\n // Send completed progress update\n sendProgressUpdate(\n commandId,\n \"scan_text_nodes\",\n \"completed\",\n 100,\n textNodes.length,\n textNodes.length,\n `Scan complete. Found ${textNodes.length} text nodes.`,\n { textNodes }\n );\n\n return {\n success: true,\n message: `Scanned ${textNodes.length} text nodes.`,\n count: textNodes.length,\n textNodes: textNodes,\n commandId,\n };\n } catch (error) {\n console.error(\"Error scanning text nodes:\", error);\n\n // Send error progress update\n sendProgressUpdate(\n commandId,\n \"scan_text_nodes\",\n \"error\",\n 0,\n 0,\n 0,\n `Error scanning text nodes: ${error.message}`,\n { error: error.message }\n );\n\n throw new Error(`Error scanning text nodes: ${error.message}`);\n }\n }\n\n // Chunked implementation\n console.log(`Using chunked scanning with chunk size: ${chunkSize}`);\n\n // First, collect all nodes to process (without processing them yet)\n const nodesToProcess = [];\n\n // Send started progress update\n sendProgressUpdate(\n commandId,\n \"scan_text_nodes\",\n \"started\",\n 0,\n 0, // Not known yet how many nodes there are\n 0,\n `Starting chunked scan of node \"${node.name || nodeId}\"`,\n { chunkSize }\n );\n\n await collectNodesToProcess(node, [], 0, nodesToProcess);\n\n const totalNodes = nodesToProcess.length;\n console.log(`Found ${totalNodes} total nodes to process`);\n\n // Calculate number of chunks needed\n const totalChunks = Math.ceil(totalNodes / chunkSize);\n console.log(`Will process in ${totalChunks} chunks`);\n\n // Send update after node collection\n sendProgressUpdate(\n commandId,\n \"scan_text_nodes\",\n \"in_progress\",\n 5, // 5% progress for collection phase\n totalNodes,\n 0,\n `Found ${totalNodes} nodes to scan. Will process in ${totalChunks} chunks.`,\n {\n totalNodes,\n totalChunks,\n chunkSize,\n }\n );\n\n // Process nodes in chunks\n const allTextNodes = [];\n let processedNodes = 0;\n let chunksProcessed = 0;\n\n for (let i = 0; i < totalNodes; i += chunkSize) {\n const chunkEnd = Math.min(i + chunkSize, totalNodes);\n console.log(\n `Processing chunk ${chunksProcessed + 1}/${totalChunks} (nodes ${i} to ${chunkEnd - 1\n })`\n );\n\n // Send update before processing chunk\n sendProgressUpdate(\n commandId,\n \"scan_text_nodes\",\n \"in_progress\",\n Math.round(5 + (chunksProcessed / totalChunks) * 90), // 5-95% for processing\n totalNodes,\n processedNodes,\n `Processing chunk ${chunksProcessed + 1}/${totalChunks}`,\n {\n currentChunk: chunksProcessed + 1,\n totalChunks,\n textNodesFound: allTextNodes.length,\n }\n );\n\n const chunkNodes = nodesToProcess.slice(i, chunkEnd);\n const chunkTextNodes = [];\n\n // Process each node in this chunk\n for (const nodeInfo of chunkNodes) {\n if (nodeInfo.node.type === \"TEXT\") {\n try {\n const textNodeInfo = await processTextNode(\n nodeInfo.node,\n nodeInfo.parentPath,\n nodeInfo.depth\n );\n if (textNodeInfo) {\n chunkTextNodes.push(textNodeInfo);\n }\n } catch (error) {\n console.error(`Error processing text node: ${error.message}`);\n // Continue with other nodes\n }\n }\n\n // Brief delay to allow UI updates and prevent freezing\n await delay(5);\n }\n\n // Add results from this chunk\n allTextNodes.push(...chunkTextNodes);\n processedNodes += chunkNodes.length;\n chunksProcessed++;\n\n // Send update after processing chunk\n sendProgressUpdate(\n commandId,\n \"scan_text_nodes\",\n \"in_progress\",\n Math.round(5 + (chunksProcessed / totalChunks) * 90), // 5-95% for processing\n totalNodes,\n processedNodes,\n `Processed chunk ${chunksProcessed}/${totalChunks}. Found ${allTextNodes.length} text nodes so far.`,\n {\n currentChunk: chunksProcessed,\n totalChunks,\n processedNodes,\n textNodesFound: allTextNodes.length,\n chunkResult: chunkTextNodes,\n }\n );\n\n // Small delay between chunks to prevent UI freezing\n if (i + chunkSize < totalNodes) {\n await delay(50);\n }\n }\n\n // Send completed progress update\n sendProgressUpdate(\n commandId,\n \"scan_text_nodes\",\n \"completed\",\n 100,\n totalNodes,\n processedNodes,\n `Scan complete. Found ${allTextNodes.length} text nodes.`,\n {\n textNodes: allTextNodes,\n processedNodes,\n chunks: chunksProcessed,\n }\n );\n\n return {\n success: true,\n message: `Chunked scan complete. Found ${allTextNodes.length} text nodes.`,\n totalNodes: allTextNodes.length,\n processedNodes: processedNodes,\n chunks: chunksProcessed,\n textNodes: allTextNodes,\n commandId,\n };\n}\n\n// Helper function to collect all nodes that need to be processed\nasync function collectNodesToProcess(\n node,\n parentPath = [],\n depth = 0,\n nodesToProcess = []\n) {\n // Skip invisible nodes\n if (node.visible === false) return;\n\n // Get the path to this node\n const nodePath = [...parentPath, node.name || `Unnamed ${node.type}`];\n\n // Add this node to the processing list\n nodesToProcess.push({\n node: node,\n parentPath: nodePath,\n depth: depth,\n });\n\n // Recursively add children\n if (\"children\" in node) {\n for (const child of node.children) {\n await collectNodesToProcess(child, nodePath, depth + 1, nodesToProcess);\n }\n }\n}\n\n// Process a single text node\nasync function processTextNode(node, parentPath, depth) {\n if (node.type !== \"TEXT\") return null;\n\n try {\n // Safely extract font information\n let fontFamily = \"\";\n let fontStyle = \"\";\n\n if (node.fontName) {\n if (typeof node.fontName === \"object\") {\n if (\"family\" in node.fontName) fontFamily = node.fontName.family;\n if (\"style\" in node.fontName) fontStyle = node.fontName.style;\n }\n }\n\n // Create a safe representation of the text node\n const safeTextNode = {\n id: node.id,\n name: node.name || \"Text\",\n type: node.type,\n characters: node.characters,\n fontSize: typeof node.fontSize === \"number\" ? node.fontSize : 0,\n fontFamily: fontFamily,\n fontStyle: fontStyle,\n x: typeof node.x === \"number\" ? node.x : 0,\n y: typeof node.y === \"number\" ? node.y : 0,\n width: typeof node.width === \"number\" ? node.width : 0,\n height: typeof node.height === \"number\" ? node.height : 0,\n path: parentPath.join(\" > \"),\n depth: depth,\n };\n\n // Highlight the node briefly (optional visual feedback)\n try {\n const originalFills = JSON.parse(JSON.stringify(node.fills));\n node.fills = [\n {\n type: \"SOLID\",\n color: { r: 1, g: 0.5, b: 0 },\n opacity: 0.3,\n },\n ];\n\n // Brief delay for the highlight to be visible\n await delay(100);\n\n try {\n node.fills = originalFills;\n } catch (err) {\n console.error(\"Error resetting fills:\", err);\n }\n } catch (highlightErr) {\n console.error(\"Error highlighting text node:\", highlightErr);\n // Continue anyway, highlighting is just visual feedback\n }\n\n return safeTextNode;\n } catch (nodeErr) {\n console.error(\"Error processing text node:\", nodeErr);\n return null;\n }\n}\n\n// A delay function that returns a promise\nfunction delay(ms) {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n// Keep the original findTextNodes for backward compatibility\nasync function findTextNodes(node, parentPath = [], depth = 0, textNodes = []) {\n // Skip invisible nodes\n if (node.visible === false) return;\n\n // Get the path to this node including its name\n const nodePath = [...parentPath, node.name || `Unnamed ${node.type}`];\n\n if (node.type === \"TEXT\") {\n try {\n // Safely extract font information to avoid Symbol serialization issues\n let fontFamily = \"\";\n let fontStyle = \"\";\n\n if (node.fontName) {\n if (typeof node.fontName === \"object\") {\n if (\"family\" in node.fontName) fontFamily = node.fontName.family;\n if (\"style\" in node.fontName) fontStyle = node.fontName.style;\n }\n }\n\n // Create a safe representation of the text node with only serializable properties\n const safeTextNode = {\n id: node.id,\n name: node.name || \"Text\",\n type: node.type,\n characters: node.characters,\n fontSize: typeof node.fontSize === \"number\" ? node.fontSize : 0,\n fontFamily: fontFamily,\n fontStyle: fontStyle,\n x: typeof node.x === \"number\" ? node.x : 0,\n y: typeof node.y === \"number\" ? node.y : 0,\n width: typeof node.width === \"number\" ? node.width : 0,\n height: typeof node.height === \"number\" ? node.height : 0,\n path: nodePath.join(\" > \"),\n depth: depth,\n };\n\n // Only highlight the node if it's not being done via API\n try {\n // Safe way to create a temporary highlight without causing serialization issues\n const originalFills = JSON.parse(JSON.stringify(node.fills));\n node.fills = [\n {\n type: \"SOLID\",\n color: { r: 1, g: 0.5, b: 0 },\n opacity: 0.3,\n },\n ];\n\n // Promise-based delay instead of setTimeout\n await delay(500);\n\n try {\n node.fills = originalFills;\n } catch (err) {\n console.error(\"Error resetting fills:\", err);\n }\n } catch (highlightErr) {\n console.error(\"Error highlighting text node:\", highlightErr);\n // Continue anyway, highlighting is just visual feedback\n }\n\n textNodes.push(safeTextNode);\n } catch (nodeErr) {\n console.error(\"Error processing text node:\", nodeErr);\n // Skip this node but continue with others\n }\n }\n\n // Recursively process children of container nodes\n if (\"children\" in node) {\n for (const child of node.children) {\n await findTextNodes(child, nodePath, depth + 1, textNodes);\n }\n }\n}\n\n// Replace text in a specific node\nasync function setMultipleTextContents(params) {\n const { nodeId, text } = params || {};\n const commandId = params.commandId || generateCommandId();\n\n if (!nodeId || !text || !Array.isArray(text)) {\n const errorMsg = \"Missing required parameters: nodeId and text array\";\n\n // Send error progress update\n sendProgressUpdate(\n commandId,\n \"set_multiple_text_contents\",\n \"error\",\n 0,\n 0,\n 0,\n errorMsg,\n { error: errorMsg }\n );\n\n throw new Error(errorMsg);\n }\n\n console.log(\n `Starting text replacement for node: ${nodeId} with ${text.length} text replacements`\n );\n\n // Send started progress update\n sendProgressUpdate(\n commandId,\n \"set_multiple_text_contents\",\n \"started\",\n 0,\n text.length,\n 0,\n `Starting text replacement for ${text.length} nodes`,\n { totalReplacements: text.length }\n );\n\n // Define the results array and counters\n const results = [];\n let successCount = 0;\n let failureCount = 0;\n\n // Split text replacements into chunks of 5\n const CHUNK_SIZE = 5;\n const chunks = [];\n\n for (let i = 0; i < text.length; i += CHUNK_SIZE) {\n chunks.push(text.slice(i, i + CHUNK_SIZE));\n }\n\n console.log(`Split ${text.length} replacements into ${chunks.length} chunks`);\n\n // Send chunking info update\n sendProgressUpdate(\n commandId,\n \"set_multiple_text_contents\",\n \"in_progress\",\n 5, // 5% progress for planning phase\n text.length,\n 0,\n `Preparing to replace text in ${text.length} nodes using ${chunks.length} chunks`,\n {\n totalReplacements: text.length,\n chunks: chunks.length,\n chunkSize: CHUNK_SIZE,\n }\n );\n\n // Process each chunk sequentially\n for (let chunkIndex = 0; chunkIndex < chunks.length; chunkIndex++) {\n const chunk = chunks[chunkIndex];\n console.log(\n `Processing chunk ${chunkIndex + 1}/${chunks.length} with ${chunk.length\n } replacements`\n );\n\n // Send chunk processing start update\n sendProgressUpdate(\n commandId,\n \"set_multiple_text_contents\",\n \"in_progress\",\n Math.round(5 + (chunkIndex / chunks.length) * 90), // 5-95% for processing\n text.length,\n successCount + failureCount,\n `Processing text replacements chunk ${chunkIndex + 1}/${chunks.length}`,\n {\n currentChunk: chunkIndex + 1,\n totalChunks: chunks.length,\n successCount,\n failureCount,\n }\n );\n\n // Process replacements within a chunk in parallel\n const chunkPromises = chunk.map(", "suffix_code": ");\n\n // Wait for all replacements in this chunk to complete\n const chunkResults = await Promise.all(chunkPromises);\n\n // Process results for this chunk\n chunkResults.forEach((result) => {\n if (result.success) {\n successCount++;\n } else {\n failureCount++;\n }\n results.push(result);\n });\n\n // Send chunk processing complete update with partial results\n sendProgressUpdate(\n commandId,\n \"set_multiple_text_contents\",\n \"in_progress\",\n Math.round(5 + ((chunkIndex + 1) / chunks.length) * 90), // 5-95% for processing\n text.length,\n successCount + failureCount,\n `Completed chunk ${chunkIndex + 1}/${chunks.length\n }. ${successCount} successful, ${failureCount} failed so far.`,\n {\n currentChunk: chunkIndex + 1,\n totalChunks: chunks.length,\n successCount,\n failureCount,\n chunkResults: chunkResults,\n }\n );\n\n // Add a small delay between chunks to avoid overloading Figma\n if (chunkIndex < chunks.length - 1) {\n console.log(\"Pausing between chunks to avoid overloading Figma...\");\n await delay(1000); // 1 second delay between chunks\n }\n }\n\n console.log(\n `Replacement complete: ${successCount} successful, ${failureCount} failed`\n );\n\n // Send completed progress update\n sendProgressUpdate(\n commandId,\n \"set_multiple_text_contents\",\n \"completed\",\n 100,\n text.length,\n successCount + failureCount,\n `Text replacement complete: ${successCount} successful, ${failureCount} failed`,\n {\n totalReplacements: text.length,\n replacementsApplied: successCount,\n replacementsFailed: failureCount,\n completedInChunks: chunks.length,\n results: results,\n }\n );\n\n return {\n success: successCount > 0,\n nodeId: nodeId,\n replacementsApplied: successCount,\n replacementsFailed: failureCount,\n totalReplacements: text.length,\n results: results,\n completedInChunks: chunks.length,\n commandId,\n };\n}\n\n// Function to generate simple UUIDs for command IDs\nfunction generateCommandId() {\n return (\n \"cmd_\" +\n Math.random().toString(36).substring(2, 15) +\n Math.random().toString(36).substring(2, 15)\n );\n}\n\nasync function getAnnotations(params) {\n try {\n const { nodeId, includeCategories = true } = params;\n\n // Get categories first if needed\n let categoriesMap = {};\n if (includeCategories) {\n const categories = await figma.annotations.getAnnotationCategoriesAsync();\n categoriesMap = categories.reduce((map, category) => {\n map[category.id] = {\n id: category.id,\n label: category.label,\n color: category.color,\n isPreset: category.isPreset,\n };\n return map;\n }, {});\n }\n\n if (nodeId) {\n // Get annotations for a specific node\n const node = await figma.getNodeByIdAsync(nodeId);\n if (!node) {\n throw new Error(`Node not found: ${nodeId}`);\n }\n\n if (!(\"annotations\" in node)) {\n throw new Error(`Node type ${node.type} does not support annotations`);\n }\n\n const result = {\n nodeId: node.id,\n name: node.name,\n annotations: node.annotations || [],\n };\n\n if (includeCategories) {\n result.categories = Object.values(categoriesMap);\n }\n\n return result;\n } else {\n // Get all annotations in the current page\n const annotations = [];\n const processNode = async (node) => {\n if (\n \"annotations\" in node &&\n node.annotations &&\n node.annotations.length > 0\n ) {\n annotations.push({\n nodeId: node.id,\n name: node.name,\n annotations: node.annotations,\n });\n }\n if (\"children\" in node) {\n for (const child of node.children) {\n await processNode(child);\n }\n }\n };\n\n // Start from current page\n await processNode(figma.currentPage);\n\n const result = {\n annotatedNodes: annotations,\n };\n\n if (includeCategories) {\n result.categories = Object.values(categoriesMap);\n }\n\n return result;\n }\n } catch (error) {\n console.error(\"Error in getAnnotations:\", error);\n throw error;\n }\n}\n\nasync function setAnnotation(params) {\n try {\n console.log(\"=== setAnnotation Debug Start ===\");\n console.log(\"Input params:\", JSON.stringify(params, null, 2));\n\n const { nodeId, annotationId, labelMarkdown, categoryId, properties } =\n params;\n\n // Validate required parameters\n if (!nodeId) {\n console.error(\"Validation failed: Missing nodeId\");\n return { success: false, error: \"Missing nodeId\" };\n }\n\n if (!labelMarkdown) {\n console.error(\"Validation failed: Missing labelMarkdown\");\n return { success: false, error: \"Missing labelMarkdown\" };\n }\n\n console.log(\"Attempting to get node:\", nodeId);\n // Get and validate node\n const node = await figma.getNodeByIdAsync(nodeId);\n console.log(\"Node lookup result:\", {\n id: nodeId,\n found: !!node,\n type: node ? node.type : undefined,\n name: node ? node.name : undefined,\n hasAnnotations: node ? \"annotations\" in node : false,\n });\n\n if (!node) {\n console.error(\"Node lookup failed:\", nodeId);\n return { success: false, error: `Node not found: ${nodeId}` };\n }\n\n // Validate node supports annotations\n if (!(\"annotations\" in node)) {\n console.error(\"Node annotation support check failed:\", {\n nodeType: node.type,\n nodeId: node.id,\n });\n return {\n success: false,\n error: `Node type ${node.type} does not support annotations`,\n };\n }\n\n // Create the annotation object\n const newAnnotation = {\n labelMarkdown,\n };\n\n // Validate and add categoryId if provided\n if (categoryId) {\n console.log(\"Adding categoryId to annotation:\", categoryId);\n newAnnotation.categoryId = categoryId;\n }\n\n // Validate and add properties if provided\n if (properties && Array.isArray(properties) && properties.length > 0) {\n console.log(\n \"Adding properties to annotation:\",\n JSON.stringify(properties, null, 2)\n );\n newAnnotation.properties = properties;\n }\n\n // Log current annotations before update\n console.log(\"Current node annotations:\", node.annotations);\n\n // Overwrite annotations\n console.log(\n \"Setting new annotation:\",\n JSON.stringify(newAnnotation, null, 2)\n );\n node.annotations = [newAnnotation];\n\n // Verify the update\n console.log(\"Updated node annotations:\", node.annotations);\n console.log(\"=== setAnnotation Debug End ===\");\n\n return {\n success: true,\n nodeId: node.id,\n name: node.name,\n annotations: node.annotations,\n };\n } catch (error) {\n console.error(\"=== setAnnotation Error ===\");\n console.error(\"Error details:\", {\n message: error.message,\n stack: error.stack,\n params: JSON.stringify(params, null, 2),\n });\n return { success: false, error: error.message };\n }\n}\n\n/**\n * Scan for nodes with specific types within a node\n * @param {Object} params - Parameters object\n * @param {string} params.nodeId - ID of the node to scan within\n * @param {Array} params.types - Array of node types to find (e.g. ['COMPONENT', 'FRAME'])\n * @returns {Object} - Object containing found nodes\n */\nasync function scanNodesByTypes(params) {\n console.log(`Starting to scan nodes by types from node ID: ${params.nodeId}`);\n const { nodeId, types = [] } = params || {};\n\n if (!types || types.length === 0) {\n throw new Error(\"No types specified to search for\");\n }\n\n const node = await figma.getNodeByIdAsync(nodeId);\n\n if (!node) {\n throw new Error(`Node with ID ${nodeId} not found`);\n }\n\n // Simple implementation without chunking\n const matchingNodes = [];\n\n // Send a single progress update to notify start\n const commandId = generateCommandId();\n sendProgressUpdate(\n commandId,\n \"scan_nodes_by_types\",\n \"started\",\n 0,\n 1,\n 0,\n `Starting scan of node \"${node.name || nodeId}\" for types: ${types.join(\n \", \"\n )}`,\n null\n );\n\n // Recursively find nodes with specified types\n await findNodesByTypes(node, types, matchingNodes);\n\n // Send completion update\n sendProgressUpdate(\n commandId,\n \"scan_nodes_by_types\",\n \"completed\",\n 100,\n matchingNodes.length,\n matchingNodes.length,\n `Scan complete. Found ${matchingNodes.length} matching nodes.`,\n { matchingNodes }\n );\n\n return {\n success: true,\n message: `Found ${matchingNodes.length} matching nodes.`,\n count: matchingNodes.length,\n matchingNodes: matchingNodes,\n searchedTypes: types,\n };\n}\n\n/**\n * Helper function to recursively find nodes with specific types\n * @param {SceneNode} node - The root node to start searching from\n * @param {Array} types - Array of node types to find\n * @param {Array} matchingNodes - Array to store found nodes\n */\nasync function findNodesByTypes(node, types, matchingNodes = []) {\n // Skip invisible nodes\n if (node.visible === false) return;\n\n // Check if this node is one of the specified types\n if (types.includes(node.type)) {\n // Create a minimal representation with just ID, type and bbox\n matchingNodes.push({\n id: node.id,\n name: node.name || `Unnamed ${node.type}`,\n type: node.type,\n // Basic bounding box info\n bbox: {\n x: typeof node.x === \"number\" ? node.x : 0,\n y: typeof node.y === \"number\" ? node.y : 0,\n width: typeof node.width === \"number\" ? node.width : 0,\n height: typeof node.height === \"number\" ? node.height : 0,\n },\n });\n }\n\n // Recursively process children of container nodes\n if (\"children\" in node) {\n for (const child of node.children) {\n await findNodesByTypes(child, types, matchingNodes);\n }\n }\n}\n\n// Set multiple annotations with async progress updates\nasync function setMultipleAnnotations(params) {\n console.log(\"=== setMultipleAnnotations Debug Start ===\");\n console.log(\"Input params:\", JSON.stringify(params, null, 2));\n\n const { nodeId, annotations } = params;\n\n if (!annotations || annotations.length === 0) {\n console.error(\"Validation failed: No annotations provided\");\n return { success: false, error: \"No annotations provided\" };\n }\n\n console.log(\n `Processing ${annotations.length} annotations for node ${nodeId}`\n );\n\n const results = [];\n let successCount = 0;\n let failureCount = 0;\n\n // Process annotations sequentially\n for (let i = 0; i < annotations.length; i++) {\n const annotation = annotations[i];\n console.log(\n `\\nProcessing annotation ${i + 1}/${annotations.length}:`,\n JSON.stringify(annotation, null, 2)\n );\n\n try {\n console.log(\"Calling setAnnotation with params:\", {\n nodeId: annotation.nodeId,\n labelMarkdown: annotation.labelMarkdown,\n categoryId: annotation.categoryId,\n properties: annotation.properties,\n });\n\n const result = await setAnnotation({\n nodeId: annotation.nodeId,\n labelMarkdown: annotation.labelMarkdown,\n categoryId: annotation.categoryId,\n properties: annotation.properties,\n });\n\n console.log(\"setAnnotation result:\", JSON.stringify(result, null, 2));\n\n if (result.success) {\n successCount++;\n results.push({ success: true, nodeId: annotation.nodeId });\n console.log(`✓ Annotation ${i + 1} applied successfully`);\n } else {\n failureCount++;\n results.push({\n success: false,\n nodeId: annotation.nodeId,\n error: result.error,\n });\n console.error(`✗ Annotation ${i + 1} failed:`, result.error);\n }\n } catch (error) {\n failureCount++;\n const errorResult = {\n success: false,\n nodeId: annotation.nodeId,\n error: error.message,\n };\n results.push(errorResult);\n console.error(`✗ Annotation ${i + 1} failed with error:`, error);\n console.error(\"Error details:\", {\n message: error.message,\n stack: error.stack,\n });\n }\n }\n\n const summary = {\n success: successCount > 0,\n annotationsApplied: successCount,\n annotationsFailed: failureCount,\n totalAnnotations: annotations.length,\n results: results,\n };\n\n console.log(\"\\n=== setMultipleAnnotations Summary ===\");\n console.log(JSON.stringify(summary, null, 2));\n console.log(\"=== setMultipleAnnotations Debug End ===\");\n\n return summary;\n}\n\nasync function deleteMultipleNodes(params) {\n const { nodeIds } = params || {};\n const commandId = generateCommandId();\n\n if (!nodeIds || !Array.isArray(nodeIds) || nodeIds.length === 0) {\n const errorMsg = \"Missing or invalid nodeIds parameter\";\n sendProgressUpdate(\n commandId,\n \"delete_multiple_nodes\",\n \"error\",\n 0,\n 0,\n 0,\n errorMsg,\n { error: errorMsg }\n );\n throw new Error(errorMsg);\n }\n\n console.log(`Starting deletion of ${nodeIds.length} nodes`);\n\n // Send started progress update\n sendProgressUpdate(\n commandId,\n \"delete_multiple_nodes\",\n \"started\",\n 0,\n nodeIds.length,\n 0,\n `Starting deletion of ${nodeIds.length} nodes`,\n { totalNodes: nodeIds.length }\n );\n\n const results = [];\n let successCount = 0;\n let failureCount = 0;\n\n // Process nodes in chunks of 5 to avoid overwhelming Figma\n const CHUNK_SIZE = 5;\n const chunks = [];\n\n for (let i = 0; i < nodeIds.length; i += CHUNK_SIZE) {\n chunks.push(nodeIds.slice(i, i + CHUNK_SIZE));\n }\n\n console.log(`Split ${nodeIds.length} deletions into ${chunks.length} chunks`);\n\n // Send chunking info update\n sendProgressUpdate(\n commandId,\n \"delete_multiple_nodes\",\n \"in_progress\",\n 5,\n nodeIds.length,\n 0,\n `Preparing to delete ${nodeIds.length} nodes using ${chunks.length} chunks`,\n {\n totalNodes: nodeIds.length,\n chunks: chunks.length,\n chunkSize: CHUNK_SIZE,\n }\n );\n\n // Process each chunk sequentially\n for (let chunkIndex = 0; chunkIndex < chunks.length; chunkIndex++) {\n const chunk = chunks[chunkIndex];\n console.log(\n `Processing chunk ${chunkIndex + 1}/${chunks.length} with ${chunk.length\n } nodes`\n );\n\n // Send chunk processing start update\n sendProgressUpdate(\n commandId,\n \"delete_multiple_nodes\",\n \"in_progress\",\n Math.round(5 + (chunkIndex / chunks.length) * 90),\n nodeIds.length,\n successCount + failureCount,\n `Processing deletion chunk ${chunkIndex + 1}/${chunks.length}`,\n {\n currentChunk: chunkIndex + 1,\n totalChunks: chunks.length,\n successCount,\n failureCount,\n }\n );\n\n // Process deletions within a chunk in parallel\n const chunkPromises = chunk.map(async (nodeId) => {\n try {\n const node = await figma.getNodeByIdAsync(nodeId);\n\n if (!node) {\n console.error(`Node not found: ${nodeId}`);\n return {\n success: false,\n nodeId: nodeId,\n error: `Node not found: ${nodeId}`,\n };\n }\n\n // Save node info before deleting\n const nodeInfo = {\n id: node.id,\n name: node.name,\n type: node.type,\n };\n\n // Delete the node\n node.remove();\n\n console.log(`Successfully deleted node: ${nodeId}`);\n return {\n success: true,\n nodeId: nodeId,\n nodeInfo: nodeInfo,\n };\n } catch (error) {\n console.error(`Error deleting node ${nodeId}: ${error.message}`);\n return {\n success: false,\n nodeId: nodeId,\n error: error.message,\n };\n }\n });\n\n // Wait for all deletions in this chunk to complete\n const chunkResults = await Promise.all(chunkPromises);\n\n // Process results for this chunk\n chunkResults.forEach((result) => {\n if (result.success) {\n successCount++;\n } else {\n failureCount++;\n }\n results.push(result);\n });\n\n // Send chunk processing complete update\n sendProgressUpdate(\n commandId,\n \"delete_multiple_nodes\",\n \"in_progress\",\n Math.round(5 + ((chunkIndex + 1) / chunks.length) * 90),\n nodeIds.length,\n successCount + failureCount,\n `Completed chunk ${chunkIndex + 1}/${chunks.length\n }. ${successCount} successful, ${failureCount} failed so far.`,\n {\n currentChunk: chunkIndex + 1,\n totalChunks: chunks.length,\n successCount,\n failureCount,\n chunkResults: chunkResults,\n }\n );\n\n // Add a small delay between chunks\n if (chunkIndex < chunks.length - 1) {\n console.log(\"Pausing between chunks...\");\n await delay(1000);\n }\n }\n\n console.log(\n `Deletion complete: ${successCount} successful, ${failureCount} failed`\n );\n\n // Send completed progress update\n sendProgressUpdate(\n commandId,\n \"delete_multiple_nodes\",\n \"completed\",\n 100,\n nodeIds.length,\n successCount + failureCount,\n `Node deletion complete: ${successCount} successful, ${failureCount} failed`,\n {\n totalNodes: nodeIds.length,\n nodesDeleted: successCount,\n nodesFailed: failureCount,\n completedInChunks: chunks.length,\n results: results,\n }\n );\n\n return {\n success: successCount > 0,\n nodesDeleted: successCount,\n nodesFailed: failureCount,\n totalNodes: nodeIds.length,\n results: results,\n completedInChunks: chunks.length,\n commandId,\n };\n}\n\n// Implementation for getInstanceOverrides function\nasync function getInstanceOverrides(instanceNode = null) {\n console.log(\"=== getInstanceOverrides called ===\");\n\n let sourceInstance = null;\n\n // Check if an instance node was passed directly\n if (instanceNode) {\n console.log(\"Using provided instance node\");\n\n // Validate that the provided node is an instance\n if (instanceNode.type !== \"INSTANCE\") {\n console.error(\"Provided node is not an instance\");\n figma.notify(\"Provided node is not a component instance\");\n return { success: false, message: \"Provided node is not a component instance\" };\n }\n\n sourceInstance = instanceNode;\n } else {\n // No node provided, use selection\n console.log(\"No node provided, using current selection\");\n\n // Get the current selection\n const selection = figma.currentPage.selection;\n\n // Check if there's anything selected\n if (selection.length === 0) {\n console.log(\"No nodes selected\");\n figma.notify(\"Please select at least one instance\");\n return { success: false, message: \"No nodes selected\" };\n }\n\n // Filter for instances in the selection\n const instances = selection.filter(node => node.type === \"INSTANCE\");\n\n if (instances.length === 0) {\n console.log(\"No instances found in selection\");\n figma.notify(\"Please select at least one component instance\");\n return { success: false, message: \"No instances found in selection\" };\n }\n\n // Take the first instance from the selection\n sourceInstance = instances[0];\n }\n\n try {\n console.log(`Getting instance information:`);\n console.log(sourceInstance);\n\n // Get component overrides and main component\n const overrides = sourceInstance.overrides || [];\n console.log(` Raw Overrides:`, overrides);\n\n // Get main component\n const mainComponent = await sourceInstance.getMainComponentAsync();\n if (!mainComponent) {\n console.error(\"Failed to get main component\");\n figma.notify(\"Failed to get main component\");\n return { success: false, message: \"Failed to get main component\" };\n }\n\n // return data to MCP server\n const returnData = {\n success: true,\n message: `Got component information from \"${sourceInstance.name}\" for overrides.length: ${overrides.length}`,\n sourceInstanceId: sourceInstance.id,\n mainComponentId: mainComponent.id,\n overridesCount: overrides.length\n };\n\n console.log(\"Data to return to MCP server:\", returnData);\n figma.notify(`Got component information from \"${sourceInstance.name}\"`);\n\n return returnData;\n } catch (error) {\n console.error(\"Error in getInstanceOverrides:\", error);\n figma.notify(`Error: ${error.message}`);\n return {\n success: false,\n message: `Error: ${error.message}`\n };\n }\n}\n\n/**\n * Helper function to validate and get target instances\n * @param {string[]} targetNodeIds - Array of instance node IDs\n * @returns {instanceNode[]} targetInstances - Array of target instances\n */\nasync function getValidTargetInstances(targetNodeIds) {\n let targetInstances = [];\n\n // Handle array of instances or single instance\n if (Array.isArray(targetNodeIds)) {\n if (targetNodeIds.length === 0) {\n return { success: false, message: \"No instances provided\" };\n }\n for (const targetNodeId of targetNodeIds) {\n const targetNode = await figma.getNodeByIdAsync(targetNodeId);\n if (targetNode && targetNode.type === \"INSTANCE\") {\n targetInstances.push(targetNode);\n }\n }\n if (targetInstances.length === 0) {\n return { success: false, message: \"No valid instances provided\" };\n }\n } else {\n return { success: false, message: \"Invalid target node IDs provided\" };\n }\n\n\n return { success: true, message: \"Valid target instances provided\", targetInstances };\n}\n\n/**\n * Helper function to validate and get saved override data\n * @param {string} sourceInstanceId - Source instance ID\n * @returns {Promise} - Validation result with source instance data or error\n */\nasync function getSourceInstanceData(sourceInstanceId) {\n if (!sourceInstanceId) {\n return { success: false, message: \"Missing source instance ID\" };\n }\n\n // Get source instance by ID\n const sourceInstance = await figma.getNodeByIdAsync(sourceInstanceId);\n if (!sourceInstance) {\n return {\n success: false,\n message: \"Source instance not found. The original instance may have been deleted.\"\n };\n }\n\n // Verify it's an instance\n if (sourceInstance.type !== \"INSTANCE\") {\n return {\n success: false,\n message: \"Source node is not a component instance.\"\n };\n }\n\n // Get main component\n const mainComponent = await sourceInstance.getMainComponentAsync();\n if (!mainComponent) {\n return {\n success: false,\n message: \"Failed to get main component from source instance.\"\n };\n }\n\n return {\n success: true,\n sourceInstance,\n mainComponent,\n overrides: sourceInstance.overrides || []\n };\n}\n\n/**\n * Sets saved overrides to the selected component instance(s)\n * @param {InstanceNode[] | null} targetInstances - Array of instance nodes to set overrides to\n * @param {Object} sourceResult - Source instance data from getSourceInstanceData\n * @returns {Promise} - Result of the set operation\n */\nasync function setInstanceOverrides(targetInstances, sourceResult) {\n try {\n\n\n const { sourceInstance, mainComponent, overrides } = sourceResult;\n\n console.log(`Processing ${targetInstances.length} instances with ${overrides.length} overrides`);\n console.log(`Source instance: ${sourceInstance.id}, Main component: ${mainComponent.id}`);\n console.log(`Overrides:`, overrides);\n\n // Process all instances\n const results = [];\n let totalAppliedCount = 0;\n\n for (const targetInstance of targetInstances) {\n try {\n // // Skip if trying to apply to the source instance itself\n // if (targetInstance.id === sourceInstance.id) {\n // console.log(`Skipping source instance itself: ${targetInstance.id}`);\n // results.push({\n // success: false,\n // instanceId: targetInstance.id,\n // instanceName: targetInstance.name,\n // message: \"This is the source instance itself, skipping\"\n // });\n // continue;\n // }\n\n // Swap component\n try {\n targetInstance.swapComponent(mainComponent);\n console.log(`Swapped component for instance \"${targetInstance.name}\"`);\n } catch (error) {\n console.error(`Error swapping component for instance \"${targetInstance.name}\":`, error);\n results.push({\n success: false,\n instanceId: targetInstance.id,\n instanceName: targetInstance.name,\n message: `Error: ${error.message}`\n });\n }\n\n // Prepare overrides by replacing node IDs\n let appliedCount = 0;\n\n // Apply each override\n for (const override of overrides) {\n // Skip if no ID or overriddenFields\n if (!override.id || !override.overriddenFields || override.overriddenFields.length === 0) {\n continue;\n }\n\n // Replace source instance ID with target instance ID in the node path\n const overrideNodeId = override.id.replace(sourceInstance.id, targetInstance.id);\n const overrideNode = await figma.getNodeByIdAsync(overrideNodeId);\n\n if (!overrideNode) {\n console.log(`Override node not found: ${overrideNodeId}`);\n continue;\n }\n\n // Get source node to copy properties from\n const sourceNode = await figma.getNodeByIdAsync(override.id);\n if (!sourceNode) {\n console.log(`Source node not found: ${override.id}`);\n continue;\n }\n\n // Apply each overridden field\n let fieldApplied = false;\n for (const field of override.overriddenFields) {\n try {\n if (field === \"componentProperties\") {\n // Apply component properties\n if (sourceNode.componentProperties && overrideNode.componentProperties) {\n const properties = {};\n for (const key in sourceNode.componentProperties) {\n // if INSTANCE_SWAP use id, otherwise use value\n if (sourceNode.componentProperties[key].type === 'INSTANCE_SWAP') {\n properties[key] = sourceNode.componentProperties[key].value;\n \n } else {\n properties[key] = sourceNode.componentProperties[key].value;\n }\n }\n overrideNode.setProperties(properties);\n fieldApplied = true;\n }\n } else if (field === \"characters\" && overrideNode.type === \"TEXT\") {\n // For text nodes, need to load fonts first\n await figma.loadFontAsync(overrideNode.fontName);\n overrideNode.characters = sourceNode.characters;\n fieldApplied = true;\n } else if (field in overrideNode) {\n // Direct property assignment\n overrideNode[field] = sourceNode[field];\n fieldApplied = true;\n }\n } catch (fieldError) {\n console.error(`Error applying field ${field}:`, fieldError);\n }\n }\n\n if (fieldApplied) {\n appliedCount++;\n }\n }\n\n if (appliedCount > 0) {\n totalAppliedCount += appliedCount;\n results.push({\n success: true,\n instanceId: targetInstance.id,\n instanceName: targetInstance.name,\n appliedCount\n });\n console.log(`Applied ${appliedCount} overrides to \"${targetInstance.name}\"`);\n } else {\n results.push({\n success: false,\n instanceId: targetInstance.id,\n instanceName: targetInstance.name,\n message: \"No overrides were applied\"\n });\n }\n } catch (instanceError) {\n console.error(`Error processing instance \"${targetInstance.name}\":`, instanceError);\n results.push({\n success: false,\n instanceId: targetInstance.id,\n instanceName: targetInstance.name,\n message: `Error: ${instanceError.message}`\n });\n }\n }\n\n // Return results\n if (totalAppliedCount > 0) {\n const instanceCount = results.filter(r => r.success).length;\n const message = `Applied ${totalAppliedCount} overrides to ${instanceCount} instances`;\n figma.notify(message);\n return {\n success: true,\n message,\n totalCount: totalAppliedCount,\n results\n };\n } else {\n const message = \"No overrides applied to any instance\";\n figma.notify(message);\n return { success: false, message, results };\n }\n\n } catch (error) {\n console.error(\"Error in setInstanceOverrides:\", error);\n const message = `Error: ${error.message}`;\n figma.notify(message);\n return { success: false, message };\n }\n}\n\nasync function setLayoutMode(params) {\n const { nodeId, layoutMode = \"NONE\", layoutWrap = \"NO_WRAP\" } = params || {};\n\n // Get the target node\n const node = await figma.getNodeByIdAsync(nodeId);\n if (!node) {\n throw new Error(`Node with ID ${nodeId} not found`);\n }\n\n // Check if node is a frame or component that supports layoutMode\n if (\n node.type !== \"FRAME\" &&\n node.type !== \"COMPONENT\" &&\n node.type !== \"COMPONENT_SET\" &&\n node.type !== \"INSTANCE\"\n ) {\n throw new Error(`Node type ${node.type} does not support layoutMode`);\n }\n\n // Set layout mode\n node.layoutMode = layoutMode;\n\n // Set layoutWrap if applicable\n if (layoutMode !== \"NONE\") {\n node.layoutWrap = layoutWrap;\n }\n\n return {\n id: node.id,\n name: node.name,\n layoutMode: node.layoutMode,\n layoutWrap: node.layoutWrap,\n };\n}\n\nasync function setPadding(params) {\n const { nodeId, paddingTop, paddingRight, paddingBottom, paddingLeft } =\n params || {};\n\n // Get the target node\n const node = await figma.getNodeByIdAsync(nodeId);\n if (!node) {\n throw new Error(`Node with ID ${nodeId} not found`);\n }\n\n // Check if node is a frame or component that supports padding\n if (\n node.type !== \"FRAME\" &&\n node.type !== \"COMPONENT\" &&\n node.type !== \"COMPONENT_SET\" &&\n node.type !== \"INSTANCE\"\n ) {\n throw new Error(`Node type ${node.type} does not support padding`);\n }\n\n // Check if the node has auto-layout enabled\n if (node.layoutMode === \"NONE\") {\n throw new Error(\n \"Padding can only be set on auto-layout frames (layoutMode must not be NONE)\"\n );\n }\n\n // Set padding values if provided\n if (paddingTop !== undefined) node.paddingTop = paddingTop;\n if (paddingRight !== undefined) node.paddingRight = paddingRight;\n if (paddingBottom !== undefined) node.paddingBottom = paddingBottom;\n if (paddingLeft !== undefined) node.paddingLeft = paddingLeft;\n\n return {\n id: node.id,\n name: node.name,\n paddingTop: node.paddingTop,\n paddingRight: node.paddingRight,\n paddingBottom: node.paddingBottom,\n paddingLeft: node.paddingLeft,\n };\n}\n\nasync function setAxisAlign(params) {\n const { nodeId, primaryAxisAlignItems, counterAxisAlignItems } = params || {};\n\n // Get the target node\n const node = await figma.getNodeByIdAsync(nodeId);\n if (!node) {\n throw new Error(`Node with ID ${nodeId} not found`);\n }\n\n // Check if node is a frame or component that supports axis alignment\n if (\n node.type !== \"FRAME\" &&\n node.type !== \"COMPONENT\" &&\n node.type !== \"COMPONENT_SET\" &&\n node.type !== \"INSTANCE\"\n ) {\n throw new Error(`Node type ${node.type} does not support axis alignment`);\n }\n\n // Check if the node has auto-layout enabled\n if (node.layoutMode === \"NONE\") {\n throw new Error(\n \"Axis alignment can only be set on auto-layout frames (layoutMode must not be NONE)\"\n );\n }\n\n // Validate and set primaryAxisAlignItems if provided\n if (primaryAxisAlignItems !== undefined) {\n if (\n ![\"MIN\", \"MAX\", \"CENTER\", \"SPACE_BETWEEN\"].includes(primaryAxisAlignItems)\n ) {\n throw new Error(\n \"Invalid primaryAxisAlignItems value. Must be one of: MIN, MAX, CENTER, SPACE_BETWEEN\"\n );\n }\n node.primaryAxisAlignItems = primaryAxisAlignItems;\n }\n\n // Validate and set counterAxisAlignItems if provided\n if (counterAxisAlignItems !== undefined) {\n if (![\"MIN\", \"MAX\", \"CENTER\", \"BASELINE\"].includes(counterAxisAlignItems)) {\n throw new Error(\n \"Invalid counterAxisAlignItems value. Must be one of: MIN, MAX, CENTER, BASELINE\"\n );\n }\n // BASELINE is only valid for horizontal layout\n if (\n counterAxisAlignItems === \"BASELINE\" &&\n node.layoutMode !== \"HORIZONTAL\"\n ) {\n throw new Error(\n \"BASELINE alignment is only valid for horizontal auto-layout frames\"\n );\n }\n node.counterAxisAlignItems = counterAxisAlignItems;\n }\n\n return {\n id: node.id,\n name: node.name,\n primaryAxisAlignItems: node.primaryAxisAlignItems,\n counterAxisAlignItems: node.counterAxisAlignItems,\n layoutMode: node.layoutMode,\n };\n}\n\nasync function setLayoutSizing(params) {\n const { nodeId, layoutSizingHorizontal, layoutSizingVertical } = params || {};\n\n // Get the target node\n const node = await figma.getNodeByIdAsync(nodeId);\n if (!node) {\n throw new Error(`Node with ID ${nodeId} not found`);\n }\n\n // Check if node is a frame or component that supports layout sizing\n if (\n node.type !== \"FRAME\" &&\n node.type !== \"COMPONENT\" &&\n node.type !== \"COMPONENT_SET\" &&\n node.type !== \"INSTANCE\"\n ) {\n throw new Error(`Node type ${node.type} does not support layout sizing`);\n }\n\n // Check if the node has auto-layout enabled\n if (node.layoutMode === \"NONE\") {\n throw new Error(\n \"Layout sizing can only be set on auto-layout frames (layoutMode must not be NONE)\"\n );\n }\n\n // Validate and set layoutSizingHorizontal if provided\n if (layoutSizingHorizontal !== undefined) {\n if (![\"FIXED\", \"HUG\", \"FILL\"].includes(layoutSizingHorizontal)) {\n throw new Error(\n \"Invalid layoutSizingHorizontal value. Must be one of: FIXED, HUG, FILL\"\n );\n }\n // HUG is only valid on auto-layout frames and text nodes\n if (\n layoutSizingHorizontal === \"HUG\" &&\n ![\"FRAME\", \"TEXT\"].includes(node.type)\n ) {\n throw new Error(\n \"HUG sizing is only valid on auto-layout frames and text nodes\"\n );\n }\n // FILL is only valid on auto-layout children\n if (\n layoutSizingHorizontal === \"FILL\" &&\n (!node.parent || node.parent.layoutMode === \"NONE\")\n ) {\n throw new Error(\"FILL sizing is only valid on auto-layout children\");\n }\n node.layoutSizingHorizontal = layoutSizingHorizontal;\n }\n\n // Validate and set layoutSizingVertical if provided\n if (layoutSizingVertical !== undefined) {\n if (![\"FIXED\", \"HUG\", \"FILL\"].includes(layoutSizingVertical)) {\n throw new Error(\n \"Invalid layoutSizingVertical value. Must be one of: FIXED, HUG, FILL\"\n );\n }\n // HUG is only valid on auto-layout frames and text nodes\n if (\n layoutSizingVertical === \"HUG\" &&\n ![\"FRAME\", \"TEXT\"].includes(node.type)\n ) {\n throw new Error(\n \"HUG sizing is only valid on auto-layout frames and text nodes\"\n );\n }\n // FILL is only valid on auto-layout children\n if (\n layoutSizingVertical === \"FILL\" &&\n (!node.parent || node.parent.layoutMode === \"NONE\")\n ) {\n throw new Error(\"FILL sizing is only valid on auto-layout children\");\n }\n node.layoutSizingVertical = layoutSizingVertical;\n }\n\n return {\n id: node.id,\n name: node.name,\n layoutSizingHorizontal: node.layoutSizingHorizontal,\n layoutSizingVertical: node.layoutSizingVertical,\n layoutMode: node.layoutMode,\n };\n}\n\nasync function setItemSpacing(params) {\n const { nodeId, itemSpacing } = params || {};\n\n // Get the target node\n const node = await figma.getNodeByIdAsync(nodeId);\n if (!node) {\n throw new Error(`Node with ID ${nodeId} not found`);\n }\n\n // Check if node is a frame or component that supports item spacing\n if (\n node.type !== \"FRAME\" &&\n node.type !== \"COMPONENT\" &&\n node.type !== \"COMPONENT_SET\" &&\n node.type !== \"INSTANCE\"\n ) {\n throw new Error(`Node type ${node.type} does not support item spacing`);\n }\n\n // Check if the node has auto-layout enabled\n if (node.layoutMode === \"NONE\") {\n throw new Error(\n \"Item spacing can only be set on auto-layout frames (layoutMode must not be NONE)\"\n );\n }\n\n // Set item spacing\n if (itemSpacing !== undefined) {\n if (typeof itemSpacing !== \"number\") {\n throw new Error(\"Item spacing must be a number\");\n }\n node.itemSpacing = itemSpacing;\n }\n\n return {\n id: node.id,\n name: node.name,\n itemSpacing: node.itemSpacing,\n layoutMode: node.layoutMode,\n };\n}\n\nasync function setDefaultConnector(params) {\n const { connectorId } = params || {};\n \n // If connectorId is provided, search and set by that ID (do not check existing storage)\n if (connectorId) {\n // Get node by specified ID\n const node = await figma.getNodeByIdAsync(connectorId);\n if (!node) {\n throw new Error(`Connector node not found with ID: ${connectorId}`);\n }\n \n // Check node type\n if (node.type !== 'CONNECTOR') {\n throw new Error(`Node is not a connector: ${connectorId}`);\n }\n \n // Set the found connector as the default connector\n await figma.clientStorage.setAsync('defaultConnectorId', connectorId);\n \n return {\n success: true,\n message: `Default connector set to: ${connectorId}`,\n connectorId: connectorId\n };\n } \n // If connectorId is not provided, check existing storage\n else {\n // Check if there is an existing default connector in client storage\n try {\n const existingConnectorId = await figma.clientStorage.getAsync('defaultConnectorId');\n \n // If there is an existing connector ID, check if the node is still valid\n if (existingConnectorId) {\n try {\n const existingConnector = await figma.getNodeByIdAsync(existingConnectorId);\n \n // If the stored connector still exists and is of type CONNECTOR\n if (existingConnector && existingConnector.type === 'CONNECTOR') {\n return {\n success: true,\n message: `Default connector is already set to: ${existingConnectorId}`,\n connectorId: existingConnectorId,\n exists: true\n };\n }\n // The stored connector is no longer valid - find a new connector\n else {\n console.log(`Stored connector ID ${existingConnectorId} is no longer valid, finding a new connector...`);\n }\n } catch (error) {\n console.log(`Error finding stored connector: ${error.message}. Will try to set a new one.`);\n }\n }\n } catch (error) {\n console.log(`Error checking for existing connector: ${error.message}`);\n }\n \n // If there is no stored default connector or it is invalid, find one in the current page\n try {\n // Find CONNECTOR type nodes in the current page\n const currentPageConnectors = figma.currentPage.findAllWithCriteria({ types: ['CONNECTOR'] });\n \n if (currentPageConnectors && currentPageConnectors.length > 0) {\n // Use the first connector found\n const foundConnector = currentPageConnectors[0];\n const autoFoundId = foundConnector.id;\n \n // Set the found connector as the default connector\n await figma.clientStorage.setAsync('defaultConnectorId', autoFoundId);\n \n return {\n success: true,\n message: `Automatically found and set default connector to: ${autoFoundId}`,\n connectorId: autoFoundId,\n autoSelected: true\n };\n } else {\n // If no connector is found in the current page, show a guide message\n throw new Error('No connector found in the current page. Please create a connector in Figma first or specify a connector ID.');\n }\n } catch (error) {\n // Error occurred while running findAllWithCriteria\n throw new Error(`Failed to find a connector: ${error.message}`);\n }\n }\n}\n\nasync function createCursorNode(targetNodeId) {\n const svgString = `\n \n `;\n try {\n const targetNode = await figma.getNodeByIdAsync(targetNodeId);\n if (!targetNode) throw new Error(\"Target node not found\");\n\n // The targetNodeId has semicolons since it is a nested node.\n // So we need to get the parent node ID from the target node ID and check if we can appendChild to it or not.\n let parentNodeId = targetNodeId.includes(';') \n ? targetNodeId.split(';')[0] \n : targetNodeId;\n if (!parentNodeId) throw new Error(\"Could not determine parent node ID\");\n\n // Find the parent node to append cursor node as child\n let parentNode = await figma.getNodeByIdAsync(parentNodeId);\n if (!parentNode) throw new Error(\"Parent node not found\");\n\n // If the parent node is not eligible to appendChild, set the parentNode to the parent of the parentNode\n if (parentNode.type === 'INSTANCE' || parentNode.type === 'COMPONENT' || parentNode.type === 'COMPONENT_SET') {\n parentNode = parentNode.parent;\n if (!parentNode) throw new Error(\"Parent node not found\");\n }\n\n // Create the cursor node\n const importedNode = await figma.createNodeFromSvg(svgString);\n if (!importedNode || !importedNode.id) {\n throw new Error(\"Failed to create imported cursor node\");\n }\n importedNode.name = \"TTF_Connector / Mouse Cursor\";\n importedNode.resize(48, 48);\n\n const cursorNode = importedNode.findOne(node => node.type === 'VECTOR');\n if (cursorNode) {\n cursorNode.fills = [{\n type: 'SOLID',\n color: { r: 0, g: 0, b: 0 },\n opacity: 1\n }];\n cursorNode.strokes = [{\n type: 'SOLID',\n color: { r: 1, g: 1, b: 1 },\n opacity: 1\n }];\n cursorNode.strokeWeight = 2;\n cursorNode.strokeAlign = 'OUTSIDE';\n cursorNode.effects = [{\n type: \"DROP_SHADOW\",\n color: { r: 0, g: 0, b: 0, a: 0.3 },\n offset: { x: 1, y: 1 },\n radius: 2,\n spread: 0,\n visible: true,\n blendMode: \"NORMAL\"\n }];\n }\n\n // Append the cursor node to the parent node\n parentNode.appendChild(importedNode);\n\n // if the parentNode has auto-layout enabled, set the layoutPositioning to ABSOLUTE\n if ('layoutMode' in parentNode && parentNode.layoutMode !== 'NONE') {\n importedNode.layoutPositioning = 'ABSOLUTE';\n }\n\n // Adjust the importedNode's position to the targetNode's position\n if (\n targetNode.absoluteBoundingBox &&\n parentNode.absoluteBoundingBox\n ) {\n // if the targetNode has absoluteBoundingBox, set the importedNode's absoluteBoundingBox to the targetNode's absoluteBoundingBox\n console.log('targetNode.absoluteBoundingBox', targetNode.absoluteBoundingBox);\n console.log('parentNode.absoluteBoundingBox', parentNode.absoluteBoundingBox);\n importedNode.x = targetNode.absoluteBoundingBox.x - parentNode.absoluteBoundingBox.x + targetNode.absoluteBoundingBox.width / 2 - 48 / 2\n importedNode.y = targetNode.absoluteBoundingBox.y - parentNode.absoluteBoundingBox.y + targetNode.absoluteBoundingBox.height / 2 - 48 / 2;\n } else if (\n 'x' in targetNode && 'y' in targetNode && 'width' in targetNode && 'height' in targetNode) {\n // if the targetNode has x, y, width, height, calculate center based on relative position\n console.log('targetNode.x/y/width/height', targetNode.x, targetNode.y, targetNode.width, targetNode.height);\n importedNode.x = targetNode.x + targetNode.width / 2 - 48 / 2;\n importedNode.y = targetNode.y + targetNode.height / 2 - 48 / 2;\n } else {\n // Fallback: Place at top-left of target if possible, otherwise at (0,0) relative to parent\n if ('x' in targetNode && 'y' in targetNode) {\n console.log('Fallback to targetNode x/y');\n importedNode.x = targetNode.x;\n importedNode.y = targetNode.y;\n } else {\n console.log('Fallback to (0,0)');\n importedNode.x = 0;\n importedNode.y = 0;\n }\n }\n\n // get the importedNode ID and the importedNode\n console.log('importedNode', importedNode);\n\n\n return { id: importedNode.id, node: importedNode };\n \n } catch (error) {\n console.error(\"Error creating cursor from SVG:\", error);\n return { id: null, node: null, error: error.message };\n }\n}\n\nasync function createConnections(params) {\n if (!params || !params.connections || !Array.isArray(params.connections)) {\n throw new Error('Missing or invalid connections parameter');\n }\n \n const { connections } = params;\n \n // Command ID for progress tracking\n const commandId = generateCommandId();\n sendProgressUpdate(\n commandId,\n \"create_connections\",\n \"started\",\n 0,\n connections.length,\n 0,\n `Starting to create ${connections.length} connections`\n );\n \n // Get default connector ID from client storage\n const defaultConnectorId = await figma.clientStorage.getAsync('defaultConnectorId');\n if (!defaultConnectorId) {\n throw new Error('No default connector set. Please try one of the following options to create connections:\\n1. Create a connector in FigJam and copy/paste it to your current page, then run the \"set_default_connector\" command.\\n2. Select an existing connector on the current page, then run the \"set_default_connector\" command.');\n }\n \n // Get the default connector\n const defaultConnector = await figma.getNodeByIdAsync(defaultConnectorId);\n if (!defaultConnector) {\n throw new Error(`Default connector not found with ID: ${defaultConnectorId}`);\n }\n if (defaultConnector.type !== 'CONNECTOR') {\n throw new Error(`Node is not a connector: ${defaultConnectorId}`);\n }\n \n // Results array for connection creation\n const results = [];\n let processedCount = 0;\n const totalCount = connections.length;\n \n // Preload fonts (used for text if provided)\n let fontLoaded = false;\n \n for (let i = 0; i < connections.length; i++) {\n try {\n const { startNodeId: originalStartId, endNodeId: originalEndId, text } = connections[i];\n let startId = originalStartId;\n let endId = originalEndId;\n\n // Check and potentially replace start node ID\n if (startId.includes(';')) {\n console.log(`Nested start node detected: ${startId}. Creating cursor node.`);\n const cursorResult = await createCursorNode(startId);\n if (!cursorResult || !cursorResult.id) {\n throw new Error(`Failed to create cursor node for nested start node: ${startId}`);\n }\n startId = cursorResult.id; \n } \n \n const startNode = await figma.getNodeByIdAsync(startId);\n if (!startNode) throw new Error(`Start node not found with ID: ${startId}`);\n\n // Check and potentially replace end node ID\n if (endId.includes(';')) {\n console.log(`Nested end node detected: ${endId}. Creating cursor node.`);\n const cursorResult = await createCursorNode(endId);\n if (!cursorResult || !cursorResult.id) {\n throw new Error(`Failed to create cursor node for nested end node: ${endId}`);\n }\n endId = cursorResult.id;\n }\n const endNode = await figma.getNodeByIdAsync(endId);\n if (!endNode) throw new Error(`End node not found with ID: ${endId}`);\n\n \n // Clone the default connector\n const clonedConnector = defaultConnector.clone();\n \n // Update connector name using potentially replaced node names\n clonedConnector.name = `TTF_Connector/${startNode.id}/${endNode.id}`;\n \n // Set start and end points using potentially replaced IDs\n clonedConnector.connectorStart = {\n endpointNodeId: startId,\n magnet: 'AUTO'\n };\n \n clonedConnector.connectorEnd = {\n endpointNodeId: endId,\n magnet: 'AUTO'\n };\n \n // Add text (if provided)\n if (text) {\n try {\n // Try to load the necessary fonts\n try {\n // First check if default connector has font and use the same\n if (defaultConnector.text && defaultConnector.text.fontName) {\n const fontName = defaultConnector.text.fontName;\n await figma.loadFontAsync(fontName);\n clonedConnector.text.fontName = fontName;\n } else {\n // Try default Inter font\n await figma.loadFontAsync({ family: \"Inter\", style: \"Regular\" });\n }\n } catch (fontError) {\n // If first font load fails, try another font style\n try {\n await figma.loadFontAsync({ family: \"Inter\", style: \"Medium\" });\n } catch (mediumFontError) {\n // If second font fails, try system font\n try {\n await figma.loadFontAsync({ family: \"System\", style: \"Regular\" });\n } catch (systemFontError) {\n // If all font loading attempts fail, throw error\n throw new Error(`Failed to load any font: ${fontError.message}`);\n }\n }\n }\n \n // Set the text\n clonedConnector.text.characters = text;\n } catch (textError) {\n console.error(\"Error setting text:\", textError);\n // Continue with connection even if text setting fails\n results.push({\n id: clonedConnector.id,\n startNodeId: startNodeId,\n endNodeId: endNodeId,\n text: \"\",\n textError: textError.message\n });\n \n // Continue to next connection\n continue;\n }\n }\n \n // Add to results (using the *original* IDs for reference if needed)\n results.push({\n id: clonedConnector.id,\n originalStartNodeId: originalStartId,\n originalEndNodeId: originalEndId,\n usedStartNodeId: startId, // ID actually used for connection\n usedEndNodeId: endId, // ID actually used for connection\n text: text || \"\"\n });\n \n // Update progress\n processedCount++;\n sendProgressUpdate(\n commandId,\n \"create_connections\",\n \"in_progress\",\n processedCount / totalCount,\n totalCount,\n processedCount,\n `Created connection ${processedCount}/${totalCount}`\n );\n \n } catch (error) {\n console.error(\"Error creating connection\", error);\n // Continue processing remaining connections even if an error occurs\n processedCount++;\n sendProgressUpdate(\n commandId,\n \"create_connections\",\n \"in_progress\",\n processedCount / totalCount,\n totalCount,\n processedCount,\n `Error creating connection: ${error.message}`\n );\n \n results.push({\n error: error.message,\n connectionInfo: connections[i]\n });\n }\n }\n \n // Completion update\n sendProgressUpdate(\n commandId,\n \"create_connections\",\n \"completed\",\n 1,\n totalCount,\n totalCount,\n `Completed creating ${results.length} connections`\n );\n \n return {\n success: true,\n count: results.length,\n connections: results\n };\n}\n", "middle_code": "async (replacement) => {\n if (!replacement.nodeId || replacement.text === undefined) {\n console.error(`Missing nodeId or text for replacement`);\n return {\n success: false,\n nodeId: replacement.nodeId || \"unknown\",\n error: \"Missing nodeId or text in replacement entry\",\n };\n }\n try {\n console.log(\n `Attempting to replace text in node: ${replacement.nodeId}`\n );\n const textNode = await figma.getNodeByIdAsync(replacement.nodeId);\n if (!textNode) {\n console.error(`Text node not found: ${replacement.nodeId}`);\n return {\n success: false,\n nodeId: replacement.nodeId,\n error: `Node not found: ${replacement.nodeId}`,\n };\n }\n if (textNode.type !== \"TEXT\") {\n console.error(\n `Node is not a text node: ${replacement.nodeId} (type: ${textNode.type})`\n );\n return {\n success: false,\n nodeId: replacement.nodeId,\n error: `Node is not a text node: ${replacement.nodeId} (type: ${textNode.type})`,\n };\n }\n const originalText = textNode.characters;\n console.log(`Original text: \"${originalText}\"`);\n console.log(`Will translate to: \"${replacement.text}\"`);\n let originalFills;\n try {\n originalFills = JSON.parse(JSON.stringify(textNode.fills));\n textNode.fills = [\n {\n type: \"SOLID\",\n color: { r: 1, g: 0.5, b: 0 },\n opacity: 0.3,\n },\n ];\n } catch (highlightErr) {\n console.error(\n `Error highlighting text node: ${highlightErr.message}`\n );\n }\n await setTextContent({\n nodeId: replacement.nodeId,\n text: replacement.text,\n });\n if (originalFills) {\n try {\n await delay(500);\n textNode.fills = originalFills;\n } catch (restoreErr) {\n console.error(`Error restoring fills: ${restoreErr.message}`);\n }\n }\n console.log(\n `Successfully replaced text in node: ${replacement.nodeId}`\n );\n return {\n success: true,\n nodeId: replacement.nodeId,\n originalText: originalText,\n translatedText: replacement.text,\n };\n } catch (error) {\n console.error(\n `Error replacing text in node ${replacement.nodeId}: ${error.message}`\n );\n return {\n success: false,\n nodeId: replacement.nodeId,\n error: `Error applying replacement: ${error.message}`,\n };\n }\n }", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "javascript", "sub_task_type": null}, "context_code": [["/cursor-talk-to-figma-mcp/src/cursor_mcp_plugin/setcharacters.js", "function uniqBy(arr, predicate) {\n const cb = typeof predicate === \"function\" ? predicate : (o) => o[predicate];\n return [\n ...arr\n .reduce((map, item) => {\n const key = item === null || item === undefined ? item : cb(item);\n\n map.has(key) || map.set(key, item);\n\n return map;\n }, new Map())\n .values(),\n ];\n}\nexport const setCharacters = async (node, characters, options) => {\n const fallbackFont = options?.fallbackFont || {\n family: \"Roboto\",\n style: \"Regular\",\n };\n try {\n if (node.fontName === figma.mixed) {\n if (options?.smartStrategy === \"prevail\") {\n const fontHashTree = {};\n for (let i = 1; i < node.characters.length; i++) {\n const charFont = node.getRangeFontName(i - 1, i);\n const key = `${charFont.family}::${charFont.style}`;\n fontHashTree[key] = fontHashTree[key] ? fontHashTree[key] + 1 : 1;\n }\n const prevailedTreeItem = Object.entries(fontHashTree).sort(\n (a, b) => b[1] - a[1]\n )[0];\n const [family, style] = prevailedTreeItem[0].split(\"::\");\n const prevailedFont = {\n family,\n style,\n };\n await figma.loadFontAsync(prevailedFont);\n node.fontName = prevailedFont;\n } else if (options?.smartStrategy === \"strict\") {\n return setCharactersWithStrictMatchFont(node, characters, fallbackFont);\n } else if (options?.smartStrategy === \"experimental\") {\n return setCharactersWithSmartMatchFont(node, characters, fallbackFont);\n } else {\n const firstCharFont = node.getRangeFontName(0, 1);\n await figma.loadFontAsync(firstCharFont);\n node.fontName = firstCharFont;\n }\n } else {\n await figma.loadFontAsync({\n family: node.fontName.family,\n style: node.fontName.style,\n });\n }\n } catch (err) {\n console.warn(\n `Failed to load \"${node.fontName[\"family\"]} ${node.fontName[\"style\"]}\" font and replaced with fallback \"${fallbackFont.family} ${fallbackFont.style}\"`,\n err\n );\n await figma.loadFontAsync(fallbackFont);\n node.fontName = fallbackFont;\n }\n try {\n node.characters = characters;\n return true;\n } catch (err) {\n console.warn(`Failed to set characters. Skipped.`, err);\n return false;\n }\n};\n\nconst setCharactersWithStrictMatchFont = async (\n node,\n characters,\n fallbackFont\n) => {\n const fontHashTree = {};\n for (let i = 1; i < node.characters.length; i++) {\n const startIdx = i - 1;\n const startCharFont = node.getRangeFontName(startIdx, i);\n const startCharFontVal = `${startCharFont.family}::${startCharFont.style}`;\n while (i < node.characters.length) {\n i++;\n const charFont = node.getRangeFontName(i - 1, i);\n if (startCharFontVal !== `${charFont.family}::${charFont.style}`) {\n break;\n }\n }\n fontHashTree[`${startIdx}_${i}`] = startCharFontVal;\n }\n await figma.loadFontAsync(fallbackFont);\n node.fontName = fallbackFont;\n node.characters = characters;\n console.log(fontHashTree);\n await Promise.all(\n Object.keys(fontHashTree).map(async (range) => {\n console.log(range, fontHashTree[range]);\n const [start, end] = range.split(\"_\");\n const [family, style] = fontHashTree[range].split(\"::\");\n const matchedFont = {\n family,\n style,\n };\n await figma.loadFontAsync(matchedFont);\n return node.setRangeFontName(Number(start), Number(end), matchedFont);\n })\n );\n return true;\n};\n\nconst getDelimiterPos = (str, delimiter, startIdx = 0, endIdx = str.length) => {\n const indices = [];\n let temp = startIdx;\n for (let i = startIdx; i < endIdx; i++) {\n if (\n str[i] === delimiter &&\n i + startIdx !== endIdx &&\n temp !== i + startIdx\n ) {\n indices.push([temp, i + startIdx]);\n temp = i + startIdx + 1;\n }\n }\n temp !== endIdx && indices.push([temp, endIdx]);\n return indices.filter(Boolean);\n};\n\nconst buildLinearOrder = (node) => {\n const fontTree = [];\n const newLinesPos = getDelimiterPos(node.characters, \"\\n\");\n newLinesPos.forEach(([newLinesRangeStart, newLinesRangeEnd], n) => {\n const newLinesRangeFont = node.getRangeFontName(\n newLinesRangeStart,\n newLinesRangeEnd\n );\n if (newLinesRangeFont === figma.mixed) {\n const spacesPos = getDelimiterPos(\n node.characters,\n \" \",\n newLinesRangeStart,\n newLinesRangeEnd\n );\n spacesPos.forEach(([spacesRangeStart, spacesRangeEnd], s) => {\n const spacesRangeFont = node.getRangeFontName(\n spacesRangeStart,\n spacesRangeEnd\n );\n if (spacesRangeFont === figma.mixed) {\n const spacesRangeFont = node.getRangeFontName(\n spacesRangeStart,\n spacesRangeStart[0]\n );\n fontTree.push({\n start: spacesRangeStart,\n delimiter: \" \",\n family: spacesRangeFont.family,\n style: spacesRangeFont.style,\n });\n } else {\n fontTree.push({\n start: spacesRangeStart,\n delimiter: \" \",\n family: spacesRangeFont.family,\n style: spacesRangeFont.style,\n });\n }\n });\n } else {\n fontTree.push({\n start: newLinesRangeStart,\n delimiter: \"\\n\",\n family: newLinesRangeFont.family,\n style: newLinesRangeFont.style,\n });\n }\n });\n return fontTree\n .sort((a, b) => +a.start - +b.start)\n .map(({ family, style, delimiter }) => ({ family, style, delimiter }));\n};\n\nconst setCharactersWithSmartMatchFont = async (\n node,\n characters,\n fallbackFont\n) => {\n const rangeTree = buildLinearOrder(node);\n const fontsToLoad = uniqBy(\n rangeTree,\n ({ family, style }) => `${family}::${style}`\n ).map(({ family, style }) => ({\n family,\n style,\n }));\n\n await Promise.all([...fontsToLoad, fallbackFont].map(figma.loadFontAsync));\n\n node.fontName = fallbackFont;\n node.characters = characters;\n\n let prevPos = 0;\n rangeTree.forEach(({ family, style, delimiter }) => {\n if (prevPos < node.characters.length) {\n const delimeterPos = node.characters.indexOf(delimiter, prevPos);\n const endPos =\n delimeterPos > prevPos ? delimeterPos : node.characters.length;\n const matchedFont = {\n family,\n style,\n };\n node.setRangeFontName(prevPos, endPos, matchedFont);\n prevPos = endPos + 1;\n }\n });\n return true;\n};\n"]], "task_instance_info": {"created_time": "2025-08-20 23:58:37", "created_task_model": "DeepSeek-R1", "function_skeleton": "async (replacement) => {}", "code_description": "This code segment functions to: Process multiple text replacement requests in parallel batches, validate target node compatibility for text modifications, apply textual content updates while providing temporary visual feedback, and track operation progress with error handling for individual replacements."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```javascript\n[TASK_BEGIN]\n async (replacement) => {\n try {\n const { nodeId: targetNodeId, text: newText } = replacement;\n const node = await figma.getNodeByIdAsync(targetNodeId);\n\n if (!node) {\n console.error(`Text node not found: ${targetNodeId}`);\n return {\n success: false,\n nodeId: targetNodeId,\n error: `Node not found`\n };\n }\n\n if (node.type !== \"TEXT\") {\n console.error(`Node is not text: ${targetNodeId} (${node.type})`);\n return {\n success: false,\n nodeId: targetNodeId,\n error: `Not a text node`\n };\n }\n\n // Load font before setting text\n await figma.loadFontAsync(node.fontName);\n \n // Set text content safely\n await setCharacters(node, newText, {\n smartStrategy: \"experimental\",\n fallbackFont: { family: \"Inter\", style: \"Regular\" }\n });\n\n return {\n success: true,\n nodeId: targetNodeId,\n characters: node.characters\n };\n } catch (error) {\n console.error(`Error processing replacement:`, error);\n return {\n success: false,\n nodeId: replacement.nodeId,\n error: error.message\n };\n }\n })\n[TASK_END]\n```", "inference_time": "2025-08-20 23-59-21"}, "editdistance_info": {"edit_distance": 25.0, "calculate_time": "2025-08-20 23:59:21", "true_code_clean": "async (replacement) => {\n if (!replacement.nodeId || replacement.text === undefined) {\n console.error(`Missing nodeId or text for replacement`);\n return {\n success: false,\n nodeId: replacement.nodeId || \"unknown\",\n error: \"Missing nodeId or text in replacement entry\",\n };\n }\n try {\n console.log(\n `Attempting to replace text in node: ${replacement.nodeId}`\n );\n const textNode = await figma.getNodeByIdAsync(replacement.nodeId);\n if (!textNode) {\n console.error(`Text node not found: ${replacement.nodeId}`);\n return {\n success: false,\n nodeId: replacement.nodeId,\n error: `Node not found: ${replacement.nodeId}`,\n };\n }\n if (textNode.type !== \"TEXT\") {\n console.error(\n `Node is not a text node: ${replacement.nodeId} (type: ${textNode.type})`\n );\n return {\n success: false,\n nodeId: replacement.nodeId,\n error: `Node is not a text node: ${replacement.nodeId} (type: ${textNode.type})`,\n };\n }\n const originalText = textNode.characters;\n console.log(`Original text: \"${originalText}\"`);\n console.log(`Will translate to: \"${replacement.text}\"`);\n let originalFills;\n try {\n originalFills = JSON.parse(JSON.stringify(textNode.fills));\n textNode.fills = [\n {\n type: \"SOLID\",\n color: { r: 1, g: 0.5, b: 0 },\n opacity: 0.3,\n },\n ];\n } catch (highlightErr) {\n console.error(\n `Error highlighting text node: ${highlightErr.message}`\n );\n }\n await setTextContent({\n nodeId: replacement.nodeId,\n text: replacement.text,\n });\n if (originalFills) {\n try {\n await delay(500);\n textNode.fills = originalFills;\n } catch (restoreErr) {\n console.error(`Error restoring fills: ${restoreErr.message}`);\n }\n }\n console.log(\n `Successfully replaced text in node: ${replacement.nodeId}`\n );\n return {\n success: true,\n nodeId: replacement.nodeId,\n originalText: originalText,\n translatedText: replacement.text,\n };\n } catch (error) {\n console.error(\n `Error replacing text in node ${replacement.nodeId}: ${error.message}`\n );\n return {\n success: false,\n nodeId: replacement.nodeId,\n error: `Error applying replacement: ${error.message}`,\n };\n }\n }", "predict_code_clean": "async (replacement) => {\n try {\n const { nodeId: targetNodeId, text: newText } = replacement;\n const node = await figma.getNodeByIdAsync(targetNodeId);\n if (!node) {\n console.error(`Text node not found: ${targetNodeId}`);\n return {\n success: false,\n nodeId: targetNodeId,\n error: `Node not found`\n };\n }\n if (node.type !== \"TEXT\") {\n console.error(`Node is not text: ${targetNodeId} (${node.type})`);\n return {\n success: false,\n nodeId: targetNodeId,\n error: `Not a text node`\n };\n }\n await figma.loadFontAsync(node.fontName);\n await setCharacters(node, newText, {\n smartStrategy: \"experimental\",\n fallbackFont: { family: \"Inter\", style: \"Regular\" }\n });\n return {\n success: true,\n nodeId: targetNodeId,\n characters: node.characters\n };\n } catch (error) {\n console.error(`Error processing replacement:`, error);\n return {\n success: false,\n nodeId: replacement.nodeId,\n error: error.message\n };\n }\n })"}} {"repo_name": "cursor-talk-to-figma-mcp", "file_name": "/cursor-talk-to-figma-mcp/src/cursor_mcp_plugin/code.js", "inference_info": {"prefix_code": "// This is the main code file for the Cursor MCP Figma plugin\n// It handles Figma API commands\n\n// Plugin state\nconst state = {\n serverPort: 3055, // Default port\n};\n\n\n// Helper function for progress updates\nfunction sendProgressUpdate(\n commandId,\n commandType,\n status,\n progress,\n totalItems,\n processedItems,\n message,\n payload = null\n) {\n const update = {\n type: \"command_progress\",\n commandId,\n commandType,\n status,\n progress,\n totalItems,\n processedItems,\n message,\n timestamp: Date.now(),\n };\n\n // Add optional chunk information if present\n if (payload) {\n if (\n payload.currentChunk !== undefined &&\n payload.totalChunks !== undefined\n ) {\n update.currentChunk = payload.currentChunk;\n update.totalChunks = payload.totalChunks;\n update.chunkSize = payload.chunkSize;\n }\n update.payload = payload;\n }\n\n // Send to UI\n figma.ui.postMessage(update);\n console.log(`Progress update: ${status} - ${progress}% - ${message}`);\n\n return update;\n}\n\n// Show UI\nfigma.showUI(__html__, { width: 350, height: 450 });\n\n// Plugin commands from UI\nfigma.ui.onmessage = async (msg) => {\n switch (msg.type) {\n case \"update-settings\":\n updateSettings(msg);\n break;\n case \"notify\":\n figma.notify(msg.message);\n break;\n case \"close-plugin\":\n figma.closePlugin();\n break;\n case \"execute-command\":\n // Execute commands received from UI (which gets them from WebSocket)\n try {\n const result = await handleCommand(msg.command, msg.params);\n // Send result back to UI\n figma.ui.postMessage({\n type: \"command-result\",\n id: msg.id,\n result,\n });\n } catch (error) {\n figma.ui.postMessage({\n type: \"command-error\",\n id: msg.id,\n error: error.message || \"Error executing command\",\n });\n }\n break;\n }\n};\n\n// Listen for plugin commands from menu\nfigma.on(\"run\", ({ command }) => {\n figma.ui.postMessage({ type: \"auto-connect\" });\n});\n\n// Update plugin settings\nfunction updateSettings(settings) {\n if (settings.serverPort) {\n state.serverPort = settings.serverPort;\n }\n\n figma.clientStorage.setAsync(\"settings\", {\n serverPort: state.serverPort,\n });\n}\n\n// Handle commands from UI\nasync function handleCommand(command, params) {\n switch (command) {\n case \"get_document_info\":\n return await getDocumentInfo();\n case \"get_selection\":\n return await getSelection();\n case \"get_node_info\":\n if (!params || !params.nodeId) {\n throw new Error(\"Missing nodeId parameter\");\n }\n return await getNodeInfo(params.nodeId);\n case \"get_nodes_info\":\n if (!params || !params.nodeIds || !Array.isArray(params.nodeIds)) {\n throw new Error(\"Missing or invalid nodeIds parameter\");\n }\n return await getNodesInfo(params.nodeIds);\n case \"read_my_design\":\n return await readMyDesign();\n case \"create_rectangle\":\n return await createRectangle(params);\n case \"create_frame\":\n return await createFrame(params);\n case \"create_text\":\n return await createText(params);\n case \"set_fill_color\":\n return await setFillColor(params);\n case \"set_stroke_color\":\n return await setStrokeColor(params);\n case \"move_node\":\n return await moveNode(params);\n case \"resize_node\":\n return await resizeNode(params);\n case \"delete_node\":\n return await deleteNode(params);\n case \"delete_multiple_nodes\":\n return await deleteMultipleNodes(params);\n case \"get_styles\":\n return await getStyles();\n case \"get_local_components\":\n return await getLocalComponents();\n // case \"get_team_components\":\n // return await getTeamComponents();\n case \"create_component_instance\":\n return await createComponentInstance(params);\n case \"export_node_as_image\":\n return await exportNodeAsImage(params);\n case \"set_corner_radius\":\n return await setCornerRadius(params);\n case \"set_text_content\":\n return await setTextContent(params);\n case \"clone_node\":\n return await cloneNode(params);\n case \"scan_text_nodes\":\n return await scanTextNodes(params);\n case \"set_multiple_text_contents\":\n return await setMultipleTextContents(params);\n case \"get_annotations\":\n return await getAnnotations(params);\n case \"set_annotation\":\n return await setAnnotation(params);\n case \"scan_nodes_by_types\":\n return await scanNodesByTypes(params);\n case \"set_multiple_annotations\":\n return await setMultipleAnnotations(params);\n case \"get_instance_overrides\":\n // Check if instanceNode parameter is provided\n if (params && params.instanceNodeId) {\n // Get the instance node by ID\n const instanceNode = await figma.getNodeByIdAsync(params.instanceNodeId);\n if (!instanceNode) {\n throw new Error(`Instance node not found with ID: ${params.instanceNodeId}`);\n }\n return await getInstanceOverrides(instanceNode);\n }\n // Call without instance node if not provided\n return await getInstanceOverrides();\n\n case \"set_instance_overrides\":\n // Check if instanceNodeIds parameter is provided\n if (params && params.targetNodeIds) {\n // Validate that targetNodeIds is an array\n if (!Array.isArray(params.targetNodeIds)) {\n throw new Error(\"targetNodeIds must be an array\");\n }\n\n // Get the instance nodes by IDs\n const targetNodes = await getValidTargetInstances(params.targetNodeIds);\n if (!targetNodes.success) {\n figma.notify(targetNodes.message);\n return { success: false, message: targetNodes.message };\n }\n\n if (params.sourceInstanceId) {\n\n // get source instance data\n let sourceInstanceData = null;\n sourceInstanceData = await getSourceInstanceData(params.sourceInstanceId);\n\n if (!sourceInstanceData.success) {\n figma.notify(sourceInstanceData.message);\n return { success: false, message: sourceInstanceData.message };\n }\n return await setInstanceOverrides(targetNodes.targetInstances, sourceInstanceData);\n } else {\n throw new Error(\"Missing sourceInstanceId parameter\");\n }\n }\n case \"set_layout_mode\":\n return await setLayoutMode(params);\n case \"set_padding\":\n return await setPadding(params);\n case \"set_axis_align\":\n return await setAxisAlign(params);\n case \"set_layout_sizing\":\n return await setLayoutSizing(params);\n case \"set_item_spacing\":\n return await setItemSpacing(params);\n case \"get_reactions\":\n if (!params || !params.nodeIds || !Array.isArray(params.nodeIds)) {\n throw new Error(\"Missing or invalid nodeIds parameter\");\n }\n return await getReactions(params.nodeIds); \n case \"set_default_connector\":\n return await setDefaultConnector(params);\n case \"create_connections\":\n return await createConnections(params);\n default:\n throw new Error(`Unknown command: ${command}`);\n }\n}\n\n// Command implementations\n\nasync function getDocumentInfo() {\n await figma.currentPage.loadAsync();\n const page = figma.currentPage;\n return {\n name: page.name,\n id: page.id,\n type: page.type,\n children: page.children.map((node) => ({\n id: node.id,\n name: node.name,\n type: node.type,\n })),\n currentPage: {\n id: page.id,\n name: page.name,\n childCount: page.children.length,\n },\n pages: [\n {\n id: page.id,\n name: page.name,\n childCount: page.children.length,\n },\n ],\n };\n}\n\nasync function getSelection() {\n return {\n selectionCount: figma.currentPage.selection.length,\n selection: figma.currentPage.selection.map((node) => ({\n id: node.id,\n name: node.name,\n type: node.type,\n visible: node.visible,\n })),\n };\n}\n\nfunction rgbaToHex(color) {\n var r = Math.round(color.r * 255);\n var g = Math.round(color.g * 255);\n var b = Math.round(color.b * 255);\n var a = color.a !== undefined ? Math.round(color.a * 255) : 255;\n\n if (a === 255) {\n return (\n \"#\" +\n [r, g, b]\n .map((x) => {\n return x.toString(16).padStart(2, \"0\");\n })\n .join(\"\")\n );\n }\n\n return (\n \"#\" +\n [r, g, b, a]\n .map((x) => {\n return x.toString(16).padStart(2, \"0\");\n })\n .join(\"\")\n );\n}\n\nfunction filterFigmaNode(node) {\n if (node.type === \"VECTOR\") {\n return null;\n }\n\n var filtered = {\n id: node.id,\n name: node.name,\n type: node.type,\n };\n\n if (node.fills && node.fills.length > 0) {\n filtered.fills = node.fills.map((fill) => {\n var processedFill = Object.assign({}, fill);\n delete processedFill.boundVariables;\n delete processedFill.imageRef;\n\n if (processedFill.gradientStops) {\n processedFill.gradientStops = processedFill.gradientStops.map(\n (stop) => {\n var processedStop = Object.assign({}, stop);\n if (processedStop.color) {\n processedStop.color = rgbaToHex(processedStop.color);\n }\n delete processedStop.boundVariables;\n return processedStop;\n }\n );\n }\n\n if (processedFill.color) {\n processedFill.color = rgbaToHex(processedFill.color);\n }\n\n return processedFill;\n });\n }\n\n if (node.strokes && node.strokes.length > 0) {\n filtered.strokes = node.strokes.map((stroke) => {\n var processedStroke = Object.assign({}, stroke);\n delete processedStroke.boundVariables;\n if (processedStroke.color) {\n processedStroke.color = rgbaToHex(processedStroke.color);\n }\n return processedStroke;\n });\n }\n\n if (node.cornerRadius !== undefined) {\n filtered.cornerRadius = node.cornerRadius;\n }\n\n if (node.absoluteBoundingBox) {\n filtered.absoluteBoundingBox = node.absoluteBoundingBox;\n }\n\n if (node.characters) {\n filtered.characters = node.characters;\n }\n\n if (node.style) {\n filtered.style = {\n fontFamily: node.style.fontFamily,\n fontStyle: node.style.fontStyle,\n fontWeight: node.style.fontWeight,\n fontSize: node.style.fontSize,\n textAlignHorizontal: node.style.textAlignHorizontal,\n letterSpacing: node.style.letterSpacing,\n lineHeightPx: node.style.lineHeightPx,\n };\n }\n\n if (node.children) {\n filtered.children = node.children\n .map((child) => {\n return filterFigmaNode(child);\n })\n .filter((child) => {\n return child !== null;\n });\n }\n\n return filtered;\n}\n\nasync function getNodeInfo(nodeId) {\n const node = await figma.getNodeByIdAsync(nodeId);\n\n if (!node) {\n throw new Error(`Node not found with ID: ${nodeId}`);\n }\n\n const response = await node.exportAsync({\n format: \"JSON_REST_V1\",\n });\n\n return filterFigmaNode(response.document);\n}\n\nasync function getNodesInfo(nodeIds) {\n try {\n // Load all nodes in parallel\n const nodes = await Promise.all(\n nodeIds.map((id) => figma.getNodeByIdAsync(id))\n );\n\n // Filter out any null values (nodes that weren't found)\n const validNodes = nodes.filter((node) => node !== null);\n\n // Export all valid nodes in parallel\n const responses = await Promise.all(\n validNodes.map(async (node) => {\n const response = await node.exportAsync({\n format: \"JSON_REST_V1\",\n });\n return {\n nodeId: node.id,\n document: filterFigmaNode(response.document),\n };\n })\n );\n\n return responses;\n } catch (error) {\n throw new Error(`Error getting nodes info: ${error.message}`);\n }\n}\n\nasync function getReactions(nodeIds) {\n try {\n const commandId = generateCommandId();\n sendProgressUpdate(\n commandId,\n \"get_reactions\",\n \"started\",\n 0,\n nodeIds.length,\n 0,\n `Starting deep search for reactions in ${nodeIds.length} nodes and their children`\n );\n\n // Function to find nodes with reactions from the node and all its children\n async function findNodesWithReactions(node, processedNodes = new Set(), depth = 0, results = []) {\n // Skip already processed nodes (prevent circular references)\n if (processedNodes.has(node.id)) {\n return results;\n }\n \n processedNodes.add(node.id);\n \n // Check if the current node has reactions\n let filteredReactions = [];\n if (node.reactions && node.reactions.length > 0) {\n // Filter out reactions with navigation === 'CHANGE_TO'\n filteredReactions = node.reactions.filter(r => {\n // Some reactions may have action or actions array\n if (r.action && r.action.navigation === 'CHANGE_TO') return false;\n if (Array.isArray(r.actions)) {\n // If any action in actions array is CHANGE_TO, exclude\n return !r.actions.some(a => a.navigation === 'CHANGE_TO');\n }\n return true;\n });\n }\n const hasFilteredReactions = filteredReactions.length > 0;\n \n // If the node has filtered reactions, add it to results and apply highlight effect\n if (hasFilteredReactions) {\n results.push({\n id: node.id,\n name: node.name,\n type: node.type,\n depth: depth,\n hasReactions: true,\n reactions: filteredReactions,\n path: getNodePath(node)\n });\n // Apply highlight effect (orange border)\n await highlightNodeWithAnimation(node);\n }\n \n // If node has children, recursively search them\n if (node.children) {\n for (const child of node.children) {\n await findNodesWithReactions(child, processedNodes, depth + 1, results);\n }\n }\n \n return results;\n }\n \n // Function to apply animated highlight effect to a node\n async function highlightNodeWithAnimation(node) {\n // Save original stroke properties\n const originalStrokeWeight = node.strokeWeight;\n const originalStrokes = node.strokes ? [...node.strokes] : [];\n \n try {\n // Apply orange border stroke\n node.strokeWeight = 4;\n node.strokes = [{\n type: 'SOLID',\n color: { r: 1, g: 0.5, b: 0 }, // Orange color\n opacity: 0.8\n }];\n \n // Set timeout for animation effect (restore to original after 1.5 seconds)\n setTimeout(() => {\n try {\n // Restore original stroke properties\n node.strokeWeight = originalStrokeWeight;\n node.strokes = originalStrokes;\n } catch (restoreError) {\n console.error(`Error restoring node stroke: ${restoreError.message}`);\n }\n }, 1500);\n } catch (highlightError) {\n console.error(`Error highlighting node: ${highlightError.message}`);\n // Continue even if highlighting fails\n }\n }\n \n // Get node hierarchy path as a string\n function getNodePath(node) {\n const path = [];\n let current = node;\n \n while (current && current.parent) {\n path.unshift(current.name);\n current = current.parent;\n }\n \n return path.join(' > ');\n }\n\n // Array to store all results\n let allResults = [];\n let processedCount = 0;\n const totalCount = nodeIds.length;\n \n // Iterate through each node and its children to search for reactions\n for (let i = 0; i < nodeIds.length; i++) {\n try {\n const nodeId = nodeIds[i];\n const node = await figma.getNodeByIdAsync(nodeId);\n \n if (!node) {\n processedCount++;\n sendProgressUpdate(\n commandId,\n \"get_reactions\",\n \"in_progress\",\n processedCount / totalCount,\n totalCount,\n processedCount,\n `Node not found: ${nodeId}`\n );\n continue;\n }\n \n // Search for reactions in the node and its children\n const processedNodes = new Set();\n const nodeResults = await findNodesWithReactions(node, processedNodes);\n \n // Add results\n allResults = allResults.concat(nodeResults);\n \n // Update progress\n processedCount++;\n sendProgressUpdate(\n commandId,\n \"get_reactions\",\n \"in_progress\",\n processedCount / totalCount,\n totalCount,\n processedCount,\n `Processed node ${processedCount}/${totalCount}, found ${nodeResults.length} nodes with reactions`\n );\n } catch (error) {\n processedCount++;\n sendProgressUpdate(\n commandId,\n \"get_reactions\",\n \"in_progress\",\n processedCount / totalCount,\n totalCount,\n processedCount,\n `Error processing node: ${error.message}`\n );\n }\n }\n\n // Completion update\n sendProgressUpdate(\n commandId,\n \"get_reactions\",\n \"completed\",\n 1,\n totalCount,\n totalCount,\n `Completed deep search: found ${allResults.length} nodes with reactions.`\n );\n\n return {\n nodesCount: nodeIds.length,\n nodesWithReactions: allResults.length,\n nodes: allResults\n };\n } catch (error) {\n throw new Error(`Failed to get reactions: ${error.message}`);\n }\n}\n\nasync function readMyDesign() {\n try {\n // Load all selected nodes in parallel\n const nodes = await Promise.all(\n figma.currentPage.selection.map((node) => figma.getNodeByIdAsync(node.id))\n );\n\n // Filter out any null values (nodes that weren't found)\n const validNodes = nodes.filter((node) => node !== null);\n\n // Export all valid nodes in parallel\n const responses = await Promise.all(\n validNodes.map(async (node) => {\n const response = await node.exportAsync({\n format: \"JSON_REST_V1\",\n });\n return {\n nodeId: node.id,\n document: filterFigmaNode(response.document),\n };\n })\n );\n\n return responses;\n } catch (error) {\n throw new Error(`Error getting nodes info: ${error.message}`);\n }\n}\n\nasync function createRectangle(params) {\n const {\n x = 0,\n y = 0,\n width = 100,\n height = 100,\n name = \"Rectangle\",\n parentId,\n } = params || {};\n\n const rect = figma.createRectangle();\n rect.x = x;\n rect.y = y;\n rect.resize(width, height);\n rect.name = name;\n\n // If parentId is provided, append to that node, otherwise append to current page\n if (parentId) {\n const parentNode = await figma.getNodeByIdAsync(parentId);\n if (!parentNode) {\n throw new Error(`Parent node not found with ID: ${parentId}`);\n }\n if (!(\"appendChild\" in parentNode)) {\n throw new Error(`Parent node does not support children: ${parentId}`);\n }\n parentNode.appendChild(rect);\n } else {\n figma.currentPage.appendChild(rect);\n }\n\n return {\n id: rect.id,\n name: rect.name,\n x: rect.x,\n y: rect.y,\n width: rect.width,\n height: rect.height,\n parentId: rect.parent ? rect.parent.id : undefined,\n };\n}\n\nasync function createFrame(params) {\n const {\n x = 0,\n y = 0,\n width = 100,\n height = 100,\n name = \"Frame\",\n parentId,\n fillColor,\n strokeColor,\n strokeWeight,\n layoutMode = \"NONE\",\n layoutWrap = \"NO_WRAP\",\n paddingTop = 10,\n paddingRight = 10,\n paddingBottom = 10,\n paddingLeft = 10,\n primaryAxisAlignItems = \"MIN\",\n counterAxisAlignItems = \"MIN\",\n layoutSizingHorizontal = \"FIXED\",\n layoutSizingVertical = \"FIXED\",\n itemSpacing = 0,\n } = params || {};\n\n const frame = figma.createFrame();\n frame.x = x;\n frame.y = y;\n frame.resize(width, height);\n frame.name = name;\n\n // Set layout mode if provided\n if (layoutMode !== \"NONE\") {\n frame.layoutMode = layoutMode;\n frame.layoutWrap = layoutWrap;\n\n // Set padding values only when layoutMode is not NONE\n frame.paddingTop = paddingTop;\n frame.paddingRight = paddingRight;\n frame.paddingBottom = paddingBottom;\n frame.paddingLeft = paddingLeft;\n\n // Set axis alignment only when layoutMode is not NONE\n frame.primaryAxisAlignItems = primaryAxisAlignItems;\n frame.counterAxisAlignItems = counterAxisAlignItems;\n\n // Set layout sizing only when layoutMode is not NONE\n frame.layoutSizingHorizontal = layoutSizingHorizontal;\n frame.layoutSizingVertical = layoutSizingVertical;\n\n // Set item spacing only when layoutMode is not NONE\n frame.itemSpacing = itemSpacing;\n }\n\n // Set fill color if provided\n if (fillColor) {\n const paintStyle = {\n type: \"SOLID\",\n color: {\n r: parseFloat(fillColor.r) || 0,\n g: parseFloat(fillColor.g) || 0,\n b: parseFloat(fillColor.b) || 0,\n },\n opacity: parseFloat(fillColor.a) || 1,\n };\n frame.fills = [paintStyle];\n }\n\n // Set stroke color and weight if provided\n if (strokeColor) {\n const strokeStyle = {\n type: \"SOLID\",\n color: {\n r: parseFloat(strokeColor.r) || 0,\n g: parseFloat(strokeColor.g) || 0,\n b: parseFloat(strokeColor.b) || 0,\n },\n opacity: parseFloat(strokeColor.a) || 1,\n };\n frame.strokes = [strokeStyle];\n }\n\n // Set stroke weight if provided\n if (strokeWeight !== undefined) {\n frame.strokeWeight = strokeWeight;\n }\n\n // If parentId is provided, append to that node, otherwise append to current page\n if (parentId) {\n const parentNode = await figma.getNodeByIdAsync(parentId);\n if (!parentNode) {\n throw new Error(`Parent node not found with ID: ${parentId}`);\n }\n if (!(\"appendChild\" in parentNode)) {\n throw new Error(`Parent node does not support children: ${parentId}`);\n }\n parentNode.appendChild(frame);\n } else {\n figma.currentPage.appendChild(frame);\n }\n\n return {\n id: frame.id,\n name: frame.name,\n x: frame.x,\n y: frame.y,\n width: frame.width,\n height: frame.height,\n fills: frame.fills,\n strokes: frame.strokes,\n strokeWeight: frame.strokeWeight,\n layoutMode: frame.layoutMode,\n layoutWrap: frame.layoutWrap,\n parentId: frame.parent ? frame.parent.id : undefined,\n };\n}\n\nasync function createText(params) {\n const {\n x = 0,\n y = 0,\n text = \"Text\",\n fontSize = 14,\n fontWeight = 400,\n fontColor = { r: 0, g: 0, b: 0, a: 1 }, // Default to black\n name = \"\",\n parentId,\n } = params || {};\n\n // Map common font weights to Figma font styles\n const getFontStyle = (weight) => {\n switch (weight) {\n case 100:\n return \"Thin\";\n case 200:\n return \"Extra Light\";\n case 300:\n return \"Light\";\n case 400:\n return \"Regular\";\n case 500:\n return \"Medium\";\n case 600:\n return \"Semi Bold\";\n case 700:\n return \"Bold\";\n case 800:\n return \"Extra Bold\";\n case 900:\n return \"Black\";\n default:\n return \"Regular\";\n }\n };\n\n const textNode = figma.createText();\n textNode.x = x;\n textNode.y = y;\n textNode.name = name || text;\n try {\n await figma.loadFontAsync({\n family: \"Inter\",\n style: getFontStyle(fontWeight),\n });\n textNode.fontName = { family: \"Inter\", style: getFontStyle(fontWeight) };\n textNode.fontSize = parseInt(fontSize);\n } catch (error) {\n console.error(\"Error setting font size\", error);\n }\n setCharacters(textNode, text);\n\n // Set text color\n const paintStyle = {\n type: \"SOLID\",\n color: {\n r: parseFloat(fontColor.r) || 0,\n g: parseFloat(fontColor.g) || 0,\n b: parseFloat(fontColor.b) || 0,\n },\n opacity: parseFloat(fontColor.a) || 1,\n };\n textNode.fills = [paintStyle];\n\n // If parentId is provided, append to that node, otherwise append to current page\n if (parentId) {\n const parentNode = await figma.getNodeByIdAsync(parentId);\n if (!parentNode) {\n throw new Error(`Parent node not found with ID: ${parentId}`);\n }\n if (!(\"appendChild\" in parentNode)) {\n throw new Error(`Parent node does not support children: ${parentId}`);\n }\n parentNode.appendChild(textNode);\n } else {\n figma.currentPage.appendChild(textNode);\n }\n\n return {\n id: textNode.id,\n name: textNode.name,\n x: textNode.x,\n y: textNode.y,\n width: textNode.width,\n height: textNode.height,\n characters: textNode.characters,\n fontSize: textNode.fontSize,\n fontWeight: fontWeight,\n fontColor: fontColor,\n fontName: textNode.fontName,\n fills: textNode.fills,\n parentId: textNode.parent ? textNode.parent.id : undefined,\n };\n}\n\nasync function setFillColor(params) {\n console.log(\"setFillColor\", params);\n const {\n nodeId,\n color: { r, g, b, a },\n } = params || {};\n\n if (!nodeId) {\n throw new Error(\"Missing nodeId parameter\");\n }\n\n const node = await figma.getNodeByIdAsync(nodeId);\n if (!node) {\n throw new Error(`Node not found with ID: ${nodeId}`);\n }\n\n if (!(\"fills\" in node)) {\n throw new Error(`Node does not support fills: ${nodeId}`);\n }\n\n // Create RGBA color\n const rgbColor = {\n r: parseFloat(r) || 0,\n g: parseFloat(g) || 0,\n b: parseFloat(b) || 0,\n a: parseFloat(a) || 1,\n };\n\n // Set fill\n const paintStyle = {\n type: \"SOLID\",\n color: {\n r: parseFloat(rgbColor.r),\n g: parseFloat(rgbColor.g),\n b: parseFloat(rgbColor.b),\n },\n opacity: parseFloat(rgbColor.a),\n };\n\n console.log(\"paintStyle\", paintStyle);\n\n node.fills = [paintStyle];\n\n return {\n id: node.id,\n name: node.name,\n fills: [paintStyle],\n };\n}\n\nasync function setStrokeColor(params) {\n const {\n nodeId,\n color: { r, g, b, a },\n weight = 1,\n } = params || {};\n\n if (!nodeId) {\n throw new Error(\"Missing nodeId parameter\");\n }\n\n const node = await figma.getNodeByIdAsync(nodeId);\n if (!node) {\n throw new Error(`Node not found with ID: ${nodeId}`);\n }\n\n if (!(\"strokes\" in node)) {\n throw new Error(`Node does not support strokes: ${nodeId}`);\n }\n\n // Create RGBA color\n const rgbColor = {\n r: r !== undefined ? r : 0,\n g: g !== undefined ? g : 0,\n b: b !== undefined ? b : 0,\n a: a !== undefined ? a : 1,\n };\n\n // Set stroke\n const paintStyle = {\n type: \"SOLID\",\n color: {\n r: rgbColor.r,\n g: rgbColor.g,\n b: rgbColor.b,\n },\n opacity: rgbColor.a,\n };\n\n node.strokes = [paintStyle];\n\n // Set stroke weight if available\n if (\"strokeWeight\" in node) {\n node.strokeWeight = weight;\n }\n\n return {\n id: node.id,\n name: node.name,\n strokes: node.strokes,\n strokeWeight: \"strokeWeight\" in node ? node.strokeWeight : undefined,\n };\n}\n\nasync function moveNode(params) {\n const { nodeId, x, y } = params || {};\n\n if (!nodeId) {\n throw new Error(\"Missing nodeId parameter\");\n }\n\n if (x === undefined || y === undefined) {\n throw new Error(\"Missing x or y parameters\");\n }\n\n const node = await figma.getNodeByIdAsync(nodeId);\n if (!node) {\n throw new Error(`Node not found with ID: ${nodeId}`);\n }\n\n if (!(\"x\" in node) || !(\"y\" in node)) {\n throw new Error(`Node does not support position: ${nodeId}`);\n }\n\n node.x = x;\n node.y = y;\n\n return {\n id: node.id,\n name: node.name,\n x: node.x,\n y: node.y,\n };\n}\n\nasync function resizeNode(params) {\n const { nodeId, width, height } = params || {};\n\n if (!nodeId) {\n throw new Error(\"Missing nodeId parameter\");\n }\n\n if (width === undefined || height === undefined) {\n throw new Error(\"Missing width or height parameters\");\n }\n\n const node = await figma.getNodeByIdAsync(nodeId);\n if (!node) {\n throw new Error(`Node not found with ID: ${nodeId}`);\n }\n\n if (!(\"resize\" in node)) {\n throw new Error(`Node does not support resizing: ${nodeId}`);\n }\n\n node.resize(width, height);\n\n return {\n id: node.id,\n name: node.name,\n width: node.width,\n height: node.height,\n };\n}\n\nasync function deleteNode(params) {\n const { nodeId } = params || {};\n\n if (!nodeId) {\n throw new Error(\"Missing nodeId parameter\");\n }\n\n const node = await figma.getNodeByIdAsync(nodeId);\n if (!node) {\n throw new Error(`Node not found with ID: ${nodeId}`);\n }\n\n // Save node info before deleting\n const nodeInfo = {\n id: node.id,\n name: node.name,\n type: node.type,\n };\n\n node.remove();\n\n return nodeInfo;\n}\n\nasync function getStyles() {\n const styles = {\n colors: await figma.getLocalPaintStylesAsync(),\n texts: await figma.getLocalTextStylesAsync(),\n effects: await figma.getLocalEffectStylesAsync(),\n grids: await figma.getLocalGridStylesAsync(),\n };\n\n return {\n colors: styles.colors.map((style) => ({\n id: style.id,\n name: style.name,\n key: style.key,\n paint: style.paints[0],\n })),\n texts: styles.texts.map((style) => ({\n id: style.id,\n name: style.name,\n key: style.key,\n fontSize: style.fontSize,\n fontName: style.fontName,\n })),\n effects: styles.effects.map((style) => ({\n id: style.id,\n name: style.name,\n key: style.key,\n })),\n grids: styles.grids.map((style) => ({\n id: style.id,\n name: style.name,\n key: style.key,\n })),\n };\n}\n\nasync function getLocalComponents() {\n await figma.loadAllPagesAsync();\n\n const components = figma.root.findAllWithCriteria({\n types: [\"COMPONENT\"],\n });\n\n return {\n count: components.length,\n components: components.map((component) => ({\n id: component.id,\n name: component.name,\n key: \"key\" in component ? component.key : null,\n })),\n };\n}\n\n// async function getTeamComponents() {\n// try {\n// const teamComponents =\n// await figma.teamLibrary.getAvailableComponentsAsync();\n\n// return {\n// count: teamComponents.length,\n// components: teamComponents.map((component) => ({\n// key: component.key,\n// name: component.name,\n// description: component.description,\n// libraryName: component.libraryName,\n// })),\n// };\n// } catch (error) {\n// throw new Error(`Error getting team components: ${error.message}`);\n// }\n// }\n\nasync function createComponentInstance(params) {\n const { componentKey, x = 0, y = 0 } = params || {};\n\n if (!componentKey) {\n throw new Error(\"Missing componentKey parameter\");\n }\n\n try {\n const component = await figma.importComponentByKeyAsync(componentKey);\n const instance = component.createInstance();\n\n instance.x = x;\n instance.y = y;\n\n figma.currentPage.appendChild(instance);\n\n return {\n id: instance.id,\n name: instance.name,\n x: instance.x,\n y: instance.y,\n width: instance.width,\n height: instance.height,\n componentId: instance.componentId,\n };\n } catch (error) {\n throw new Error(`Error creating component instance: ${error.message}`);\n }\n}\n\n", "suffix_code": "\nfunction customBase64Encode(bytes) {\n const chars =\n \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n let base64 = \"\";\n\n const byteLength = bytes.byteLength;\n const byteRemainder = byteLength % 3;\n const mainLength = byteLength - byteRemainder;\n\n let a, b, c, d;\n let chunk;\n\n // Main loop deals with bytes in chunks of 3\n for (let i = 0; i < mainLength; i = i + 3) {\n // Combine the three bytes into a single integer\n chunk = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2];\n\n // Use bitmasks to extract 6-bit segments from the triplet\n a = (chunk & 16515072) >> 18; // 16515072 = (2^6 - 1) << 18\n b = (chunk & 258048) >> 12; // 258048 = (2^6 - 1) << 12\n c = (chunk & 4032) >> 6; // 4032 = (2^6 - 1) << 6\n d = chunk & 63; // 63 = 2^6 - 1\n\n // Convert the raw binary segments to the appropriate ASCII encoding\n base64 += chars[a] + chars[b] + chars[c] + chars[d];\n }\n\n // Deal with the remaining bytes and padding\n if (byteRemainder === 1) {\n chunk = bytes[mainLength];\n\n a = (chunk & 252) >> 2; // 252 = (2^6 - 1) << 2\n\n // Set the 4 least significant bits to zero\n b = (chunk & 3) << 4; // 3 = 2^2 - 1\n\n base64 += chars[a] + chars[b] + \"==\";\n } else if (byteRemainder === 2) {\n chunk = (bytes[mainLength] << 8) | bytes[mainLength + 1];\n\n a = (chunk & 64512) >> 10; // 64512 = (2^6 - 1) << 10\n b = (chunk & 1008) >> 4; // 1008 = (2^6 - 1) << 4\n\n // Set the 2 least significant bits to zero\n c = (chunk & 15) << 2; // 15 = 2^4 - 1\n\n base64 += chars[a] + chars[b] + chars[c] + \"=\";\n }\n\n return base64;\n}\n\nasync function setCornerRadius(params) {\n const { nodeId, radius, corners } = params || {};\n\n if (!nodeId) {\n throw new Error(\"Missing nodeId parameter\");\n }\n\n if (radius === undefined) {\n throw new Error(\"Missing radius parameter\");\n }\n\n const node = await figma.getNodeByIdAsync(nodeId);\n if (!node) {\n throw new Error(`Node not found with ID: ${nodeId}`);\n }\n\n // Check if node supports corner radius\n if (!(\"cornerRadius\" in node)) {\n throw new Error(`Node does not support corner radius: ${nodeId}`);\n }\n\n // If corners array is provided, set individual corner radii\n if (corners && Array.isArray(corners) && corners.length === 4) {\n if (\"topLeftRadius\" in node) {\n // Node supports individual corner radii\n if (corners[0]) node.topLeftRadius = radius;\n if (corners[1]) node.topRightRadius = radius;\n if (corners[2]) node.bottomRightRadius = radius;\n if (corners[3]) node.bottomLeftRadius = radius;\n } else {\n // Node only supports uniform corner radius\n node.cornerRadius = radius;\n }\n } else {\n // Set uniform corner radius\n node.cornerRadius = radius;\n }\n\n return {\n id: node.id,\n name: node.name,\n cornerRadius: \"cornerRadius\" in node ? node.cornerRadius : undefined,\n topLeftRadius: \"topLeftRadius\" in node ? node.topLeftRadius : undefined,\n topRightRadius: \"topRightRadius\" in node ? node.topRightRadius : undefined,\n bottomRightRadius:\n \"bottomRightRadius\" in node ? node.bottomRightRadius : undefined,\n bottomLeftRadius:\n \"bottomLeftRadius\" in node ? node.bottomLeftRadius : undefined,\n };\n}\n\nasync function setTextContent(params) {\n const { nodeId, text } = params || {};\n\n if (!nodeId) {\n throw new Error(\"Missing nodeId parameter\");\n }\n\n if (text === undefined) {\n throw new Error(\"Missing text parameter\");\n }\n\n const node = await figma.getNodeByIdAsync(nodeId);\n if (!node) {\n throw new Error(`Node not found with ID: ${nodeId}`);\n }\n\n if (node.type !== \"TEXT\") {\n throw new Error(`Node is not a text node: ${nodeId}`);\n }\n\n try {\n await figma.loadFontAsync(node.fontName);\n\n await setCharacters(node, text);\n\n return {\n id: node.id,\n name: node.name,\n characters: node.characters,\n fontName: node.fontName,\n };\n } catch (error) {\n throw new Error(`Error setting text content: ${error.message}`);\n }\n}\n\n// Initialize settings on load\n(async function initializePlugin() {\n try {\n const savedSettings = await figma.clientStorage.getAsync(\"settings\");\n if (savedSettings) {\n if (savedSettings.serverPort) {\n state.serverPort = savedSettings.serverPort;\n }\n }\n\n // Send initial settings to UI\n figma.ui.postMessage({\n type: \"init-settings\",\n settings: {\n serverPort: state.serverPort,\n },\n });\n } catch (error) {\n console.error(\"Error loading settings:\", error);\n }\n})();\n\nfunction uniqBy(arr, predicate) {\n const cb = typeof predicate === \"function\" ? predicate : (o) => o[predicate];\n return [\n ...arr\n .reduce((map, item) => {\n const key = item === null || item === undefined ? item : cb(item);\n\n map.has(key) || map.set(key, item);\n\n return map;\n }, new Map())\n .values(),\n ];\n}\nconst setCharacters = async (node, characters, options) => {\n const fallbackFont = (options && options.fallbackFont) || {\n family: \"Inter\",\n style: \"Regular\",\n };\n try {\n if (node.fontName === figma.mixed) {\n if (options && options.smartStrategy === \"prevail\") {\n const fontHashTree = {};\n for (let i = 1; i < node.characters.length; i++) {\n const charFont = node.getRangeFontName(i - 1, i);\n const key = `${charFont.family}::${charFont.style}`;\n fontHashTree[key] = fontHashTree[key] ? fontHashTree[key] + 1 : 1;\n }\n const prevailedTreeItem = Object.entries(fontHashTree).sort(\n (a, b) => b[1] - a[1]\n )[0];\n const [family, style] = prevailedTreeItem[0].split(\"::\");\n const prevailedFont = {\n family,\n style,\n };\n await figma.loadFontAsync(prevailedFont);\n node.fontName = prevailedFont;\n } else if (options && options.smartStrategy === \"strict\") {\n return setCharactersWithStrictMatchFont(node, characters, fallbackFont);\n } else if (options && options.smartStrategy === \"experimental\") {\n return setCharactersWithSmartMatchFont(node, characters, fallbackFont);\n } else {\n const firstCharFont = node.getRangeFontName(0, 1);\n await figma.loadFontAsync(firstCharFont);\n node.fontName = firstCharFont;\n }\n } else {\n await figma.loadFontAsync({\n family: node.fontName.family,\n style: node.fontName.style,\n });\n }\n } catch (err) {\n console.warn(\n `Failed to load \"${node.fontName[\"family\"]} ${node.fontName[\"style\"]}\" font and replaced with fallback \"${fallbackFont.family} ${fallbackFont.style}\"`,\n err\n );\n await figma.loadFontAsync(fallbackFont);\n node.fontName = fallbackFont;\n }\n try {\n node.characters = characters;\n return true;\n } catch (err) {\n console.warn(`Failed to set characters. Skipped.`, err);\n return false;\n }\n};\n\nconst setCharactersWithStrictMatchFont = async (\n node,\n characters,\n fallbackFont\n) => {\n const fontHashTree = {};\n for (let i = 1; i < node.characters.length; i++) {\n const startIdx = i - 1;\n const startCharFont = node.getRangeFontName(startIdx, i);\n const startCharFontVal = `${startCharFont.family}::${startCharFont.style}`;\n while (i < node.characters.length) {\n i++;\n const charFont = node.getRangeFontName(i - 1, i);\n if (startCharFontVal !== `${charFont.family}::${charFont.style}`) {\n break;\n }\n }\n fontHashTree[`${startIdx}_${i}`] = startCharFontVal;\n }\n await figma.loadFontAsync(fallbackFont);\n node.fontName = fallbackFont;\n node.characters = characters;\n console.log(fontHashTree);\n await Promise.all(\n Object.keys(fontHashTree).map(async (range) => {\n console.log(range, fontHashTree[range]);\n const [start, end] = range.split(\"_\");\n const [family, style] = fontHashTree[range].split(\"::\");\n const matchedFont = {\n family,\n style,\n };\n await figma.loadFontAsync(matchedFont);\n return node.setRangeFontName(Number(start), Number(end), matchedFont);\n })\n );\n return true;\n};\n\nconst getDelimiterPos = (str, delimiter, startIdx = 0, endIdx = str.length) => {\n const indices = [];\n let temp = startIdx;\n for (let i = startIdx; i < endIdx; i++) {\n if (\n str[i] === delimiter &&\n i + startIdx !== endIdx &&\n temp !== i + startIdx\n ) {\n indices.push([temp, i + startIdx]);\n temp = i + startIdx + 1;\n }\n }\n temp !== endIdx && indices.push([temp, endIdx]);\n return indices.filter(Boolean);\n};\n\nconst buildLinearOrder = (node) => {\n const fontTree = [];\n const newLinesPos = getDelimiterPos(node.characters, \"\\n\");\n newLinesPos.forEach(([newLinesRangeStart, newLinesRangeEnd], n) => {\n const newLinesRangeFont = node.getRangeFontName(\n newLinesRangeStart,\n newLinesRangeEnd\n );\n if (newLinesRangeFont === figma.mixed) {\n const spacesPos = getDelimiterPos(\n node.characters,\n \" \",\n newLinesRangeStart,\n newLinesRangeEnd\n );\n spacesPos.forEach(([spacesRangeStart, spacesRangeEnd], s) => {\n const spacesRangeFont = node.getRangeFontName(\n spacesRangeStart,\n spacesRangeEnd\n );\n if (spacesRangeFont === figma.mixed) {\n const spacesRangeFont = node.getRangeFontName(\n spacesRangeStart,\n spacesRangeStart[0]\n );\n fontTree.push({\n start: spacesRangeStart,\n delimiter: \" \",\n family: spacesRangeFont.family,\n style: spacesRangeFont.style,\n });\n } else {\n fontTree.push({\n start: spacesRangeStart,\n delimiter: \" \",\n family: spacesRangeFont.family,\n style: spacesRangeFont.style,\n });\n }\n });\n } else {\n fontTree.push({\n start: newLinesRangeStart,\n delimiter: \"\\n\",\n family: newLinesRangeFont.family,\n style: newLinesRangeFont.style,\n });\n }\n });\n return fontTree\n .sort((a, b) => +a.start - +b.start)\n .map(({ family, style, delimiter }) => ({ family, style, delimiter }));\n};\n\nconst setCharactersWithSmartMatchFont = async (\n node,\n characters,\n fallbackFont\n) => {\n const rangeTree = buildLinearOrder(node);\n const fontsToLoad = uniqBy(\n rangeTree,\n ({ family, style }) => `${family}::${style}`\n ).map(({ family, style }) => ({\n family,\n style,\n }));\n\n await Promise.all([...fontsToLoad, fallbackFont].map(figma.loadFontAsync));\n\n node.fontName = fallbackFont;\n node.characters = characters;\n\n let prevPos = 0;\n rangeTree.forEach(({ family, style, delimiter }) => {\n if (prevPos < node.characters.length) {\n const delimeterPos = node.characters.indexOf(delimiter, prevPos);\n const endPos =\n delimeterPos > prevPos ? delimeterPos : node.characters.length;\n const matchedFont = {\n family,\n style,\n };\n node.setRangeFontName(prevPos, endPos, matchedFont);\n prevPos = endPos + 1;\n }\n });\n return true;\n};\n\n// Add the cloneNode function implementation\nasync function cloneNode(params) {\n const { nodeId, x, y } = params || {};\n\n if (!nodeId) {\n throw new Error(\"Missing nodeId parameter\");\n }\n\n const node = await figma.getNodeByIdAsync(nodeId);\n if (!node) {\n throw new Error(`Node not found with ID: ${nodeId}`);\n }\n\n // Clone the node\n const clone = node.clone();\n\n // If x and y are provided, move the clone to that position\n if (x !== undefined && y !== undefined) {\n if (!(\"x\" in clone) || !(\"y\" in clone)) {\n throw new Error(`Cloned node does not support position: ${nodeId}`);\n }\n clone.x = x;\n clone.y = y;\n }\n\n // Add the clone to the same parent as the original node\n if (node.parent) {\n node.parent.appendChild(clone);\n } else {\n figma.currentPage.appendChild(clone);\n }\n\n return {\n id: clone.id,\n name: clone.name,\n x: \"x\" in clone ? clone.x : undefined,\n y: \"y\" in clone ? clone.y : undefined,\n width: \"width\" in clone ? clone.width : undefined,\n height: \"height\" in clone ? clone.height : undefined,\n };\n}\n\nasync function scanTextNodes(params) {\n console.log(`Starting to scan text nodes from node ID: ${params.nodeId}`);\n const {\n nodeId,\n useChunking = true,\n chunkSize = 10,\n commandId = generateCommandId(),\n } = params || {};\n\n const node = await figma.getNodeByIdAsync(nodeId);\n\n if (!node) {\n console.error(`Node with ID ${nodeId} not found`);\n // Send error progress update\n sendProgressUpdate(\n commandId,\n \"scan_text_nodes\",\n \"error\",\n 0,\n 0,\n 0,\n `Node with ID ${nodeId} not found`,\n { error: `Node not found: ${nodeId}` }\n );\n throw new Error(`Node with ID ${nodeId} not found`);\n }\n\n // If chunking is not enabled, use the original implementation\n if (!useChunking) {\n const textNodes = [];\n try {\n // Send started progress update\n sendProgressUpdate(\n commandId,\n \"scan_text_nodes\",\n \"started\",\n 0,\n 1, // Not known yet how many nodes there are\n 0,\n `Starting scan of node \"${node.name || nodeId}\" without chunking`,\n null\n );\n\n await findTextNodes(node, [], 0, textNodes);\n\n // Send completed progress update\n sendProgressUpdate(\n commandId,\n \"scan_text_nodes\",\n \"completed\",\n 100,\n textNodes.length,\n textNodes.length,\n `Scan complete. Found ${textNodes.length} text nodes.`,\n { textNodes }\n );\n\n return {\n success: true,\n message: `Scanned ${textNodes.length} text nodes.`,\n count: textNodes.length,\n textNodes: textNodes,\n commandId,\n };\n } catch (error) {\n console.error(\"Error scanning text nodes:\", error);\n\n // Send error progress update\n sendProgressUpdate(\n commandId,\n \"scan_text_nodes\",\n \"error\",\n 0,\n 0,\n 0,\n `Error scanning text nodes: ${error.message}`,\n { error: error.message }\n );\n\n throw new Error(`Error scanning text nodes: ${error.message}`);\n }\n }\n\n // Chunked implementation\n console.log(`Using chunked scanning with chunk size: ${chunkSize}`);\n\n // First, collect all nodes to process (without processing them yet)\n const nodesToProcess = [];\n\n // Send started progress update\n sendProgressUpdate(\n commandId,\n \"scan_text_nodes\",\n \"started\",\n 0,\n 0, // Not known yet how many nodes there are\n 0,\n `Starting chunked scan of node \"${node.name || nodeId}\"`,\n { chunkSize }\n );\n\n await collectNodesToProcess(node, [], 0, nodesToProcess);\n\n const totalNodes = nodesToProcess.length;\n console.log(`Found ${totalNodes} total nodes to process`);\n\n // Calculate number of chunks needed\n const totalChunks = Math.ceil(totalNodes / chunkSize);\n console.log(`Will process in ${totalChunks} chunks`);\n\n // Send update after node collection\n sendProgressUpdate(\n commandId,\n \"scan_text_nodes\",\n \"in_progress\",\n 5, // 5% progress for collection phase\n totalNodes,\n 0,\n `Found ${totalNodes} nodes to scan. Will process in ${totalChunks} chunks.`,\n {\n totalNodes,\n totalChunks,\n chunkSize,\n }\n );\n\n // Process nodes in chunks\n const allTextNodes = [];\n let processedNodes = 0;\n let chunksProcessed = 0;\n\n for (let i = 0; i < totalNodes; i += chunkSize) {\n const chunkEnd = Math.min(i + chunkSize, totalNodes);\n console.log(\n `Processing chunk ${chunksProcessed + 1}/${totalChunks} (nodes ${i} to ${chunkEnd - 1\n })`\n );\n\n // Send update before processing chunk\n sendProgressUpdate(\n commandId,\n \"scan_text_nodes\",\n \"in_progress\",\n Math.round(5 + (chunksProcessed / totalChunks) * 90), // 5-95% for processing\n totalNodes,\n processedNodes,\n `Processing chunk ${chunksProcessed + 1}/${totalChunks}`,\n {\n currentChunk: chunksProcessed + 1,\n totalChunks,\n textNodesFound: allTextNodes.length,\n }\n );\n\n const chunkNodes = nodesToProcess.slice(i, chunkEnd);\n const chunkTextNodes = [];\n\n // Process each node in this chunk\n for (const nodeInfo of chunkNodes) {\n if (nodeInfo.node.type === \"TEXT\") {\n try {\n const textNodeInfo = await processTextNode(\n nodeInfo.node,\n nodeInfo.parentPath,\n nodeInfo.depth\n );\n if (textNodeInfo) {\n chunkTextNodes.push(textNodeInfo);\n }\n } catch (error) {\n console.error(`Error processing text node: ${error.message}`);\n // Continue with other nodes\n }\n }\n\n // Brief delay to allow UI updates and prevent freezing\n await delay(5);\n }\n\n // Add results from this chunk\n allTextNodes.push(...chunkTextNodes);\n processedNodes += chunkNodes.length;\n chunksProcessed++;\n\n // Send update after processing chunk\n sendProgressUpdate(\n commandId,\n \"scan_text_nodes\",\n \"in_progress\",\n Math.round(5 + (chunksProcessed / totalChunks) * 90), // 5-95% for processing\n totalNodes,\n processedNodes,\n `Processed chunk ${chunksProcessed}/${totalChunks}. Found ${allTextNodes.length} text nodes so far.`,\n {\n currentChunk: chunksProcessed,\n totalChunks,\n processedNodes,\n textNodesFound: allTextNodes.length,\n chunkResult: chunkTextNodes,\n }\n );\n\n // Small delay between chunks to prevent UI freezing\n if (i + chunkSize < totalNodes) {\n await delay(50);\n }\n }\n\n // Send completed progress update\n sendProgressUpdate(\n commandId,\n \"scan_text_nodes\",\n \"completed\",\n 100,\n totalNodes,\n processedNodes,\n `Scan complete. Found ${allTextNodes.length} text nodes.`,\n {\n textNodes: allTextNodes,\n processedNodes,\n chunks: chunksProcessed,\n }\n );\n\n return {\n success: true,\n message: `Chunked scan complete. Found ${allTextNodes.length} text nodes.`,\n totalNodes: allTextNodes.length,\n processedNodes: processedNodes,\n chunks: chunksProcessed,\n textNodes: allTextNodes,\n commandId,\n };\n}\n\n// Helper function to collect all nodes that need to be processed\nasync function collectNodesToProcess(\n node,\n parentPath = [],\n depth = 0,\n nodesToProcess = []\n) {\n // Skip invisible nodes\n if (node.visible === false) return;\n\n // Get the path to this node\n const nodePath = [...parentPath, node.name || `Unnamed ${node.type}`];\n\n // Add this node to the processing list\n nodesToProcess.push({\n node: node,\n parentPath: nodePath,\n depth: depth,\n });\n\n // Recursively add children\n if (\"children\" in node) {\n for (const child of node.children) {\n await collectNodesToProcess(child, nodePath, depth + 1, nodesToProcess);\n }\n }\n}\n\n// Process a single text node\nasync function processTextNode(node, parentPath, depth) {\n if (node.type !== \"TEXT\") return null;\n\n try {\n // Safely extract font information\n let fontFamily = \"\";\n let fontStyle = \"\";\n\n if (node.fontName) {\n if (typeof node.fontName === \"object\") {\n if (\"family\" in node.fontName) fontFamily = node.fontName.family;\n if (\"style\" in node.fontName) fontStyle = node.fontName.style;\n }\n }\n\n // Create a safe representation of the text node\n const safeTextNode = {\n id: node.id,\n name: node.name || \"Text\",\n type: node.type,\n characters: node.characters,\n fontSize: typeof node.fontSize === \"number\" ? node.fontSize : 0,\n fontFamily: fontFamily,\n fontStyle: fontStyle,\n x: typeof node.x === \"number\" ? node.x : 0,\n y: typeof node.y === \"number\" ? node.y : 0,\n width: typeof node.width === \"number\" ? node.width : 0,\n height: typeof node.height === \"number\" ? node.height : 0,\n path: parentPath.join(\" > \"),\n depth: depth,\n };\n\n // Highlight the node briefly (optional visual feedback)\n try {\n const originalFills = JSON.parse(JSON.stringify(node.fills));\n node.fills = [\n {\n type: \"SOLID\",\n color: { r: 1, g: 0.5, b: 0 },\n opacity: 0.3,\n },\n ];\n\n // Brief delay for the highlight to be visible\n await delay(100);\n\n try {\n node.fills = originalFills;\n } catch (err) {\n console.error(\"Error resetting fills:\", err);\n }\n } catch (highlightErr) {\n console.error(\"Error highlighting text node:\", highlightErr);\n // Continue anyway, highlighting is just visual feedback\n }\n\n return safeTextNode;\n } catch (nodeErr) {\n console.error(\"Error processing text node:\", nodeErr);\n return null;\n }\n}\n\n// A delay function that returns a promise\nfunction delay(ms) {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n// Keep the original findTextNodes for backward compatibility\nasync function findTextNodes(node, parentPath = [], depth = 0, textNodes = []) {\n // Skip invisible nodes\n if (node.visible === false) return;\n\n // Get the path to this node including its name\n const nodePath = [...parentPath, node.name || `Unnamed ${node.type}`];\n\n if (node.type === \"TEXT\") {\n try {\n // Safely extract font information to avoid Symbol serialization issues\n let fontFamily = \"\";\n let fontStyle = \"\";\n\n if (node.fontName) {\n if (typeof node.fontName === \"object\") {\n if (\"family\" in node.fontName) fontFamily = node.fontName.family;\n if (\"style\" in node.fontName) fontStyle = node.fontName.style;\n }\n }\n\n // Create a safe representation of the text node with only serializable properties\n const safeTextNode = {\n id: node.id,\n name: node.name || \"Text\",\n type: node.type,\n characters: node.characters,\n fontSize: typeof node.fontSize === \"number\" ? node.fontSize : 0,\n fontFamily: fontFamily,\n fontStyle: fontStyle,\n x: typeof node.x === \"number\" ? node.x : 0,\n y: typeof node.y === \"number\" ? node.y : 0,\n width: typeof node.width === \"number\" ? node.width : 0,\n height: typeof node.height === \"number\" ? node.height : 0,\n path: nodePath.join(\" > \"),\n depth: depth,\n };\n\n // Only highlight the node if it's not being done via API\n try {\n // Safe way to create a temporary highlight without causing serialization issues\n const originalFills = JSON.parse(JSON.stringify(node.fills));\n node.fills = [\n {\n type: \"SOLID\",\n color: { r: 1, g: 0.5, b: 0 },\n opacity: 0.3,\n },\n ];\n\n // Promise-based delay instead of setTimeout\n await delay(500);\n\n try {\n node.fills = originalFills;\n } catch (err) {\n console.error(\"Error resetting fills:\", err);\n }\n } catch (highlightErr) {\n console.error(\"Error highlighting text node:\", highlightErr);\n // Continue anyway, highlighting is just visual feedback\n }\n\n textNodes.push(safeTextNode);\n } catch (nodeErr) {\n console.error(\"Error processing text node:\", nodeErr);\n // Skip this node but continue with others\n }\n }\n\n // Recursively process children of container nodes\n if (\"children\" in node) {\n for (const child of node.children) {\n await findTextNodes(child, nodePath, depth + 1, textNodes);\n }\n }\n}\n\n// Replace text in a specific node\nasync function setMultipleTextContents(params) {\n const { nodeId, text } = params || {};\n const commandId = params.commandId || generateCommandId();\n\n if (!nodeId || !text || !Array.isArray(text)) {\n const errorMsg = \"Missing required parameters: nodeId and text array\";\n\n // Send error progress update\n sendProgressUpdate(\n commandId,\n \"set_multiple_text_contents\",\n \"error\",\n 0,\n 0,\n 0,\n errorMsg,\n { error: errorMsg }\n );\n\n throw new Error(errorMsg);\n }\n\n console.log(\n `Starting text replacement for node: ${nodeId} with ${text.length} text replacements`\n );\n\n // Send started progress update\n sendProgressUpdate(\n commandId,\n \"set_multiple_text_contents\",\n \"started\",\n 0,\n text.length,\n 0,\n `Starting text replacement for ${text.length} nodes`,\n { totalReplacements: text.length }\n );\n\n // Define the results array and counters\n const results = [];\n let successCount = 0;\n let failureCount = 0;\n\n // Split text replacements into chunks of 5\n const CHUNK_SIZE = 5;\n const chunks = [];\n\n for (let i = 0; i < text.length; i += CHUNK_SIZE) {\n chunks.push(text.slice(i, i + CHUNK_SIZE));\n }\n\n console.log(`Split ${text.length} replacements into ${chunks.length} chunks`);\n\n // Send chunking info update\n sendProgressUpdate(\n commandId,\n \"set_multiple_text_contents\",\n \"in_progress\",\n 5, // 5% progress for planning phase\n text.length,\n 0,\n `Preparing to replace text in ${text.length} nodes using ${chunks.length} chunks`,\n {\n totalReplacements: text.length,\n chunks: chunks.length,\n chunkSize: CHUNK_SIZE,\n }\n );\n\n // Process each chunk sequentially\n for (let chunkIndex = 0; chunkIndex < chunks.length; chunkIndex++) {\n const chunk = chunks[chunkIndex];\n console.log(\n `Processing chunk ${chunkIndex + 1}/${chunks.length} with ${chunk.length\n } replacements`\n );\n\n // Send chunk processing start update\n sendProgressUpdate(\n commandId,\n \"set_multiple_text_contents\",\n \"in_progress\",\n Math.round(5 + (chunkIndex / chunks.length) * 90), // 5-95% for processing\n text.length,\n successCount + failureCount,\n `Processing text replacements chunk ${chunkIndex + 1}/${chunks.length}`,\n {\n currentChunk: chunkIndex + 1,\n totalChunks: chunks.length,\n successCount,\n failureCount,\n }\n );\n\n // Process replacements within a chunk in parallel\n const chunkPromises = chunk.map(async (replacement) => {\n if (!replacement.nodeId || replacement.text === undefined) {\n console.error(`Missing nodeId or text for replacement`);\n return {\n success: false,\n nodeId: replacement.nodeId || \"unknown\",\n error: \"Missing nodeId or text in replacement entry\",\n };\n }\n\n try {\n console.log(\n `Attempting to replace text in node: ${replacement.nodeId}`\n );\n\n // Get the text node to update (just to check it exists and get original text)\n const textNode = await figma.getNodeByIdAsync(replacement.nodeId);\n\n if (!textNode) {\n console.error(`Text node not found: ${replacement.nodeId}`);\n return {\n success: false,\n nodeId: replacement.nodeId,\n error: `Node not found: ${replacement.nodeId}`,\n };\n }\n\n if (textNode.type !== \"TEXT\") {\n console.error(\n `Node is not a text node: ${replacement.nodeId} (type: ${textNode.type})`\n );\n return {\n success: false,\n nodeId: replacement.nodeId,\n error: `Node is not a text node: ${replacement.nodeId} (type: ${textNode.type})`,\n };\n }\n\n // Save original text for the result\n const originalText = textNode.characters;\n console.log(`Original text: \"${originalText}\"`);\n console.log(`Will translate to: \"${replacement.text}\"`);\n\n // Highlight the node before changing text\n let originalFills;\n try {\n // Save original fills for restoration later\n originalFills = JSON.parse(JSON.stringify(textNode.fills));\n // Apply highlight color (orange with 30% opacity)\n textNode.fills = [\n {\n type: \"SOLID\",\n color: { r: 1, g: 0.5, b: 0 },\n opacity: 0.3,\n },\n ];\n } catch (highlightErr) {\n console.error(\n `Error highlighting text node: ${highlightErr.message}`\n );\n // Continue anyway, highlighting is just visual feedback\n }\n\n // Use the existing setTextContent function to handle font loading and text setting\n await setTextContent({\n nodeId: replacement.nodeId,\n text: replacement.text,\n });\n\n // Keep highlight for a moment after text change, then restore original fills\n if (originalFills) {\n try {\n // Use delay function for consistent timing\n await delay(500);\n textNode.fills = originalFills;\n } catch (restoreErr) {\n console.error(`Error restoring fills: ${restoreErr.message}`);\n }\n }\n\n console.log(\n `Successfully replaced text in node: ${replacement.nodeId}`\n );\n return {\n success: true,\n nodeId: replacement.nodeId,\n originalText: originalText,\n translatedText: replacement.text,\n };\n } catch (error) {\n console.error(\n `Error replacing text in node ${replacement.nodeId}: ${error.message}`\n );\n return {\n success: false,\n nodeId: replacement.nodeId,\n error: `Error applying replacement: ${error.message}`,\n };\n }\n });\n\n // Wait for all replacements in this chunk to complete\n const chunkResults = await Promise.all(chunkPromises);\n\n // Process results for this chunk\n chunkResults.forEach((result) => {\n if (result.success) {\n successCount++;\n } else {\n failureCount++;\n }\n results.push(result);\n });\n\n // Send chunk processing complete update with partial results\n sendProgressUpdate(\n commandId,\n \"set_multiple_text_contents\",\n \"in_progress\",\n Math.round(5 + ((chunkIndex + 1) / chunks.length) * 90), // 5-95% for processing\n text.length,\n successCount + failureCount,\n `Completed chunk ${chunkIndex + 1}/${chunks.length\n }. ${successCount} successful, ${failureCount} failed so far.`,\n {\n currentChunk: chunkIndex + 1,\n totalChunks: chunks.length,\n successCount,\n failureCount,\n chunkResults: chunkResults,\n }\n );\n\n // Add a small delay between chunks to avoid overloading Figma\n if (chunkIndex < chunks.length - 1) {\n console.log(\"Pausing between chunks to avoid overloading Figma...\");\n await delay(1000); // 1 second delay between chunks\n }\n }\n\n console.log(\n `Replacement complete: ${successCount} successful, ${failureCount} failed`\n );\n\n // Send completed progress update\n sendProgressUpdate(\n commandId,\n \"set_multiple_text_contents\",\n \"completed\",\n 100,\n text.length,\n successCount + failureCount,\n `Text replacement complete: ${successCount} successful, ${failureCount} failed`,\n {\n totalReplacements: text.length,\n replacementsApplied: successCount,\n replacementsFailed: failureCount,\n completedInChunks: chunks.length,\n results: results,\n }\n );\n\n return {\n success: successCount > 0,\n nodeId: nodeId,\n replacementsApplied: successCount,\n replacementsFailed: failureCount,\n totalReplacements: text.length,\n results: results,\n completedInChunks: chunks.length,\n commandId,\n };\n}\n\n// Function to generate simple UUIDs for command IDs\nfunction generateCommandId() {\n return (\n \"cmd_\" +\n Math.random().toString(36).substring(2, 15) +\n Math.random().toString(36).substring(2, 15)\n );\n}\n\nasync function getAnnotations(params) {\n try {\n const { nodeId, includeCategories = true } = params;\n\n // Get categories first if needed\n let categoriesMap = {};\n if (includeCategories) {\n const categories = await figma.annotations.getAnnotationCategoriesAsync();\n categoriesMap = categories.reduce((map, category) => {\n map[category.id] = {\n id: category.id,\n label: category.label,\n color: category.color,\n isPreset: category.isPreset,\n };\n return map;\n }, {});\n }\n\n if (nodeId) {\n // Get annotations for a specific node\n const node = await figma.getNodeByIdAsync(nodeId);\n if (!node) {\n throw new Error(`Node not found: ${nodeId}`);\n }\n\n if (!(\"annotations\" in node)) {\n throw new Error(`Node type ${node.type} does not support annotations`);\n }\n\n const result = {\n nodeId: node.id,\n name: node.name,\n annotations: node.annotations || [],\n };\n\n if (includeCategories) {\n result.categories = Object.values(categoriesMap);\n }\n\n return result;\n } else {\n // Get all annotations in the current page\n const annotations = [];\n const processNode = async (node) => {\n if (\n \"annotations\" in node &&\n node.annotations &&\n node.annotations.length > 0\n ) {\n annotations.push({\n nodeId: node.id,\n name: node.name,\n annotations: node.annotations,\n });\n }\n if (\"children\" in node) {\n for (const child of node.children) {\n await processNode(child);\n }\n }\n };\n\n // Start from current page\n await processNode(figma.currentPage);\n\n const result = {\n annotatedNodes: annotations,\n };\n\n if (includeCategories) {\n result.categories = Object.values(categoriesMap);\n }\n\n return result;\n }\n } catch (error) {\n console.error(\"Error in getAnnotations:\", error);\n throw error;\n }\n}\n\nasync function setAnnotation(params) {\n try {\n console.log(\"=== setAnnotation Debug Start ===\");\n console.log(\"Input params:\", JSON.stringify(params, null, 2));\n\n const { nodeId, annotationId, labelMarkdown, categoryId, properties } =\n params;\n\n // Validate required parameters\n if (!nodeId) {\n console.error(\"Validation failed: Missing nodeId\");\n return { success: false, error: \"Missing nodeId\" };\n }\n\n if (!labelMarkdown) {\n console.error(\"Validation failed: Missing labelMarkdown\");\n return { success: false, error: \"Missing labelMarkdown\" };\n }\n\n console.log(\"Attempting to get node:\", nodeId);\n // Get and validate node\n const node = await figma.getNodeByIdAsync(nodeId);\n console.log(\"Node lookup result:\", {\n id: nodeId,\n found: !!node,\n type: node ? node.type : undefined,\n name: node ? node.name : undefined,\n hasAnnotations: node ? \"annotations\" in node : false,\n });\n\n if (!node) {\n console.error(\"Node lookup failed:\", nodeId);\n return { success: false, error: `Node not found: ${nodeId}` };\n }\n\n // Validate node supports annotations\n if (!(\"annotations\" in node)) {\n console.error(\"Node annotation support check failed:\", {\n nodeType: node.type,\n nodeId: node.id,\n });\n return {\n success: false,\n error: `Node type ${node.type} does not support annotations`,\n };\n }\n\n // Create the annotation object\n const newAnnotation = {\n labelMarkdown,\n };\n\n // Validate and add categoryId if provided\n if (categoryId) {\n console.log(\"Adding categoryId to annotation:\", categoryId);\n newAnnotation.categoryId = categoryId;\n }\n\n // Validate and add properties if provided\n if (properties && Array.isArray(properties) && properties.length > 0) {\n console.log(\n \"Adding properties to annotation:\",\n JSON.stringify(properties, null, 2)\n );\n newAnnotation.properties = properties;\n }\n\n // Log current annotations before update\n console.log(\"Current node annotations:\", node.annotations);\n\n // Overwrite annotations\n console.log(\n \"Setting new annotation:\",\n JSON.stringify(newAnnotation, null, 2)\n );\n node.annotations = [newAnnotation];\n\n // Verify the update\n console.log(\"Updated node annotations:\", node.annotations);\n console.log(\"=== setAnnotation Debug End ===\");\n\n return {\n success: true,\n nodeId: node.id,\n name: node.name,\n annotations: node.annotations,\n };\n } catch (error) {\n console.error(\"=== setAnnotation Error ===\");\n console.error(\"Error details:\", {\n message: error.message,\n stack: error.stack,\n params: JSON.stringify(params, null, 2),\n });\n return { success: false, error: error.message };\n }\n}\n\n/**\n * Scan for nodes with specific types within a node\n * @param {Object} params - Parameters object\n * @param {string} params.nodeId - ID of the node to scan within\n * @param {Array} params.types - Array of node types to find (e.g. ['COMPONENT', 'FRAME'])\n * @returns {Object} - Object containing found nodes\n */\nasync function scanNodesByTypes(params) {\n console.log(`Starting to scan nodes by types from node ID: ${params.nodeId}`);\n const { nodeId, types = [] } = params || {};\n\n if (!types || types.length === 0) {\n throw new Error(\"No types specified to search for\");\n }\n\n const node = await figma.getNodeByIdAsync(nodeId);\n\n if (!node) {\n throw new Error(`Node with ID ${nodeId} not found`);\n }\n\n // Simple implementation without chunking\n const matchingNodes = [];\n\n // Send a single progress update to notify start\n const commandId = generateCommandId();\n sendProgressUpdate(\n commandId,\n \"scan_nodes_by_types\",\n \"started\",\n 0,\n 1,\n 0,\n `Starting scan of node \"${node.name || nodeId}\" for types: ${types.join(\n \", \"\n )}`,\n null\n );\n\n // Recursively find nodes with specified types\n await findNodesByTypes(node, types, matchingNodes);\n\n // Send completion update\n sendProgressUpdate(\n commandId,\n \"scan_nodes_by_types\",\n \"completed\",\n 100,\n matchingNodes.length,\n matchingNodes.length,\n `Scan complete. Found ${matchingNodes.length} matching nodes.`,\n { matchingNodes }\n );\n\n return {\n success: true,\n message: `Found ${matchingNodes.length} matching nodes.`,\n count: matchingNodes.length,\n matchingNodes: matchingNodes,\n searchedTypes: types,\n };\n}\n\n/**\n * Helper function to recursively find nodes with specific types\n * @param {SceneNode} node - The root node to start searching from\n * @param {Array} types - Array of node types to find\n * @param {Array} matchingNodes - Array to store found nodes\n */\nasync function findNodesByTypes(node, types, matchingNodes = []) {\n // Skip invisible nodes\n if (node.visible === false) return;\n\n // Check if this node is one of the specified types\n if (types.includes(node.type)) {\n // Create a minimal representation with just ID, type and bbox\n matchingNodes.push({\n id: node.id,\n name: node.name || `Unnamed ${node.type}`,\n type: node.type,\n // Basic bounding box info\n bbox: {\n x: typeof node.x === \"number\" ? node.x : 0,\n y: typeof node.y === \"number\" ? node.y : 0,\n width: typeof node.width === \"number\" ? node.width : 0,\n height: typeof node.height === \"number\" ? node.height : 0,\n },\n });\n }\n\n // Recursively process children of container nodes\n if (\"children\" in node) {\n for (const child of node.children) {\n await findNodesByTypes(child, types, matchingNodes);\n }\n }\n}\n\n// Set multiple annotations with async progress updates\nasync function setMultipleAnnotations(params) {\n console.log(\"=== setMultipleAnnotations Debug Start ===\");\n console.log(\"Input params:\", JSON.stringify(params, null, 2));\n\n const { nodeId, annotations } = params;\n\n if (!annotations || annotations.length === 0) {\n console.error(\"Validation failed: No annotations provided\");\n return { success: false, error: \"No annotations provided\" };\n }\n\n console.log(\n `Processing ${annotations.length} annotations for node ${nodeId}`\n );\n\n const results = [];\n let successCount = 0;\n let failureCount = 0;\n\n // Process annotations sequentially\n for (let i = 0; i < annotations.length; i++) {\n const annotation = annotations[i];\n console.log(\n `\\nProcessing annotation ${i + 1}/${annotations.length}:`,\n JSON.stringify(annotation, null, 2)\n );\n\n try {\n console.log(\"Calling setAnnotation with params:\", {\n nodeId: annotation.nodeId,\n labelMarkdown: annotation.labelMarkdown,\n categoryId: annotation.categoryId,\n properties: annotation.properties,\n });\n\n const result = await setAnnotation({\n nodeId: annotation.nodeId,\n labelMarkdown: annotation.labelMarkdown,\n categoryId: annotation.categoryId,\n properties: annotation.properties,\n });\n\n console.log(\"setAnnotation result:\", JSON.stringify(result, null, 2));\n\n if (result.success) {\n successCount++;\n results.push({ success: true, nodeId: annotation.nodeId });\n console.log(`✓ Annotation ${i + 1} applied successfully`);\n } else {\n failureCount++;\n results.push({\n success: false,\n nodeId: annotation.nodeId,\n error: result.error,\n });\n console.error(`✗ Annotation ${i + 1} failed:`, result.error);\n }\n } catch (error) {\n failureCount++;\n const errorResult = {\n success: false,\n nodeId: annotation.nodeId,\n error: error.message,\n };\n results.push(errorResult);\n console.error(`✗ Annotation ${i + 1} failed with error:`, error);\n console.error(\"Error details:\", {\n message: error.message,\n stack: error.stack,\n });\n }\n }\n\n const summary = {\n success: successCount > 0,\n annotationsApplied: successCount,\n annotationsFailed: failureCount,\n totalAnnotations: annotations.length,\n results: results,\n };\n\n console.log(\"\\n=== setMultipleAnnotations Summary ===\");\n console.log(JSON.stringify(summary, null, 2));\n console.log(\"=== setMultipleAnnotations Debug End ===\");\n\n return summary;\n}\n\nasync function deleteMultipleNodes(params) {\n const { nodeIds } = params || {};\n const commandId = generateCommandId();\n\n if (!nodeIds || !Array.isArray(nodeIds) || nodeIds.length === 0) {\n const errorMsg = \"Missing or invalid nodeIds parameter\";\n sendProgressUpdate(\n commandId,\n \"delete_multiple_nodes\",\n \"error\",\n 0,\n 0,\n 0,\n errorMsg,\n { error: errorMsg }\n );\n throw new Error(errorMsg);\n }\n\n console.log(`Starting deletion of ${nodeIds.length} nodes`);\n\n // Send started progress update\n sendProgressUpdate(\n commandId,\n \"delete_multiple_nodes\",\n \"started\",\n 0,\n nodeIds.length,\n 0,\n `Starting deletion of ${nodeIds.length} nodes`,\n { totalNodes: nodeIds.length }\n );\n\n const results = [];\n let successCount = 0;\n let failureCount = 0;\n\n // Process nodes in chunks of 5 to avoid overwhelming Figma\n const CHUNK_SIZE = 5;\n const chunks = [];\n\n for (let i = 0; i < nodeIds.length; i += CHUNK_SIZE) {\n chunks.push(nodeIds.slice(i, i + CHUNK_SIZE));\n }\n\n console.log(`Split ${nodeIds.length} deletions into ${chunks.length} chunks`);\n\n // Send chunking info update\n sendProgressUpdate(\n commandId,\n \"delete_multiple_nodes\",\n \"in_progress\",\n 5,\n nodeIds.length,\n 0,\n `Preparing to delete ${nodeIds.length} nodes using ${chunks.length} chunks`,\n {\n totalNodes: nodeIds.length,\n chunks: chunks.length,\n chunkSize: CHUNK_SIZE,\n }\n );\n\n // Process each chunk sequentially\n for (let chunkIndex = 0; chunkIndex < chunks.length; chunkIndex++) {\n const chunk = chunks[chunkIndex];\n console.log(\n `Processing chunk ${chunkIndex + 1}/${chunks.length} with ${chunk.length\n } nodes`\n );\n\n // Send chunk processing start update\n sendProgressUpdate(\n commandId,\n \"delete_multiple_nodes\",\n \"in_progress\",\n Math.round(5 + (chunkIndex / chunks.length) * 90),\n nodeIds.length,\n successCount + failureCount,\n `Processing deletion chunk ${chunkIndex + 1}/${chunks.length}`,\n {\n currentChunk: chunkIndex + 1,\n totalChunks: chunks.length,\n successCount,\n failureCount,\n }\n );\n\n // Process deletions within a chunk in parallel\n const chunkPromises = chunk.map(async (nodeId) => {\n try {\n const node = await figma.getNodeByIdAsync(nodeId);\n\n if (!node) {\n console.error(`Node not found: ${nodeId}`);\n return {\n success: false,\n nodeId: nodeId,\n error: `Node not found: ${nodeId}`,\n };\n }\n\n // Save node info before deleting\n const nodeInfo = {\n id: node.id,\n name: node.name,\n type: node.type,\n };\n\n // Delete the node\n node.remove();\n\n console.log(`Successfully deleted node: ${nodeId}`);\n return {\n success: true,\n nodeId: nodeId,\n nodeInfo: nodeInfo,\n };\n } catch (error) {\n console.error(`Error deleting node ${nodeId}: ${error.message}`);\n return {\n success: false,\n nodeId: nodeId,\n error: error.message,\n };\n }\n });\n\n // Wait for all deletions in this chunk to complete\n const chunkResults = await Promise.all(chunkPromises);\n\n // Process results for this chunk\n chunkResults.forEach((result) => {\n if (result.success) {\n successCount++;\n } else {\n failureCount++;\n }\n results.push(result);\n });\n\n // Send chunk processing complete update\n sendProgressUpdate(\n commandId,\n \"delete_multiple_nodes\",\n \"in_progress\",\n Math.round(5 + ((chunkIndex + 1) / chunks.length) * 90),\n nodeIds.length,\n successCount + failureCount,\n `Completed chunk ${chunkIndex + 1}/${chunks.length\n }. ${successCount} successful, ${failureCount} failed so far.`,\n {\n currentChunk: chunkIndex + 1,\n totalChunks: chunks.length,\n successCount,\n failureCount,\n chunkResults: chunkResults,\n }\n );\n\n // Add a small delay between chunks\n if (chunkIndex < chunks.length - 1) {\n console.log(\"Pausing between chunks...\");\n await delay(1000);\n }\n }\n\n console.log(\n `Deletion complete: ${successCount} successful, ${failureCount} failed`\n );\n\n // Send completed progress update\n sendProgressUpdate(\n commandId,\n \"delete_multiple_nodes\",\n \"completed\",\n 100,\n nodeIds.length,\n successCount + failureCount,\n `Node deletion complete: ${successCount} successful, ${failureCount} failed`,\n {\n totalNodes: nodeIds.length,\n nodesDeleted: successCount,\n nodesFailed: failureCount,\n completedInChunks: chunks.length,\n results: results,\n }\n );\n\n return {\n success: successCount > 0,\n nodesDeleted: successCount,\n nodesFailed: failureCount,\n totalNodes: nodeIds.length,\n results: results,\n completedInChunks: chunks.length,\n commandId,\n };\n}\n\n// Implementation for getInstanceOverrides function\nasync function getInstanceOverrides(instanceNode = null) {\n console.log(\"=== getInstanceOverrides called ===\");\n\n let sourceInstance = null;\n\n // Check if an instance node was passed directly\n if (instanceNode) {\n console.log(\"Using provided instance node\");\n\n // Validate that the provided node is an instance\n if (instanceNode.type !== \"INSTANCE\") {\n console.error(\"Provided node is not an instance\");\n figma.notify(\"Provided node is not a component instance\");\n return { success: false, message: \"Provided node is not a component instance\" };\n }\n\n sourceInstance = instanceNode;\n } else {\n // No node provided, use selection\n console.log(\"No node provided, using current selection\");\n\n // Get the current selection\n const selection = figma.currentPage.selection;\n\n // Check if there's anything selected\n if (selection.length === 0) {\n console.log(\"No nodes selected\");\n figma.notify(\"Please select at least one instance\");\n return { success: false, message: \"No nodes selected\" };\n }\n\n // Filter for instances in the selection\n const instances = selection.filter(node => node.type === \"INSTANCE\");\n\n if (instances.length === 0) {\n console.log(\"No instances found in selection\");\n figma.notify(\"Please select at least one component instance\");\n return { success: false, message: \"No instances found in selection\" };\n }\n\n // Take the first instance from the selection\n sourceInstance = instances[0];\n }\n\n try {\n console.log(`Getting instance information:`);\n console.log(sourceInstance);\n\n // Get component overrides and main component\n const overrides = sourceInstance.overrides || [];\n console.log(` Raw Overrides:`, overrides);\n\n // Get main component\n const mainComponent = await sourceInstance.getMainComponentAsync();\n if (!mainComponent) {\n console.error(\"Failed to get main component\");\n figma.notify(\"Failed to get main component\");\n return { success: false, message: \"Failed to get main component\" };\n }\n\n // return data to MCP server\n const returnData = {\n success: true,\n message: `Got component information from \"${sourceInstance.name}\" for overrides.length: ${overrides.length}`,\n sourceInstanceId: sourceInstance.id,\n mainComponentId: mainComponent.id,\n overridesCount: overrides.length\n };\n\n console.log(\"Data to return to MCP server:\", returnData);\n figma.notify(`Got component information from \"${sourceInstance.name}\"`);\n\n return returnData;\n } catch (error) {\n console.error(\"Error in getInstanceOverrides:\", error);\n figma.notify(`Error: ${error.message}`);\n return {\n success: false,\n message: `Error: ${error.message}`\n };\n }\n}\n\n/**\n * Helper function to validate and get target instances\n * @param {string[]} targetNodeIds - Array of instance node IDs\n * @returns {instanceNode[]} targetInstances - Array of target instances\n */\nasync function getValidTargetInstances(targetNodeIds) {\n let targetInstances = [];\n\n // Handle array of instances or single instance\n if (Array.isArray(targetNodeIds)) {\n if (targetNodeIds.length === 0) {\n return { success: false, message: \"No instances provided\" };\n }\n for (const targetNodeId of targetNodeIds) {\n const targetNode = await figma.getNodeByIdAsync(targetNodeId);\n if (targetNode && targetNode.type === \"INSTANCE\") {\n targetInstances.push(targetNode);\n }\n }\n if (targetInstances.length === 0) {\n return { success: false, message: \"No valid instances provided\" };\n }\n } else {\n return { success: false, message: \"Invalid target node IDs provided\" };\n }\n\n\n return { success: true, message: \"Valid target instances provided\", targetInstances };\n}\n\n/**\n * Helper function to validate and get saved override data\n * @param {string} sourceInstanceId - Source instance ID\n * @returns {Promise} - Validation result with source instance data or error\n */\nasync function getSourceInstanceData(sourceInstanceId) {\n if (!sourceInstanceId) {\n return { success: false, message: \"Missing source instance ID\" };\n }\n\n // Get source instance by ID\n const sourceInstance = await figma.getNodeByIdAsync(sourceInstanceId);\n if (!sourceInstance) {\n return {\n success: false,\n message: \"Source instance not found. The original instance may have been deleted.\"\n };\n }\n\n // Verify it's an instance\n if (sourceInstance.type !== \"INSTANCE\") {\n return {\n success: false,\n message: \"Source node is not a component instance.\"\n };\n }\n\n // Get main component\n const mainComponent = await sourceInstance.getMainComponentAsync();\n if (!mainComponent) {\n return {\n success: false,\n message: \"Failed to get main component from source instance.\"\n };\n }\n\n return {\n success: true,\n sourceInstance,\n mainComponent,\n overrides: sourceInstance.overrides || []\n };\n}\n\n/**\n * Sets saved overrides to the selected component instance(s)\n * @param {InstanceNode[] | null} targetInstances - Array of instance nodes to set overrides to\n * @param {Object} sourceResult - Source instance data from getSourceInstanceData\n * @returns {Promise} - Result of the set operation\n */\nasync function setInstanceOverrides(targetInstances, sourceResult) {\n try {\n\n\n const { sourceInstance, mainComponent, overrides } = sourceResult;\n\n console.log(`Processing ${targetInstances.length} instances with ${overrides.length} overrides`);\n console.log(`Source instance: ${sourceInstance.id}, Main component: ${mainComponent.id}`);\n console.log(`Overrides:`, overrides);\n\n // Process all instances\n const results = [];\n let totalAppliedCount = 0;\n\n for (const targetInstance of targetInstances) {\n try {\n // // Skip if trying to apply to the source instance itself\n // if (targetInstance.id === sourceInstance.id) {\n // console.log(`Skipping source instance itself: ${targetInstance.id}`);\n // results.push({\n // success: false,\n // instanceId: targetInstance.id,\n // instanceName: targetInstance.name,\n // message: \"This is the source instance itself, skipping\"\n // });\n // continue;\n // }\n\n // Swap component\n try {\n targetInstance.swapComponent(mainComponent);\n console.log(`Swapped component for instance \"${targetInstance.name}\"`);\n } catch (error) {\n console.error(`Error swapping component for instance \"${targetInstance.name}\":`, error);\n results.push({\n success: false,\n instanceId: targetInstance.id,\n instanceName: targetInstance.name,\n message: `Error: ${error.message}`\n });\n }\n\n // Prepare overrides by replacing node IDs\n let appliedCount = 0;\n\n // Apply each override\n for (const override of overrides) {\n // Skip if no ID or overriddenFields\n if (!override.id || !override.overriddenFields || override.overriddenFields.length === 0) {\n continue;\n }\n\n // Replace source instance ID with target instance ID in the node path\n const overrideNodeId = override.id.replace(sourceInstance.id, targetInstance.id);\n const overrideNode = await figma.getNodeByIdAsync(overrideNodeId);\n\n if (!overrideNode) {\n console.log(`Override node not found: ${overrideNodeId}`);\n continue;\n }\n\n // Get source node to copy properties from\n const sourceNode = await figma.getNodeByIdAsync(override.id);\n if (!sourceNode) {\n console.log(`Source node not found: ${override.id}`);\n continue;\n }\n\n // Apply each overridden field\n let fieldApplied = false;\n for (const field of override.overriddenFields) {\n try {\n if (field === \"componentProperties\") {\n // Apply component properties\n if (sourceNode.componentProperties && overrideNode.componentProperties) {\n const properties = {};\n for (const key in sourceNode.componentProperties) {\n // if INSTANCE_SWAP use id, otherwise use value\n if (sourceNode.componentProperties[key].type === 'INSTANCE_SWAP') {\n properties[key] = sourceNode.componentProperties[key].value;\n \n } else {\n properties[key] = sourceNode.componentProperties[key].value;\n }\n }\n overrideNode.setProperties(properties);\n fieldApplied = true;\n }\n } else if (field === \"characters\" && overrideNode.type === \"TEXT\") {\n // For text nodes, need to load fonts first\n await figma.loadFontAsync(overrideNode.fontName);\n overrideNode.characters = sourceNode.characters;\n fieldApplied = true;\n } else if (field in overrideNode) {\n // Direct property assignment\n overrideNode[field] = sourceNode[field];\n fieldApplied = true;\n }\n } catch (fieldError) {\n console.error(`Error applying field ${field}:`, fieldError);\n }\n }\n\n if (fieldApplied) {\n appliedCount++;\n }\n }\n\n if (appliedCount > 0) {\n totalAppliedCount += appliedCount;\n results.push({\n success: true,\n instanceId: targetInstance.id,\n instanceName: targetInstance.name,\n appliedCount\n });\n console.log(`Applied ${appliedCount} overrides to \"${targetInstance.name}\"`);\n } else {\n results.push({\n success: false,\n instanceId: targetInstance.id,\n instanceName: targetInstance.name,\n message: \"No overrides were applied\"\n });\n }\n } catch (instanceError) {\n console.error(`Error processing instance \"${targetInstance.name}\":`, instanceError);\n results.push({\n success: false,\n instanceId: targetInstance.id,\n instanceName: targetInstance.name,\n message: `Error: ${instanceError.message}`\n });\n }\n }\n\n // Return results\n if (totalAppliedCount > 0) {\n const instanceCount = results.filter(r => r.success).length;\n const message = `Applied ${totalAppliedCount} overrides to ${instanceCount} instances`;\n figma.notify(message);\n return {\n success: true,\n message,\n totalCount: totalAppliedCount,\n results\n };\n } else {\n const message = \"No overrides applied to any instance\";\n figma.notify(message);\n return { success: false, message, results };\n }\n\n } catch (error) {\n console.error(\"Error in setInstanceOverrides:\", error);\n const message = `Error: ${error.message}`;\n figma.notify(message);\n return { success: false, message };\n }\n}\n\nasync function setLayoutMode(params) {\n const { nodeId, layoutMode = \"NONE\", layoutWrap = \"NO_WRAP\" } = params || {};\n\n // Get the target node\n const node = await figma.getNodeByIdAsync(nodeId);\n if (!node) {\n throw new Error(`Node with ID ${nodeId} not found`);\n }\n\n // Check if node is a frame or component that supports layoutMode\n if (\n node.type !== \"FRAME\" &&\n node.type !== \"COMPONENT\" &&\n node.type !== \"COMPONENT_SET\" &&\n node.type !== \"INSTANCE\"\n ) {\n throw new Error(`Node type ${node.type} does not support layoutMode`);\n }\n\n // Set layout mode\n node.layoutMode = layoutMode;\n\n // Set layoutWrap if applicable\n if (layoutMode !== \"NONE\") {\n node.layoutWrap = layoutWrap;\n }\n\n return {\n id: node.id,\n name: node.name,\n layoutMode: node.layoutMode,\n layoutWrap: node.layoutWrap,\n };\n}\n\nasync function setPadding(params) {\n const { nodeId, paddingTop, paddingRight, paddingBottom, paddingLeft } =\n params || {};\n\n // Get the target node\n const node = await figma.getNodeByIdAsync(nodeId);\n if (!node) {\n throw new Error(`Node with ID ${nodeId} not found`);\n }\n\n // Check if node is a frame or component that supports padding\n if (\n node.type !== \"FRAME\" &&\n node.type !== \"COMPONENT\" &&\n node.type !== \"COMPONENT_SET\" &&\n node.type !== \"INSTANCE\"\n ) {\n throw new Error(`Node type ${node.type} does not support padding`);\n }\n\n // Check if the node has auto-layout enabled\n if (node.layoutMode === \"NONE\") {\n throw new Error(\n \"Padding can only be set on auto-layout frames (layoutMode must not be NONE)\"\n );\n }\n\n // Set padding values if provided\n if (paddingTop !== undefined) node.paddingTop = paddingTop;\n if (paddingRight !== undefined) node.paddingRight = paddingRight;\n if (paddingBottom !== undefined) node.paddingBottom = paddingBottom;\n if (paddingLeft !== undefined) node.paddingLeft = paddingLeft;\n\n return {\n id: node.id,\n name: node.name,\n paddingTop: node.paddingTop,\n paddingRight: node.paddingRight,\n paddingBottom: node.paddingBottom,\n paddingLeft: node.paddingLeft,\n };\n}\n\nasync function setAxisAlign(params) {\n const { nodeId, primaryAxisAlignItems, counterAxisAlignItems } = params || {};\n\n // Get the target node\n const node = await figma.getNodeByIdAsync(nodeId);\n if (!node) {\n throw new Error(`Node with ID ${nodeId} not found`);\n }\n\n // Check if node is a frame or component that supports axis alignment\n if (\n node.type !== \"FRAME\" &&\n node.type !== \"COMPONENT\" &&\n node.type !== \"COMPONENT_SET\" &&\n node.type !== \"INSTANCE\"\n ) {\n throw new Error(`Node type ${node.type} does not support axis alignment`);\n }\n\n // Check if the node has auto-layout enabled\n if (node.layoutMode === \"NONE\") {\n throw new Error(\n \"Axis alignment can only be set on auto-layout frames (layoutMode must not be NONE)\"\n );\n }\n\n // Validate and set primaryAxisAlignItems if provided\n if (primaryAxisAlignItems !== undefined) {\n if (\n ![\"MIN\", \"MAX\", \"CENTER\", \"SPACE_BETWEEN\"].includes(primaryAxisAlignItems)\n ) {\n throw new Error(\n \"Invalid primaryAxisAlignItems value. Must be one of: MIN, MAX, CENTER, SPACE_BETWEEN\"\n );\n }\n node.primaryAxisAlignItems = primaryAxisAlignItems;\n }\n\n // Validate and set counterAxisAlignItems if provided\n if (counterAxisAlignItems !== undefined) {\n if (![\"MIN\", \"MAX\", \"CENTER\", \"BASELINE\"].includes(counterAxisAlignItems)) {\n throw new Error(\n \"Invalid counterAxisAlignItems value. Must be one of: MIN, MAX, CENTER, BASELINE\"\n );\n }\n // BASELINE is only valid for horizontal layout\n if (\n counterAxisAlignItems === \"BASELINE\" &&\n node.layoutMode !== \"HORIZONTAL\"\n ) {\n throw new Error(\n \"BASELINE alignment is only valid for horizontal auto-layout frames\"\n );\n }\n node.counterAxisAlignItems = counterAxisAlignItems;\n }\n\n return {\n id: node.id,\n name: node.name,\n primaryAxisAlignItems: node.primaryAxisAlignItems,\n counterAxisAlignItems: node.counterAxisAlignItems,\n layoutMode: node.layoutMode,\n };\n}\n\nasync function setLayoutSizing(params) {\n const { nodeId, layoutSizingHorizontal, layoutSizingVertical } = params || {};\n\n // Get the target node\n const node = await figma.getNodeByIdAsync(nodeId);\n if (!node) {\n throw new Error(`Node with ID ${nodeId} not found`);\n }\n\n // Check if node is a frame or component that supports layout sizing\n if (\n node.type !== \"FRAME\" &&\n node.type !== \"COMPONENT\" &&\n node.type !== \"COMPONENT_SET\" &&\n node.type !== \"INSTANCE\"\n ) {\n throw new Error(`Node type ${node.type} does not support layout sizing`);\n }\n\n // Check if the node has auto-layout enabled\n if (node.layoutMode === \"NONE\") {\n throw new Error(\n \"Layout sizing can only be set on auto-layout frames (layoutMode must not be NONE)\"\n );\n }\n\n // Validate and set layoutSizingHorizontal if provided\n if (layoutSizingHorizontal !== undefined) {\n if (![\"FIXED\", \"HUG\", \"FILL\"].includes(layoutSizingHorizontal)) {\n throw new Error(\n \"Invalid layoutSizingHorizontal value. Must be one of: FIXED, HUG, FILL\"\n );\n }\n // HUG is only valid on auto-layout frames and text nodes\n if (\n layoutSizingHorizontal === \"HUG\" &&\n ![\"FRAME\", \"TEXT\"].includes(node.type)\n ) {\n throw new Error(\n \"HUG sizing is only valid on auto-layout frames and text nodes\"\n );\n }\n // FILL is only valid on auto-layout children\n if (\n layoutSizingHorizontal === \"FILL\" &&\n (!node.parent || node.parent.layoutMode === \"NONE\")\n ) {\n throw new Error(\"FILL sizing is only valid on auto-layout children\");\n }\n node.layoutSizingHorizontal = layoutSizingHorizontal;\n }\n\n // Validate and set layoutSizingVertical if provided\n if (layoutSizingVertical !== undefined) {\n if (![\"FIXED\", \"HUG\", \"FILL\"].includes(layoutSizingVertical)) {\n throw new Error(\n \"Invalid layoutSizingVertical value. Must be one of: FIXED, HUG, FILL\"\n );\n }\n // HUG is only valid on auto-layout frames and text nodes\n if (\n layoutSizingVertical === \"HUG\" &&\n ![\"FRAME\", \"TEXT\"].includes(node.type)\n ) {\n throw new Error(\n \"HUG sizing is only valid on auto-layout frames and text nodes\"\n );\n }\n // FILL is only valid on auto-layout children\n if (\n layoutSizingVertical === \"FILL\" &&\n (!node.parent || node.parent.layoutMode === \"NONE\")\n ) {\n throw new Error(\"FILL sizing is only valid on auto-layout children\");\n }\n node.layoutSizingVertical = layoutSizingVertical;\n }\n\n return {\n id: node.id,\n name: node.name,\n layoutSizingHorizontal: node.layoutSizingHorizontal,\n layoutSizingVertical: node.layoutSizingVertical,\n layoutMode: node.layoutMode,\n };\n}\n\nasync function setItemSpacing(params) {\n const { nodeId, itemSpacing } = params || {};\n\n // Get the target node\n const node = await figma.getNodeByIdAsync(nodeId);\n if (!node) {\n throw new Error(`Node with ID ${nodeId} not found`);\n }\n\n // Check if node is a frame or component that supports item spacing\n if (\n node.type !== \"FRAME\" &&\n node.type !== \"COMPONENT\" &&\n node.type !== \"COMPONENT_SET\" &&\n node.type !== \"INSTANCE\"\n ) {\n throw new Error(`Node type ${node.type} does not support item spacing`);\n }\n\n // Check if the node has auto-layout enabled\n if (node.layoutMode === \"NONE\") {\n throw new Error(\n \"Item spacing can only be set on auto-layout frames (layoutMode must not be NONE)\"\n );\n }\n\n // Set item spacing\n if (itemSpacing !== undefined) {\n if (typeof itemSpacing !== \"number\") {\n throw new Error(\"Item spacing must be a number\");\n }\n node.itemSpacing = itemSpacing;\n }\n\n return {\n id: node.id,\n name: node.name,\n itemSpacing: node.itemSpacing,\n layoutMode: node.layoutMode,\n };\n}\n\nasync function setDefaultConnector(params) {\n const { connectorId } = params || {};\n \n // If connectorId is provided, search and set by that ID (do not check existing storage)\n if (connectorId) {\n // Get node by specified ID\n const node = await figma.getNodeByIdAsync(connectorId);\n if (!node) {\n throw new Error(`Connector node not found with ID: ${connectorId}`);\n }\n \n // Check node type\n if (node.type !== 'CONNECTOR') {\n throw new Error(`Node is not a connector: ${connectorId}`);\n }\n \n // Set the found connector as the default connector\n await figma.clientStorage.setAsync('defaultConnectorId', connectorId);\n \n return {\n success: true,\n message: `Default connector set to: ${connectorId}`,\n connectorId: connectorId\n };\n } \n // If connectorId is not provided, check existing storage\n else {\n // Check if there is an existing default connector in client storage\n try {\n const existingConnectorId = await figma.clientStorage.getAsync('defaultConnectorId');\n \n // If there is an existing connector ID, check if the node is still valid\n if (existingConnectorId) {\n try {\n const existingConnector = await figma.getNodeByIdAsync(existingConnectorId);\n \n // If the stored connector still exists and is of type CONNECTOR\n if (existingConnector && existingConnector.type === 'CONNECTOR') {\n return {\n success: true,\n message: `Default connector is already set to: ${existingConnectorId}`,\n connectorId: existingConnectorId,\n exists: true\n };\n }\n // The stored connector is no longer valid - find a new connector\n else {\n console.log(`Stored connector ID ${existingConnectorId} is no longer valid, finding a new connector...`);\n }\n } catch (error) {\n console.log(`Error finding stored connector: ${error.message}. Will try to set a new one.`);\n }\n }\n } catch (error) {\n console.log(`Error checking for existing connector: ${error.message}`);\n }\n \n // If there is no stored default connector or it is invalid, find one in the current page\n try {\n // Find CONNECTOR type nodes in the current page\n const currentPageConnectors = figma.currentPage.findAllWithCriteria({ types: ['CONNECTOR'] });\n \n if (currentPageConnectors && currentPageConnectors.length > 0) {\n // Use the first connector found\n const foundConnector = currentPageConnectors[0];\n const autoFoundId = foundConnector.id;\n \n // Set the found connector as the default connector\n await figma.clientStorage.setAsync('defaultConnectorId', autoFoundId);\n \n return {\n success: true,\n message: `Automatically found and set default connector to: ${autoFoundId}`,\n connectorId: autoFoundId,\n autoSelected: true\n };\n } else {\n // If no connector is found in the current page, show a guide message\n throw new Error('No connector found in the current page. Please create a connector in Figma first or specify a connector ID.');\n }\n } catch (error) {\n // Error occurred while running findAllWithCriteria\n throw new Error(`Failed to find a connector: ${error.message}`);\n }\n }\n}\n\nasync function createCursorNode(targetNodeId) {\n const svgString = `\n \n `;\n try {\n const targetNode = await figma.getNodeByIdAsync(targetNodeId);\n if (!targetNode) throw new Error(\"Target node not found\");\n\n // The targetNodeId has semicolons since it is a nested node.\n // So we need to get the parent node ID from the target node ID and check if we can appendChild to it or not.\n let parentNodeId = targetNodeId.includes(';') \n ? targetNodeId.split(';')[0] \n : targetNodeId;\n if (!parentNodeId) throw new Error(\"Could not determine parent node ID\");\n\n // Find the parent node to append cursor node as child\n let parentNode = await figma.getNodeByIdAsync(parentNodeId);\n if (!parentNode) throw new Error(\"Parent node not found\");\n\n // If the parent node is not eligible to appendChild, set the parentNode to the parent of the parentNode\n if (parentNode.type === 'INSTANCE' || parentNode.type === 'COMPONENT' || parentNode.type === 'COMPONENT_SET') {\n parentNode = parentNode.parent;\n if (!parentNode) throw new Error(\"Parent node not found\");\n }\n\n // Create the cursor node\n const importedNode = await figma.createNodeFromSvg(svgString);\n if (!importedNode || !importedNode.id) {\n throw new Error(\"Failed to create imported cursor node\");\n }\n importedNode.name = \"TTF_Connector / Mouse Cursor\";\n importedNode.resize(48, 48);\n\n const cursorNode = importedNode.findOne(node => node.type === 'VECTOR');\n if (cursorNode) {\n cursorNode.fills = [{\n type: 'SOLID',\n color: { r: 0, g: 0, b: 0 },\n opacity: 1\n }];\n cursorNode.strokes = [{\n type: 'SOLID',\n color: { r: 1, g: 1, b: 1 },\n opacity: 1\n }];\n cursorNode.strokeWeight = 2;\n cursorNode.strokeAlign = 'OUTSIDE';\n cursorNode.effects = [{\n type: \"DROP_SHADOW\",\n color: { r: 0, g: 0, b: 0, a: 0.3 },\n offset: { x: 1, y: 1 },\n radius: 2,\n spread: 0,\n visible: true,\n blendMode: \"NORMAL\"\n }];\n }\n\n // Append the cursor node to the parent node\n parentNode.appendChild(importedNode);\n\n // if the parentNode has auto-layout enabled, set the layoutPositioning to ABSOLUTE\n if ('layoutMode' in parentNode && parentNode.layoutMode !== 'NONE') {\n importedNode.layoutPositioning = 'ABSOLUTE';\n }\n\n // Adjust the importedNode's position to the targetNode's position\n if (\n targetNode.absoluteBoundingBox &&\n parentNode.absoluteBoundingBox\n ) {\n // if the targetNode has absoluteBoundingBox, set the importedNode's absoluteBoundingBox to the targetNode's absoluteBoundingBox\n console.log('targetNode.absoluteBoundingBox', targetNode.absoluteBoundingBox);\n console.log('parentNode.absoluteBoundingBox', parentNode.absoluteBoundingBox);\n importedNode.x = targetNode.absoluteBoundingBox.x - parentNode.absoluteBoundingBox.x + targetNode.absoluteBoundingBox.width / 2 - 48 / 2\n importedNode.y = targetNode.absoluteBoundingBox.y - parentNode.absoluteBoundingBox.y + targetNode.absoluteBoundingBox.height / 2 - 48 / 2;\n } else if (\n 'x' in targetNode && 'y' in targetNode && 'width' in targetNode && 'height' in targetNode) {\n // if the targetNode has x, y, width, height, calculate center based on relative position\n console.log('targetNode.x/y/width/height', targetNode.x, targetNode.y, targetNode.width, targetNode.height);\n importedNode.x = targetNode.x + targetNode.width / 2 - 48 / 2;\n importedNode.y = targetNode.y + targetNode.height / 2 - 48 / 2;\n } else {\n // Fallback: Place at top-left of target if possible, otherwise at (0,0) relative to parent\n if ('x' in targetNode && 'y' in targetNode) {\n console.log('Fallback to targetNode x/y');\n importedNode.x = targetNode.x;\n importedNode.y = targetNode.y;\n } else {\n console.log('Fallback to (0,0)');\n importedNode.x = 0;\n importedNode.y = 0;\n }\n }\n\n // get the importedNode ID and the importedNode\n console.log('importedNode', importedNode);\n\n\n return { id: importedNode.id, node: importedNode };\n \n } catch (error) {\n console.error(\"Error creating cursor from SVG:\", error);\n return { id: null, node: null, error: error.message };\n }\n}\n\nasync function createConnections(params) {\n if (!params || !params.connections || !Array.isArray(params.connections)) {\n throw new Error('Missing or invalid connections parameter');\n }\n \n const { connections } = params;\n \n // Command ID for progress tracking\n const commandId = generateCommandId();\n sendProgressUpdate(\n commandId,\n \"create_connections\",\n \"started\",\n 0,\n connections.length,\n 0,\n `Starting to create ${connections.length} connections`\n );\n \n // Get default connector ID from client storage\n const defaultConnectorId = await figma.clientStorage.getAsync('defaultConnectorId');\n if (!defaultConnectorId) {\n throw new Error('No default connector set. Please try one of the following options to create connections:\\n1. Create a connector in FigJam and copy/paste it to your current page, then run the \"set_default_connector\" command.\\n2. Select an existing connector on the current page, then run the \"set_default_connector\" command.');\n }\n \n // Get the default connector\n const defaultConnector = await figma.getNodeByIdAsync(defaultConnectorId);\n if (!defaultConnector) {\n throw new Error(`Default connector not found with ID: ${defaultConnectorId}`);\n }\n if (defaultConnector.type !== 'CONNECTOR') {\n throw new Error(`Node is not a connector: ${defaultConnectorId}`);\n }\n \n // Results array for connection creation\n const results = [];\n let processedCount = 0;\n const totalCount = connections.length;\n \n // Preload fonts (used for text if provided)\n let fontLoaded = false;\n \n for (let i = 0; i < connections.length; i++) {\n try {\n const { startNodeId: originalStartId, endNodeId: originalEndId, text } = connections[i];\n let startId = originalStartId;\n let endId = originalEndId;\n\n // Check and potentially replace start node ID\n if (startId.includes(';')) {\n console.log(`Nested start node detected: ${startId}. Creating cursor node.`);\n const cursorResult = await createCursorNode(startId);\n if (!cursorResult || !cursorResult.id) {\n throw new Error(`Failed to create cursor node for nested start node: ${startId}`);\n }\n startId = cursorResult.id; \n } \n \n const startNode = await figma.getNodeByIdAsync(startId);\n if (!startNode) throw new Error(`Start node not found with ID: ${startId}`);\n\n // Check and potentially replace end node ID\n if (endId.includes(';')) {\n console.log(`Nested end node detected: ${endId}. Creating cursor node.`);\n const cursorResult = await createCursorNode(endId);\n if (!cursorResult || !cursorResult.id) {\n throw new Error(`Failed to create cursor node for nested end node: ${endId}`);\n }\n endId = cursorResult.id;\n }\n const endNode = await figma.getNodeByIdAsync(endId);\n if (!endNode) throw new Error(`End node not found with ID: ${endId}`);\n\n \n // Clone the default connector\n const clonedConnector = defaultConnector.clone();\n \n // Update connector name using potentially replaced node names\n clonedConnector.name = `TTF_Connector/${startNode.id}/${endNode.id}`;\n \n // Set start and end points using potentially replaced IDs\n clonedConnector.connectorStart = {\n endpointNodeId: startId,\n magnet: 'AUTO'\n };\n \n clonedConnector.connectorEnd = {\n endpointNodeId: endId,\n magnet: 'AUTO'\n };\n \n // Add text (if provided)\n if (text) {\n try {\n // Try to load the necessary fonts\n try {\n // First check if default connector has font and use the same\n if (defaultConnector.text && defaultConnector.text.fontName) {\n const fontName = defaultConnector.text.fontName;\n await figma.loadFontAsync(fontName);\n clonedConnector.text.fontName = fontName;\n } else {\n // Try default Inter font\n await figma.loadFontAsync({ family: \"Inter\", style: \"Regular\" });\n }\n } catch (fontError) {\n // If first font load fails, try another font style\n try {\n await figma.loadFontAsync({ family: \"Inter\", style: \"Medium\" });\n } catch (mediumFontError) {\n // If second font fails, try system font\n try {\n await figma.loadFontAsync({ family: \"System\", style: \"Regular\" });\n } catch (systemFontError) {\n // If all font loading attempts fail, throw error\n throw new Error(`Failed to load any font: ${fontError.message}`);\n }\n }\n }\n \n // Set the text\n clonedConnector.text.characters = text;\n } catch (textError) {\n console.error(\"Error setting text:\", textError);\n // Continue with connection even if text setting fails\n results.push({\n id: clonedConnector.id,\n startNodeId: startNodeId,\n endNodeId: endNodeId,\n text: \"\",\n textError: textError.message\n });\n \n // Continue to next connection\n continue;\n }\n }\n \n // Add to results (using the *original* IDs for reference if needed)\n results.push({\n id: clonedConnector.id,\n originalStartNodeId: originalStartId,\n originalEndNodeId: originalEndId,\n usedStartNodeId: startId, // ID actually used for connection\n usedEndNodeId: endId, // ID actually used for connection\n text: text || \"\"\n });\n \n // Update progress\n processedCount++;\n sendProgressUpdate(\n commandId,\n \"create_connections\",\n \"in_progress\",\n processedCount / totalCount,\n totalCount,\n processedCount,\n `Created connection ${processedCount}/${totalCount}`\n );\n \n } catch (error) {\n console.error(\"Error creating connection\", error);\n // Continue processing remaining connections even if an error occurs\n processedCount++;\n sendProgressUpdate(\n commandId,\n \"create_connections\",\n \"in_progress\",\n processedCount / totalCount,\n totalCount,\n processedCount,\n `Error creating connection: ${error.message}`\n );\n \n results.push({\n error: error.message,\n connectionInfo: connections[i]\n });\n }\n }\n \n // Completion update\n sendProgressUpdate(\n commandId,\n \"create_connections\",\n \"completed\",\n 1,\n totalCount,\n totalCount,\n `Completed creating ${results.length} connections`\n );\n \n return {\n success: true,\n count: results.length,\n connections: results\n };\n}\n", "middle_code": "async function exportNodeAsImage(params) {\n const { nodeId, scale = 1 } = params || {};\n const format = \"PNG\";\n if (!nodeId) {\n throw new Error(\"Missing nodeId parameter\");\n }\n const node = await figma.getNodeByIdAsync(nodeId);\n if (!node) {\n throw new Error(`Node not found with ID: ${nodeId}`);\n }\n if (!(\"exportAsync\" in node)) {\n throw new Error(`Node does not support exporting: ${nodeId}`);\n }\n try {\n const settings = {\n format: format,\n constraint: { type: \"SCALE\", value: scale },\n };\n const bytes = await node.exportAsync(settings);\n let mimeType;\n switch (format) {\n case \"PNG\":\n mimeType = \"image/png\";\n break;\n case \"JPG\":\n mimeType = \"image/jpeg\";\n break;\n case \"SVG\":\n mimeType = \"image/svg+xml\";\n break;\n case \"PDF\":\n mimeType = \"application/pdf\";\n break;\n default:\n mimeType = \"application/octet-stream\";\n }\n const base64 = customBase64Encode(bytes);\n return {\n nodeId,\n format,\n scale,\n mimeType,\n imageData: base64,\n };\n } catch (error) {\n throw new Error(`Error exporting node as image: ${error.message}`);\n }\n}", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "javascript", "sub_task_type": null}, "context_code": [["/cursor-talk-to-figma-mcp/src/cursor_mcp_plugin/setcharacters.js", "function uniqBy(arr, predicate) {\n const cb = typeof predicate === \"function\" ? predicate : (o) => o[predicate];\n return [\n ...arr\n .reduce((map, item) => {\n const key = item === null || item === undefined ? item : cb(item);\n\n map.has(key) || map.set(key, item);\n\n return map;\n }, new Map())\n .values(),\n ];\n}\nexport const setCharacters = async (node, characters, options) => {\n const fallbackFont = options?.fallbackFont || {\n family: \"Roboto\",\n style: \"Regular\",\n };\n try {\n if (node.fontName === figma.mixed) {\n if (options?.smartStrategy === \"prevail\") {\n const fontHashTree = {};\n for (let i = 1; i < node.characters.length; i++) {\n const charFont = node.getRangeFontName(i - 1, i);\n const key = `${charFont.family}::${charFont.style}`;\n fontHashTree[key] = fontHashTree[key] ? fontHashTree[key] + 1 : 1;\n }\n const prevailedTreeItem = Object.entries(fontHashTree).sort(\n (a, b) => b[1] - a[1]\n )[0];\n const [family, style] = prevailedTreeItem[0].split(\"::\");\n const prevailedFont = {\n family,\n style,\n };\n await figma.loadFontAsync(prevailedFont);\n node.fontName = prevailedFont;\n } else if (options?.smartStrategy === \"strict\") {\n return setCharactersWithStrictMatchFont(node, characters, fallbackFont);\n } else if (options?.smartStrategy === \"experimental\") {\n return setCharactersWithSmartMatchFont(node, characters, fallbackFont);\n } else {\n const firstCharFont = node.getRangeFontName(0, 1);\n await figma.loadFontAsync(firstCharFont);\n node.fontName = firstCharFont;\n }\n } else {\n await figma.loadFontAsync({\n family: node.fontName.family,\n style: node.fontName.style,\n });\n }\n } catch (err) {\n console.warn(\n `Failed to load \"${node.fontName[\"family\"]} ${node.fontName[\"style\"]}\" font and replaced with fallback \"${fallbackFont.family} ${fallbackFont.style}\"`,\n err\n );\n await figma.loadFontAsync(fallbackFont);\n node.fontName = fallbackFont;\n }\n try {\n node.characters = characters;\n return true;\n } catch (err) {\n console.warn(`Failed to set characters. Skipped.`, err);\n return false;\n }\n};\n\nconst setCharactersWithStrictMatchFont = async (\n node,\n characters,\n fallbackFont\n) => {\n const fontHashTree = {};\n for (let i = 1; i < node.characters.length; i++) {\n const startIdx = i - 1;\n const startCharFont = node.getRangeFontName(startIdx, i);\n const startCharFontVal = `${startCharFont.family}::${startCharFont.style}`;\n while (i < node.characters.length) {\n i++;\n const charFont = node.getRangeFontName(i - 1, i);\n if (startCharFontVal !== `${charFont.family}::${charFont.style}`) {\n break;\n }\n }\n fontHashTree[`${startIdx}_${i}`] = startCharFontVal;\n }\n await figma.loadFontAsync(fallbackFont);\n node.fontName = fallbackFont;\n node.characters = characters;\n console.log(fontHashTree);\n await Promise.all(\n Object.keys(fontHashTree).map(async (range) => {\n console.log(range, fontHashTree[range]);\n const [start, end] = range.split(\"_\");\n const [family, style] = fontHashTree[range].split(\"::\");\n const matchedFont = {\n family,\n style,\n };\n await figma.loadFontAsync(matchedFont);\n return node.setRangeFontName(Number(start), Number(end), matchedFont);\n })\n );\n return true;\n};\n\nconst getDelimiterPos = (str, delimiter, startIdx = 0, endIdx = str.length) => {\n const indices = [];\n let temp = startIdx;\n for (let i = startIdx; i < endIdx; i++) {\n if (\n str[i] === delimiter &&\n i + startIdx !== endIdx &&\n temp !== i + startIdx\n ) {\n indices.push([temp, i + startIdx]);\n temp = i + startIdx + 1;\n }\n }\n temp !== endIdx && indices.push([temp, endIdx]);\n return indices.filter(Boolean);\n};\n\nconst buildLinearOrder = (node) => {\n const fontTree = [];\n const newLinesPos = getDelimiterPos(node.characters, \"\\n\");\n newLinesPos.forEach(([newLinesRangeStart, newLinesRangeEnd], n) => {\n const newLinesRangeFont = node.getRangeFontName(\n newLinesRangeStart,\n newLinesRangeEnd\n );\n if (newLinesRangeFont === figma.mixed) {\n const spacesPos = getDelimiterPos(\n node.characters,\n \" \",\n newLinesRangeStart,\n newLinesRangeEnd\n );\n spacesPos.forEach(([spacesRangeStart, spacesRangeEnd], s) => {\n const spacesRangeFont = node.getRangeFontName(\n spacesRangeStart,\n spacesRangeEnd\n );\n if (spacesRangeFont === figma.mixed) {\n const spacesRangeFont = node.getRangeFontName(\n spacesRangeStart,\n spacesRangeStart[0]\n );\n fontTree.push({\n start: spacesRangeStart,\n delimiter: \" \",\n family: spacesRangeFont.family,\n style: spacesRangeFont.style,\n });\n } else {\n fontTree.push({\n start: spacesRangeStart,\n delimiter: \" \",\n family: spacesRangeFont.family,\n style: spacesRangeFont.style,\n });\n }\n });\n } else {\n fontTree.push({\n start: newLinesRangeStart,\n delimiter: \"\\n\",\n family: newLinesRangeFont.family,\n style: newLinesRangeFont.style,\n });\n }\n });\n return fontTree\n .sort((a, b) => +a.start - +b.start)\n .map(({ family, style, delimiter }) => ({ family, style, delimiter }));\n};\n\nconst setCharactersWithSmartMatchFont = async (\n node,\n characters,\n fallbackFont\n) => {\n const rangeTree = buildLinearOrder(node);\n const fontsToLoad = uniqBy(\n rangeTree,\n ({ family, style }) => `${family}::${style}`\n ).map(({ family, style }) => ({\n family,\n style,\n }));\n\n await Promise.all([...fontsToLoad, fallbackFont].map(figma.loadFontAsync));\n\n node.fontName = fallbackFont;\n node.characters = characters;\n\n let prevPos = 0;\n rangeTree.forEach(({ family, style, delimiter }) => {\n if (prevPos < node.characters.length) {\n const delimeterPos = node.characters.indexOf(delimiter, prevPos);\n const endPos =\n delimeterPos > prevPos ? delimeterPos : node.characters.length;\n const matchedFont = {\n family,\n style,\n };\n node.setRangeFontName(prevPos, endPos, matchedFont);\n prevPos = endPos + 1;\n }\n });\n return true;\n};\n"]], "task_instance_info": {"created_time": "2025-08-20 23:58:36", "created_task_model": "DeepSeek-R1", "function_skeleton": "async function exportNodeAsImage (params) {}", "code_description": "This code segment functions to: Export a visual element as encoded image data using specified dimensions and formatting parameters, then convert the binary output into a standardized text-based representation for transmission while preserving critical metadata about the output format and scaling characteristics."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```javascript\n[TASK_BEGIN]\nasync function exportNodeAsImage(params) {\n const { nodeId, format = \"PNG\", scale = 1, constraintType = \"SCALE\" } = params || {};\n\n if (!nodeId) {\n throw new Error(\"Missing nodeId parameter\");\n }\n\n const node = await figma.getNodeByIdAsync(nodeId);\n if (!node) {\n throw new Error(`Node not found with ID: ${nodeId}`);\n }\n\n const exportSettings = {\n format: format.toUpperCase(),\n constraint: { type: constraintType, value: scale }\n };\n\n try {\n const imageData = await node.exportAsync(exportSettings);\n const base64Image = customBase64Encode(imageData);\n\n return {\n id: node.id,\n name: node.name,\n format: exportSettings.format,\n scale: scale,\n imageData: base64Image,\n mimeType: format === \"JPG\" ? \"image/jpeg\" : \"image/png\",\n size: imageData.byteLength\n };\n } catch (error) {\n throw new Error(`Failed to export node: ${error.message}`);\n }\n}\n[TASK_END]\n```", "inference_time": "2025-08-20 23-59-23"}, "editdistance_info": {"edit_distance": 39.7306, "calculate_time": "2025-08-20 23:59:23", "true_code_clean": "async function exportNodeAsImage(params) {\n const { nodeId, scale = 1 } = params || {};\n const format = \"PNG\";\n if (!nodeId) {\n throw new Error(\"Missing nodeId parameter\");\n }\n const node = await figma.getNodeByIdAsync(nodeId);\n if (!node) {\n throw new Error(`Node not found with ID: ${nodeId}`);\n }\n if (!(\"exportAsync\" in node)) {\n throw new Error(`Node does not support exporting: ${nodeId}`);\n }\n try {\n const settings = {\n format: format,\n constraint: { type: \"SCALE\", value: scale },\n };\n const bytes = await node.exportAsync(settings);\n let mimeType;\n switch (format) {\n case \"PNG\":\n mimeType = \"image/png\";\n break;\n case \"JPG\":\n mimeType = \"image/jpeg\";\n break;\n case \"SVG\":\n mimeType = \"image/svg+xml\";\n break;\n case \"PDF\":\n mimeType = \"application/pdf\";\n break;\n default:\n mimeType = \"application/octet-stream\";\n }\n const base64 = customBase64Encode(bytes);\n return {\n nodeId,\n format,\n scale,\n mimeType,\n imageData: base64,\n };\n } catch (error) {\n throw new Error(`Error exporting node as image: ${error.message}`);\n }\n}", "predict_code_clean": "async function exportNodeAsImage(params) {\n const { nodeId, format = \"PNG\", scale = 1, constraintType = \"SCALE\" } = params || {};\n if (!nodeId) {\n throw new Error(\"Missing nodeId parameter\");\n }\n const node = await figma.getNodeByIdAsync(nodeId);\n if (!node) {\n throw new Error(`Node not found with ID: ${nodeId}`);\n }\n const exportSettings = {\n format: format.toUpperCase(),\n constraint: { type: constraintType, value: scale }\n };\n try {\n const imageData = await node.exportAsync(exportSettings);\n const base64Image = customBase64Encode(imageData);\n return {\n id: node.id,\n name: node.name,\n format: exportSettings.format,\n scale: scale,\n imageData: base64Image,\n mimeType: format === \"JPG\" ? \"image/jpeg\" : \"image/png\",\n size: imageData.byteLength\n };\n } catch (error) {\n throw new Error(`Failed to export node: ${error.message}`);\n }\n}"}} {"repo_name": "cursor-talk-to-figma-mcp", "file_name": "/cursor-talk-to-figma-mcp/src/cursor_mcp_plugin/code.js", "inference_info": {"prefix_code": "// This is the main code file for the Cursor MCP Figma plugin\n// It handles Figma API commands\n\n// Plugin state\nconst state = {\n serverPort: 3055, // Default port\n};\n\n\n// Helper function for progress updates\nfunction sendProgressUpdate(\n commandId,\n commandType,\n status,\n progress,\n totalItems,\n processedItems,\n message,\n payload = null\n) {\n const update = {\n type: \"command_progress\",\n commandId,\n commandType,\n status,\n progress,\n totalItems,\n processedItems,\n message,\n timestamp: Date.now(),\n };\n\n // Add optional chunk information if present\n if (payload) {\n if (\n payload.currentChunk !== undefined &&\n payload.totalChunks !== undefined\n ) {\n update.currentChunk = payload.currentChunk;\n update.totalChunks = payload.totalChunks;\n update.chunkSize = payload.chunkSize;\n }\n update.payload = payload;\n }\n\n // Send to UI\n figma.ui.postMessage(update);\n console.log(`Progress update: ${status} - ${progress}% - ${message}`);\n\n return update;\n}\n\n// Show UI\nfigma.showUI(__html__, { width: 350, height: 450 });\n\n// Plugin commands from UI\nfigma.ui.onmessage = async (msg) => {\n switch (msg.type) {\n case \"update-settings\":\n updateSettings(msg);\n break;\n case \"notify\":\n figma.notify(msg.message);\n break;\n case \"close-plugin\":\n figma.closePlugin();\n break;\n case \"execute-command\":\n // Execute commands received from UI (which gets them from WebSocket)\n try {\n const result = await handleCommand(msg.command, msg.params);\n // Send result back to UI\n figma.ui.postMessage({\n type: \"command-result\",\n id: msg.id,\n result,\n });\n } catch (error) {\n figma.ui.postMessage({\n type: \"command-error\",\n id: msg.id,\n error: error.message || \"Error executing command\",\n });\n }\n break;\n }\n};\n\n// Listen for plugin commands from menu\nfigma.on(\"run\", ({ command }) => {\n figma.ui.postMessage({ type: \"auto-connect\" });\n});\n\n// Update plugin settings\nfunction updateSettings(settings) {\n if (settings.serverPort) {\n state.serverPort = settings.serverPort;\n }\n\n figma.clientStorage.setAsync(\"settings\", {\n serverPort: state.serverPort,\n });\n}\n\n// Handle commands from UI\nasync function handleCommand(command, params) {\n switch (command) {\n case \"get_document_info\":\n return await getDocumentInfo();\n case \"get_selection\":\n return await getSelection();\n case \"get_node_info\":\n if (!params || !params.nodeId) {\n throw new Error(\"Missing nodeId parameter\");\n }\n return await getNodeInfo(params.nodeId);\n case \"get_nodes_info\":\n if (!params || !params.nodeIds || !Array.isArray(params.nodeIds)) {\n throw new Error(\"Missing or invalid nodeIds parameter\");\n }\n return await getNodesInfo(params.nodeIds);\n case \"read_my_design\":\n return await readMyDesign();\n case \"create_rectangle\":\n return await createRectangle(params);\n case \"create_frame\":\n return await createFrame(params);\n case \"create_text\":\n return await createText(params);\n case \"set_fill_color\":\n return await setFillColor(params);\n case \"set_stroke_color\":\n return await setStrokeColor(params);\n case \"move_node\":\n return await moveNode(params);\n case \"resize_node\":\n return await resizeNode(params);\n case \"delete_node\":\n return await deleteNode(params);\n case \"delete_multiple_nodes\":\n return await deleteMultipleNodes(params);\n case \"get_styles\":\n return await getStyles();\n case \"get_local_components\":\n return await getLocalComponents();\n // case \"get_team_components\":\n // return await getTeamComponents();\n case \"create_component_instance\":\n return await createComponentInstance(params);\n case \"export_node_as_image\":\n return await exportNodeAsImage(params);\n case \"set_corner_radius\":\n return await setCornerRadius(params);\n case \"set_text_content\":\n return await setTextContent(params);\n case \"clone_node\":\n return await cloneNode(params);\n case \"scan_text_nodes\":\n return await scanTextNodes(params);\n case \"set_multiple_text_contents\":\n return await setMultipleTextContents(params);\n case \"get_annotations\":\n return await getAnnotations(params);\n case \"set_annotation\":\n return await setAnnotation(params);\n case \"scan_nodes_by_types\":\n return await scanNodesByTypes(params);\n case \"set_multiple_annotations\":\n return await setMultipleAnnotations(params);\n case \"get_instance_overrides\":\n // Check if instanceNode parameter is provided\n if (params && params.instanceNodeId) {\n // Get the instance node by ID\n const instanceNode = await figma.getNodeByIdAsync(params.instanceNodeId);\n if (!instanceNode) {\n throw new Error(`Instance node not found with ID: ${params.instanceNodeId}`);\n }\n return await getInstanceOverrides(instanceNode);\n }\n // Call without instance node if not provided\n return await getInstanceOverrides();\n\n case \"set_instance_overrides\":\n // Check if instanceNodeIds parameter is provided\n if (params && params.targetNodeIds) {\n // Validate that targetNodeIds is an array\n if (!Array.isArray(params.targetNodeIds)) {\n throw new Error(\"targetNodeIds must be an array\");\n }\n\n // Get the instance nodes by IDs\n const targetNodes = await getValidTargetInstances(params.targetNodeIds);\n if (!targetNodes.success) {\n figma.notify(targetNodes.message);\n return { success: false, message: targetNodes.message };\n }\n\n if (params.sourceInstanceId) {\n\n // get source instance data\n let sourceInstanceData = null;\n sourceInstanceData = await getSourceInstanceData(params.sourceInstanceId);\n\n if (!sourceInstanceData.success) {\n figma.notify(sourceInstanceData.message);\n return { success: false, message: sourceInstanceData.message };\n }\n return await setInstanceOverrides(targetNodes.targetInstances, sourceInstanceData);\n } else {\n throw new Error(\"Missing sourceInstanceId parameter\");\n }\n }\n case \"set_layout_mode\":\n return await setLayoutMode(params);\n case \"set_padding\":\n return await setPadding(params);\n case \"set_axis_align\":\n return await setAxisAlign(params);\n case \"set_layout_sizing\":\n return await setLayoutSizing(params);\n case \"set_item_spacing\":\n return await setItemSpacing(params);\n case \"get_reactions\":\n if (!params || !params.nodeIds || !Array.isArray(params.nodeIds)) {\n throw new Error(\"Missing or invalid nodeIds parameter\");\n }\n return await getReactions(params.nodeIds); \n case \"set_default_connector\":\n return await setDefaultConnector(params);\n case \"create_connections\":\n return await createConnections(params);\n default:\n throw new Error(`Unknown command: ${command}`);\n }\n}\n\n// Command implementations\n\nasync function getDocumentInfo() {\n await figma.currentPage.loadAsync();\n const page = figma.currentPage;\n return {\n name: page.name,\n id: page.id,\n type: page.type,\n children: page.children.map((node) => ({\n id: node.id,\n name: node.name,\n type: node.type,\n })),\n currentPage: {\n id: page.id,\n name: page.name,\n childCount: page.children.length,\n },\n pages: [\n {\n id: page.id,\n name: page.name,\n childCount: page.children.length,\n },\n ],\n };\n}\n\nasync function getSelection() {\n return {\n selectionCount: figma.currentPage.selection.length,\n selection: figma.currentPage.selection.map((node) => ({\n id: node.id,\n name: node.name,\n type: node.type,\n visible: node.visible,\n })),\n };\n}\n\nfunction rgbaToHex(color) {\n var r = Math.round(color.r * 255);\n var g = Math.round(color.g * 255);\n var b = Math.round(color.b * 255);\n var a = color.a !== undefined ? Math.round(color.a * 255) : 255;\n\n if (a === 255) {\n return (\n \"#\" +\n [r, g, b]\n .map((x) => {\n return x.toString(16).padStart(2, \"0\");\n })\n .join(\"\")\n );\n }\n\n return (\n \"#\" +\n [r, g, b, a]\n .map((x) => {\n return x.toString(16).padStart(2, \"0\");\n })\n .join(\"\")\n );\n}\n\nfunction filterFigmaNode(node) {\n if (node.type === \"VECTOR\") {\n return null;\n }\n\n var filtered = {\n id: node.id,\n name: node.name,\n type: node.type,\n };\n\n if (node.fills && node.fills.length > 0) {\n filtered.fills = node.fills.map((fill) => {\n var processedFill = Object.assign({}, fill);\n delete processedFill.boundVariables;\n delete processedFill.imageRef;\n\n if (processedFill.gradientStops) {\n processedFill.gradientStops = processedFill.gradientStops.map(\n (stop) => {\n var processedStop = Object.assign({}, stop);\n if (processedStop.color) {\n processedStop.color = rgbaToHex(processedStop.color);\n }\n delete processedStop.boundVariables;\n return processedStop;\n }\n );\n }\n\n if (processedFill.color) {\n processedFill.color = rgbaToHex(processedFill.color);\n }\n\n return processedFill;\n });\n }\n\n if (node.strokes && node.strokes.length > 0) {\n filtered.strokes = node.strokes.map((stroke) => {\n var processedStroke = Object.assign({}, stroke);\n delete processedStroke.boundVariables;\n if (processedStroke.color) {\n processedStroke.color = rgbaToHex(processedStroke.color);\n }\n return processedStroke;\n });\n }\n\n if (node.cornerRadius !== undefined) {\n filtered.cornerRadius = node.cornerRadius;\n }\n\n if (node.absoluteBoundingBox) {\n filtered.absoluteBoundingBox = node.absoluteBoundingBox;\n }\n\n if (node.characters) {\n filtered.characters = node.characters;\n }\n\n if (node.style) {\n filtered.style = {\n fontFamily: node.style.fontFamily,\n fontStyle: node.style.fontStyle,\n fontWeight: node.style.fontWeight,\n fontSize: node.style.fontSize,\n textAlignHorizontal: node.style.textAlignHorizontal,\n letterSpacing: node.style.letterSpacing,\n lineHeightPx: node.style.lineHeightPx,\n };\n }\n\n if (node.children) {\n filtered.children = node.children\n .map((child) => {\n return filterFigmaNode(child);\n })\n .filter((child) => {\n return child !== null;\n });\n }\n\n return filtered;\n}\n\nasync function getNodeInfo(nodeId) {\n const node = await figma.getNodeByIdAsync(nodeId);\n\n if (!node) {\n throw new Error(`Node not found with ID: ${nodeId}`);\n }\n\n const response = await node.exportAsync({\n format: \"JSON_REST_V1\",\n });\n\n return filterFigmaNode(response.document);\n}\n\nasync function getNodesInfo(nodeIds) {\n try {\n // Load all nodes in parallel\n const nodes = await Promise.all(\n nodeIds.map((id) => figma.getNodeByIdAsync(id))\n );\n\n // Filter out any null values (nodes that weren't found)\n const validNodes = nodes.filter((node) => node !== null);\n\n // Export all valid nodes in parallel\n const responses = await Promise.all(\n validNodes.map(async (node) => {\n const response = await node.exportAsync({\n format: \"JSON_REST_V1\",\n });\n return {\n nodeId: node.id,\n document: filterFigmaNode(response.document),\n };\n })\n );\n\n return responses;\n } catch (error) {\n throw new Error(`Error getting nodes info: ${error.message}`);\n }\n}\n\nasync function getReactions(nodeIds) {\n try {\n const commandId = generateCommandId();\n sendProgressUpdate(\n commandId,\n \"get_reactions\",\n \"started\",\n 0,\n nodeIds.length,\n 0,\n `Starting deep search for reactions in ${nodeIds.length} nodes and their children`\n );\n\n // Function to find nodes with reactions from the node and all its children\n async function findNodesWithReactions(node, processedNodes = new Set(), depth = 0, results = []) {\n // Skip already processed nodes (prevent circular references)\n if (processedNodes.has(node.id)) {\n return results;\n }\n \n processedNodes.add(node.id);\n \n // Check if the current node has reactions\n let filteredReactions = [];\n if (node.reactions && node.reactions.length > 0) {\n // Filter out reactions with navigation === 'CHANGE_TO'\n filteredReactions = node.reactions.filter(r => {\n // Some reactions may have action or actions array\n if (r.action && r.action.navigation === 'CHANGE_TO') return false;\n if (Array.isArray(r.actions)) {\n // If any action in actions array is CHANGE_TO, exclude\n return !r.actions.some(a => a.navigation === 'CHANGE_TO');\n }\n return true;\n });\n }\n const hasFilteredReactions = filteredReactions.length > 0;\n \n // If the node has filtered reactions, add it to results and apply highlight effect\n if (hasFilteredReactions) {\n results.push({\n id: node.id,\n name: node.name,\n type: node.type,\n depth: depth,\n hasReactions: true,\n reactions: filteredReactions,\n path: getNodePath(node)\n });\n // Apply highlight effect (orange border)\n await highlightNodeWithAnimation(node);\n }\n \n // If node has children, recursively search them\n if (node.children) {\n for (const child of node.children) {\n await findNodesWithReactions(child, processedNodes, depth + 1, results);\n }\n }\n \n return results;\n }\n \n // Function to apply animated highlight effect to a node\n async function highlightNodeWithAnimation(node) {\n // Save original stroke properties\n const originalStrokeWeight = node.strokeWeight;\n const originalStrokes = node.strokes ? [...node.strokes] : [];\n \n try {\n // Apply orange border stroke\n node.strokeWeight = 4;\n node.strokes = [{\n type: 'SOLID',\n color: { r: 1, g: 0.5, b: 0 }, // Orange color\n opacity: 0.8\n }];\n \n // Set timeout for animation effect (restore to original after 1.5 seconds)\n setTimeout(() => {\n try {\n // Restore original stroke properties\n node.strokeWeight = originalStrokeWeight;\n node.strokes = originalStrokes;\n } catch (restoreError) {\n console.error(`Error restoring node stroke: ${restoreError.message}`);\n }\n }, 1500);\n } catch (highlightError) {\n console.error(`Error highlighting node: ${highlightError.message}`);\n // Continue even if highlighting fails\n }\n }\n \n // Get node hierarchy path as a string\n function getNodePath(node) {\n const path = [];\n let current = node;\n \n while (current && current.parent) {\n path.unshift(current.name);\n current = current.parent;\n }\n \n return path.join(' > ');\n }\n\n // Array to store all results\n let allResults = [];\n let processedCount = 0;\n const totalCount = nodeIds.length;\n \n // Iterate through each node and its children to search for reactions\n for (let i = 0; i < nodeIds.length; i++) {\n try {\n const nodeId = nodeIds[i];\n const node = await figma.getNodeByIdAsync(nodeId);\n \n if (!node) {\n processedCount++;\n sendProgressUpdate(\n commandId,\n \"get_reactions\",\n \"in_progress\",\n processedCount / totalCount,\n totalCount,\n processedCount,\n `Node not found: ${nodeId}`\n );\n continue;\n }\n \n // Search for reactions in the node and its children\n const processedNodes = new Set();\n const nodeResults = await findNodesWithReactions(node, processedNodes);\n \n // Add results\n allResults = allResults.concat(nodeResults);\n \n // Update progress\n processedCount++;\n sendProgressUpdate(\n commandId,\n \"get_reactions\",\n \"in_progress\",\n processedCount / totalCount,\n totalCount,\n processedCount,\n `Processed node ${processedCount}/${totalCount}, found ${nodeResults.length} nodes with reactions`\n );\n } catch (error) {\n processedCount++;\n sendProgressUpdate(\n commandId,\n \"get_reactions\",\n \"in_progress\",\n processedCount / totalCount,\n totalCount,\n processedCount,\n `Error processing node: ${error.message}`\n );\n }\n }\n\n // Completion update\n sendProgressUpdate(\n commandId,\n \"get_reactions\",\n \"completed\",\n 1,\n totalCount,\n totalCount,\n `Completed deep search: found ${allResults.length} nodes with reactions.`\n );\n\n return {\n nodesCount: nodeIds.length,\n nodesWithReactions: allResults.length,\n nodes: allResults\n };\n } catch (error) {\n throw new Error(`Failed to get reactions: ${error.message}`);\n }\n}\n\nasync function readMyDesign() {\n try {\n // Load all selected nodes in parallel\n const nodes = await Promise.all(\n figma.currentPage.selection.map((node) => figma.getNodeByIdAsync(node.id))\n );\n\n // Filter out any null values (nodes that weren't found)\n const validNodes = nodes.filter((node) => node !== null);\n\n // Export all valid nodes in parallel\n const responses = await Promise.all(\n validNodes.map(async (node) => {\n const response = await node.exportAsync({\n format: \"JSON_REST_V1\",\n });\n return {\n nodeId: node.id,\n document: filterFigmaNode(response.document),\n };\n })\n );\n\n return responses;\n } catch (error) {\n throw new Error(`Error getting nodes info: ${error.message}`);\n }\n}\n\nasync function createRectangle(params) {\n const {\n x = 0,\n y = 0,\n width = 100,\n height = 100,\n name = \"Rectangle\",\n parentId,\n } = params || {};\n\n const rect = figma.createRectangle();\n rect.x = x;\n rect.y = y;\n rect.resize(width, height);\n rect.name = name;\n\n // If parentId is provided, append to that node, otherwise append to current page\n if (parentId) {\n const parentNode = await figma.getNodeByIdAsync(parentId);\n if (!parentNode) {\n throw new Error(`Parent node not found with ID: ${parentId}`);\n }\n if (!(\"appendChild\" in parentNode)) {\n throw new Error(`Parent node does not support children: ${parentId}`);\n }\n parentNode.appendChild(rect);\n } else {\n figma.currentPage.appendChild(rect);\n }\n\n return {\n id: rect.id,\n name: rect.name,\n x: rect.x,\n y: rect.y,\n width: rect.width,\n height: rect.height,\n parentId: rect.parent ? rect.parent.id : undefined,\n };\n}\n\nasync function createFrame(params) {\n const {\n x = 0,\n y = 0,\n width = 100,\n height = 100,\n name = \"Frame\",\n parentId,\n fillColor,\n strokeColor,\n strokeWeight,\n layoutMode = \"NONE\",\n layoutWrap = \"NO_WRAP\",\n paddingTop = 10,\n paddingRight = 10,\n paddingBottom = 10,\n paddingLeft = 10,\n primaryAxisAlignItems = \"MIN\",\n counterAxisAlignItems = \"MIN\",\n layoutSizingHorizontal = \"FIXED\",\n layoutSizingVertical = \"FIXED\",\n itemSpacing = 0,\n } = params || {};\n\n const frame = figma.createFrame();\n frame.x = x;\n frame.y = y;\n frame.resize(width, height);\n frame.name = name;\n\n // Set layout mode if provided\n if (layoutMode !== \"NONE\") {\n frame.layoutMode = layoutMode;\n frame.layoutWrap = layoutWrap;\n\n // Set padding values only when layoutMode is not NONE\n frame.paddingTop = paddingTop;\n frame.paddingRight = paddingRight;\n frame.paddingBottom = paddingBottom;\n frame.paddingLeft = paddingLeft;\n\n // Set axis alignment only when layoutMode is not NONE\n frame.primaryAxisAlignItems = primaryAxisAlignItems;\n frame.counterAxisAlignItems = counterAxisAlignItems;\n\n // Set layout sizing only when layoutMode is not NONE\n frame.layoutSizingHorizontal = layoutSizingHorizontal;\n frame.layoutSizingVertical = layoutSizingVertical;\n\n // Set item spacing only when layoutMode is not NONE\n frame.itemSpacing = itemSpacing;\n }\n\n // Set fill color if provided\n if (fillColor) {\n const paintStyle = {\n type: \"SOLID\",\n color: {\n r: parseFloat(fillColor.r) || 0,\n g: parseFloat(fillColor.g) || 0,\n b: parseFloat(fillColor.b) || 0,\n },\n opacity: parseFloat(fillColor.a) || 1,\n };\n frame.fills = [paintStyle];\n }\n\n // Set stroke color and weight if provided\n if (strokeColor) {\n const strokeStyle = {\n type: \"SOLID\",\n color: {\n r: parseFloat(strokeColor.r) || 0,\n g: parseFloat(strokeColor.g) || 0,\n b: parseFloat(strokeColor.b) || 0,\n },\n opacity: parseFloat(strokeColor.a) || 1,\n };\n frame.strokes = [strokeStyle];\n }\n\n // Set stroke weight if provided\n if (strokeWeight !== undefined) {\n frame.strokeWeight = strokeWeight;\n }\n\n // If parentId is provided, append to that node, otherwise append to current page\n if (parentId) {\n const parentNode = await figma.getNodeByIdAsync(parentId);\n if (!parentNode) {\n throw new Error(`Parent node not found with ID: ${parentId}`);\n }\n if (!(\"appendChild\" in parentNode)) {\n throw new Error(`Parent node does not support children: ${parentId}`);\n }\n parentNode.appendChild(frame);\n } else {\n figma.currentPage.appendChild(frame);\n }\n\n return {\n id: frame.id,\n name: frame.name,\n x: frame.x,\n y: frame.y,\n width: frame.width,\n height: frame.height,\n fills: frame.fills,\n strokes: frame.strokes,\n strokeWeight: frame.strokeWeight,\n layoutMode: frame.layoutMode,\n layoutWrap: frame.layoutWrap,\n parentId: frame.parent ? frame.parent.id : undefined,\n };\n}\n\nasync function createText(params) {\n const {\n x = 0,\n y = 0,\n text = \"Text\",\n fontSize = 14,\n fontWeight = 400,\n fontColor = { r: 0, g: 0, b: 0, a: 1 }, // Default to black\n name = \"\",\n parentId,\n } = params || {};\n\n // Map common font weights to Figma font styles\n const getFontStyle = (weight) => {\n switch (weight) {\n case 100:\n return \"Thin\";\n case 200:\n return \"Extra Light\";\n case 300:\n return \"Light\";\n case 400:\n return \"Regular\";\n case 500:\n return \"Medium\";\n case 600:\n return \"Semi Bold\";\n case 700:\n return \"Bold\";\n case 800:\n return \"Extra Bold\";\n case 900:\n return \"Black\";\n default:\n return \"Regular\";\n }\n };\n\n const textNode = figma.createText();\n textNode.x = x;\n textNode.y = y;\n textNode.name = name || text;\n try {\n await figma.loadFontAsync({\n family: \"Inter\",\n style: getFontStyle(fontWeight),\n });\n textNode.fontName = { family: \"Inter\", style: getFontStyle(fontWeight) };\n textNode.fontSize = parseInt(fontSize);\n } catch (error) {\n console.error(\"Error setting font size\", error);\n }\n setCharacters(textNode, text);\n\n // Set text color\n const paintStyle = {\n type: \"SOLID\",\n color: {\n r: parseFloat(fontColor.r) || 0,\n g: parseFloat(fontColor.g) || 0,\n b: parseFloat(fontColor.b) || 0,\n },\n opacity: parseFloat(fontColor.a) || 1,\n };\n textNode.fills = [paintStyle];\n\n // If parentId is provided, append to that node, otherwise append to current page\n if (parentId) {\n const parentNode = await figma.getNodeByIdAsync(parentId);\n if (!parentNode) {\n throw new Error(`Parent node not found with ID: ${parentId}`);\n }\n if (!(\"appendChild\" in parentNode)) {\n throw new Error(`Parent node does not support children: ${parentId}`);\n }\n parentNode.appendChild(textNode);\n } else {\n figma.currentPage.appendChild(textNode);\n }\n\n return {\n id: textNode.id,\n name: textNode.name,\n x: textNode.x,\n y: textNode.y,\n width: textNode.width,\n height: textNode.height,\n characters: textNode.characters,\n fontSize: textNode.fontSize,\n fontWeight: fontWeight,\n fontColor: fontColor,\n fontName: textNode.fontName,\n fills: textNode.fills,\n parentId: textNode.parent ? textNode.parent.id : undefined,\n };\n}\n\nasync function setFillColor(params) {\n console.log(\"setFillColor\", params);\n const {\n nodeId,\n color: { r, g, b, a },\n } = params || {};\n\n if (!nodeId) {\n throw new Error(\"Missing nodeId parameter\");\n }\n\n const node = await figma.getNodeByIdAsync(nodeId);\n if (!node) {\n throw new Error(`Node not found with ID: ${nodeId}`);\n }\n\n if (!(\"fills\" in node)) {\n throw new Error(`Node does not support fills: ${nodeId}`);\n }\n\n // Create RGBA color\n const rgbColor = {\n r: parseFloat(r) || 0,\n g: parseFloat(g) || 0,\n b: parseFloat(b) || 0,\n a: parseFloat(a) || 1,\n };\n\n // Set fill\n const paintStyle = {\n type: \"SOLID\",\n color: {\n r: parseFloat(rgbColor.r),\n g: parseFloat(rgbColor.g),\n b: parseFloat(rgbColor.b),\n },\n opacity: parseFloat(rgbColor.a),\n };\n\n console.log(\"paintStyle\", paintStyle);\n\n node.fills = [paintStyle];\n\n return {\n id: node.id,\n name: node.name,\n fills: [paintStyle],\n };\n}\n\nasync function setStrokeColor(params) {\n const {\n nodeId,\n color: { r, g, b, a },\n weight = 1,\n } = params || {};\n\n if (!nodeId) {\n throw new Error(\"Missing nodeId parameter\");\n }\n\n const node = await figma.getNodeByIdAsync(nodeId);\n if (!node) {\n throw new Error(`Node not found with ID: ${nodeId}`);\n }\n\n if (!(\"strokes\" in node)) {\n throw new Error(`Node does not support strokes: ${nodeId}`);\n }\n\n // Create RGBA color\n const rgbColor = {\n r: r !== undefined ? r : 0,\n g: g !== undefined ? g : 0,\n b: b !== undefined ? b : 0,\n a: a !== undefined ? a : 1,\n };\n\n // Set stroke\n const paintStyle = {\n type: \"SOLID\",\n color: {\n r: rgbColor.r,\n g: rgbColor.g,\n b: rgbColor.b,\n },\n opacity: rgbColor.a,\n };\n\n node.strokes = [paintStyle];\n\n // Set stroke weight if available\n if (\"strokeWeight\" in node) {\n node.strokeWeight = weight;\n }\n\n return {\n id: node.id,\n name: node.name,\n strokes: node.strokes,\n strokeWeight: \"strokeWeight\" in node ? node.strokeWeight : undefined,\n };\n}\n\nasync function moveNode(params) {\n const { nodeId, x, y } = params || {};\n\n if (!nodeId) {\n throw new Error(\"Missing nodeId parameter\");\n }\n\n if (x === undefined || y === undefined) {\n throw new Error(\"Missing x or y parameters\");\n }\n\n const node = await figma.getNodeByIdAsync(nodeId);\n if (!node) {\n throw new Error(`Node not found with ID: ${nodeId}`);\n }\n\n if (!(\"x\" in node) || !(\"y\" in node)) {\n throw new Error(`Node does not support position: ${nodeId}`);\n }\n\n node.x = x;\n node.y = y;\n\n return {\n id: node.id,\n name: node.name,\n x: node.x,\n y: node.y,\n };\n}\n\nasync function resizeNode(params) {\n const { nodeId, width, height } = params || {};\n\n if (!nodeId) {\n throw new Error(\"Missing nodeId parameter\");\n }\n\n if (width === undefined || height === undefined) {\n throw new Error(\"Missing width or height parameters\");\n }\n\n const node = await figma.getNodeByIdAsync(nodeId);\n if (!node) {\n throw new Error(`Node not found with ID: ${nodeId}`);\n }\n\n if (!(\"resize\" in node)) {\n throw new Error(`Node does not support resizing: ${nodeId}`);\n }\n\n node.resize(width, height);\n\n return {\n id: node.id,\n name: node.name,\n width: node.width,\n height: node.height,\n };\n}\n\nasync function deleteNode(params) {\n const { nodeId } = params || {};\n\n if (!nodeId) {\n throw new Error(\"Missing nodeId parameter\");\n }\n\n const node = await figma.getNodeByIdAsync(nodeId);\n if (!node) {\n throw new Error(`Node not found with ID: ${nodeId}`);\n }\n\n // Save node info before deleting\n const nodeInfo = {\n id: node.id,\n name: node.name,\n type: node.type,\n };\n\n node.remove();\n\n return nodeInfo;\n}\n\nasync function getStyles() {\n const styles = {\n colors: await figma.getLocalPaintStylesAsync(),\n texts: await figma.getLocalTextStylesAsync(),\n effects: await figma.getLocalEffectStylesAsync(),\n grids: await figma.getLocalGridStylesAsync(),\n };\n\n return {\n colors: styles.colors.map((style) => ({\n id: style.id,\n name: style.name,\n key: style.key,\n paint: style.paints[0],\n })),\n texts: styles.texts.map((style) => ({\n id: style.id,\n name: style.name,\n key: style.key,\n fontSize: style.fontSize,\n fontName: style.fontName,\n })),\n effects: styles.effects.map((style) => ({\n id: style.id,\n name: style.name,\n key: style.key,\n })),\n grids: styles.grids.map((style) => ({\n id: style.id,\n name: style.name,\n key: style.key,\n })),\n };\n}\n\nasync function getLocalComponents() {\n await figma.loadAllPagesAsync();\n\n const components = figma.root.findAllWithCriteria({\n types: [\"COMPONENT\"],\n });\n\n return {\n count: components.length,\n components: components.map((component) => ({\n id: component.id,\n name: component.name,\n key: \"key\" in component ? component.key : null,\n })),\n };\n}\n\n// async function getTeamComponents() {\n// try {\n// const teamComponents =\n// await figma.teamLibrary.getAvailableComponentsAsync();\n\n// return {\n// count: teamComponents.length,\n// components: teamComponents.map((component) => ({\n// key: component.key,\n// name: component.name,\n// description: component.description,\n// libraryName: component.libraryName,\n// })),\n// };\n// } catch (error) {\n// throw new Error(`Error getting team components: ${error.message}`);\n// }\n// }\n\nasync function createComponentInstance(params) {\n const { componentKey, x = 0, y = 0 } = params || {};\n\n if (!componentKey) {\n throw new Error(\"Missing componentKey parameter\");\n }\n\n try {\n const component = await figma.importComponentByKeyAsync(componentKey);\n const instance = component.createInstance();\n\n instance.x = x;\n instance.y = y;\n\n figma.currentPage.appendChild(instance);\n\n return {\n id: instance.id,\n name: instance.name,\n x: instance.x,\n y: instance.y,\n width: instance.width,\n height: instance.height,\n componentId: instance.componentId,\n };\n } catch (error) {\n throw new Error(`Error creating component instance: ${error.message}`);\n }\n}\n\nasync function exportNodeAsImage(params) {\n const { nodeId, scale = 1 } = params || {};\n\n const format = \"PNG\";\n\n if (!nodeId) {\n throw new Error(\"Missing nodeId parameter\");\n }\n\n const node = await figma.getNodeByIdAsync(nodeId);\n if (!node) {\n throw new Error(`Node not found with ID: ${nodeId}`);\n }\n\n if (!(\"exportAsync\" in node)) {\n throw new Error(`Node does not support exporting: ${nodeId}`);\n }\n\n try {\n const settings = {\n format: format,\n constraint: { type: \"SCALE\", value: scale },\n };\n\n const bytes = await node.exportAsync(settings);\n\n let mimeType;\n switch (format) {\n case \"PNG\":\n mimeType = \"image/png\";\n break;\n case \"JPG\":\n mimeType = \"image/jpeg\";\n break;\n case \"SVG\":\n mimeType = \"image/svg+xml\";\n break;\n case \"PDF\":\n mimeType = \"application/pdf\";\n break;\n default:\n mimeType = \"application/octet-stream\";\n }\n\n // Proper way to convert Uint8Array to base64\n const base64 = customBase64Encode(bytes);\n // const imageData = `data:${mimeType};base64,${base64}`;\n\n return {\n nodeId,\n format,\n scale,\n mimeType,\n imageData: base64,\n };\n } catch (error) {\n throw new Error(`Error exporting node as image: ${error.message}`);\n }\n}\nfunction customBase64Encode(bytes) {\n const chars =\n \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n let base64 = \"\";\n\n const byteLength = bytes.byteLength;\n const byteRemainder = byteLength % 3;\n const mainLength = byteLength - byteRemainder;\n\n let a, b, c, d;\n let chunk;\n\n // Main loop deals with bytes in chunks of 3\n for (let i = 0; i < mainLength; i = i + 3) {\n // Combine the three bytes into a single integer\n chunk = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2];\n\n // Use bitmasks to extract 6-bit segments from the triplet\n a = (chunk & 16515072) >> 18; // 16515072 = (2^6 - 1) << 18\n b = (chunk & 258048) >> 12; // 258048 = (2^6 - 1) << 12\n c = (chunk & 4032) >> 6; // 4032 = (2^6 - 1) << 6\n d = chunk & 63; // 63 = 2^6 - 1\n\n // Convert the raw binary segments to the appropriate ASCII encoding\n base64 += chars[a] + chars[b] + chars[c] + chars[d];\n }\n\n // Deal with the remaining bytes and padding\n if (byteRemainder === 1) {\n chunk = bytes[mainLength];\n\n a = (chunk & 252) >> 2; // 252 = (2^6 - 1) << 2\n\n // Set the 4 least significant bits to zero\n b = (chunk & 3) << 4; // 3 = 2^2 - 1\n\n base64 += chars[a] + chars[b] + \"==\";\n } else if (byteRemainder === 2) {\n chunk = (bytes[mainLength] << 8) | bytes[mainLength + 1];\n\n a = (chunk & 64512) >> 10; // 64512 = (2^6 - 1) << 10\n b = (chunk & 1008) >> 4; // 1008 = (2^6 - 1) << 4\n\n // Set the 2 least significant bits to zero\n c = (chunk & 15) << 2; // 15 = 2^4 - 1\n\n base64 += chars[a] + chars[b] + chars[c] + \"=\";\n }\n\n return base64;\n}\n\nasync function setCornerRadius(params) {\n const { nodeId, radius, corners } = params || {};\n\n if (!nodeId) {\n throw new Error(\"Missing nodeId parameter\");\n }\n\n if (radius === undefined) {\n throw new Error(\"Missing radius parameter\");\n }\n\n const node = await figma.getNodeByIdAsync(nodeId);\n if (!node) {\n throw new Error(`Node not found with ID: ${nodeId}`);\n }\n\n // Check if node supports corner radius\n if (!(\"cornerRadius\" in node)) {\n throw new Error(`Node does not support corner radius: ${nodeId}`);\n }\n\n // If corners array is provided, set individual corner radii\n if (corners && Array.isArray(corners) && corners.length === 4) {\n if (\"topLeftRadius\" in node) {\n // Node supports individual corner radii\n if (corners[0]) node.topLeftRadius = radius;\n if (corners[1]) node.topRightRadius = radius;\n if (corners[2]) node.bottomRightRadius = radius;\n if (corners[3]) node.bottomLeftRadius = radius;\n } else {\n // Node only supports uniform corner radius\n node.cornerRadius = radius;\n }\n } else {\n // Set uniform corner radius\n node.cornerRadius = radius;\n }\n\n return {\n id: node.id,\n name: node.name,\n cornerRadius: \"cornerRadius\" in node ? node.cornerRadius : undefined,\n topLeftRadius: \"topLeftRadius\" in node ? node.topLeftRadius : undefined,\n topRightRadius: \"topRightRadius\" in node ? node.topRightRadius : undefined,\n bottomRightRadius:\n \"bottomRightRadius\" in node ? node.bottomRightRadius : undefined,\n bottomLeftRadius:\n \"bottomLeftRadius\" in node ? node.bottomLeftRadius : undefined,\n };\n}\n\nasync function setTextContent(params) {\n const { nodeId, text } = params || {};\n\n if (!nodeId) {\n throw new Error(\"Missing nodeId parameter\");\n }\n\n if (text === undefined) {\n throw new Error(\"Missing text parameter\");\n }\n\n const node = await figma.getNodeByIdAsync(nodeId);\n if (!node) {\n throw new Error(`Node not found with ID: ${nodeId}`);\n }\n\n if (node.type !== \"TEXT\") {\n throw new Error(`Node is not a text node: ${nodeId}`);\n }\n\n try {\n await figma.loadFontAsync(node.fontName);\n\n await setCharacters(node, text);\n\n return {\n id: node.id,\n name: node.name,\n characters: node.characters,\n fontName: node.fontName,\n };\n } catch (error) {\n throw new Error(`Error setting text content: ${error.message}`);\n }\n}\n\n// Initialize settings on load\n(async function initializePlugin() {\n try {\n const savedSettings = await figma.clientStorage.getAsync(\"settings\");\n if (savedSettings) {\n if (savedSettings.serverPort) {\n state.serverPort = savedSettings.serverPort;\n }\n }\n\n // Send initial settings to UI\n figma.ui.postMessage({\n type: \"init-settings\",\n settings: {\n serverPort: state.serverPort,\n },\n });\n } catch (error) {\n console.error(\"Error loading settings:\", error);\n }\n})();\n\nfunction uniqBy(arr, predicate) {\n const cb = typeof predicate === \"function\" ? predicate : (o) => o[predicate];\n return [\n ...arr\n .reduce((map, item) => {\n const key = item === null || item === undefined ? item : cb(item);\n\n map.has(key) || map.set(key, item);\n\n return map;\n }, new Map())\n .values(),\n ];\n}\nconst setCharacters = async (node, characters, options) => {\n const fallbackFont = (options && options.fallbackFont) || {\n family: \"Inter\",\n style: \"Regular\",\n };\n try {\n if (node.fontName === figma.mixed) {\n if (options && options.smartStrategy === \"prevail\") {\n const fontHashTree = {};\n for (let i = 1; i < node.characters.length; i++) {\n const charFont = node.getRangeFontName(i - 1, i);\n const key = `${charFont.family}::${charFont.style}`;\n fontHashTree[key] = fontHashTree[key] ? fontHashTree[key] + 1 : 1;\n }\n const prevailedTreeItem = Object.entries(fontHashTree).sort(\n (a, b) => b[1] - a[1]\n )[0];\n const [family, style] = prevailedTreeItem[0].split(\"::\");\n const prevailedFont = {\n family,\n style,\n };\n await figma.loadFontAsync(prevailedFont);\n node.fontName = prevailedFont;\n } else if (options && options.smartStrategy === \"strict\") {\n return setCharactersWithStrictMatchFont(node, characters, fallbackFont);\n } else if (options && options.smartStrategy === \"experimental\") {\n return setCharactersWithSmartMatchFont(node, characters, fallbackFont);\n } else {\n const firstCharFont = node.getRangeFontName(0, 1);\n await figma.loadFontAsync(firstCharFont);\n node.fontName = firstCharFont;\n }\n } else {\n await figma.loadFontAsync({\n family: node.fontName.family,\n style: node.fontName.style,\n });\n }\n } catch (err) {\n console.warn(\n `Failed to load \"${node.fontName[\"family\"]} ${node.fontName[\"style\"]}\" font and replaced with fallback \"${fallbackFont.family} ${fallbackFont.style}\"`,\n err\n );\n await figma.loadFontAsync(fallbackFont);\n node.fontName = fallbackFont;\n }\n try {\n node.characters = characters;\n return true;\n } catch (err) {\n console.warn(`Failed to set characters. Skipped.`, err);\n return false;\n }\n};\n\nconst setCharactersWithStrictMatchFont = async (\n node,\n characters,\n fallbackFont\n) => {\n const fontHashTree = {};\n for (let i = 1; i < node.characters.length; i++) {\n const startIdx = i - 1;\n const startCharFont = node.getRangeFontName(startIdx, i);\n const startCharFontVal = `${startCharFont.family}::${startCharFont.style}`;\n while (i < node.characters.length) {\n i++;\n const charFont = node.getRangeFontName(i - 1, i);\n if (startCharFontVal !== `${charFont.family}::${charFont.style}`) {\n break;\n }\n }\n fontHashTree[`${startIdx}_${i}`] = startCharFontVal;\n }\n await figma.loadFontAsync(fallbackFont);\n node.fontName = fallbackFont;\n node.characters = characters;\n console.log(fontHashTree);\n await Promise.all(\n Object.keys(fontHashTree).map(async (range) => {\n console.log(range, fontHashTree[range]);\n const [start, end] = range.split(\"_\");\n const [family, style] = fontHashTree[range].split(\"::\");\n const matchedFont = {\n family,\n style,\n };\n await figma.loadFontAsync(matchedFont);\n return node.setRangeFontName(Number(start), Number(end), matchedFont);\n })\n );\n return true;\n};\n\nconst getDelimiterPos = (str, delimiter, startIdx = 0, endIdx = str.length) => {\n const indices = [];\n let temp = startIdx;\n for (let i = startIdx; i < endIdx; i++) {\n if (\n str[i] === delimiter &&\n i + startIdx !== endIdx &&\n temp !== i + startIdx\n ) {\n indices.push([temp, i + startIdx]);\n temp = i + startIdx + 1;\n }\n }\n temp !== endIdx && indices.push([temp, endIdx]);\n return indices.filter(Boolean);\n};\n\nconst buildLinearOrder = (node) => {\n const fontTree = [];\n const newLinesPos = getDelimiterPos(node.characters, \"\\n\");\n newLinesPos.forEach(([newLinesRangeStart, newLinesRangeEnd], n) => {\n const newLinesRangeFont = node.getRangeFontName(\n newLinesRangeStart,\n newLinesRangeEnd\n );\n if (newLinesRangeFont === figma.mixed) {\n const spacesPos = getDelimiterPos(\n node.characters,\n \" \",\n newLinesRangeStart,\n newLinesRangeEnd\n );\n spacesPos.forEach(([spacesRangeStart, spacesRangeEnd], s) => {\n const spacesRangeFont = node.getRangeFontName(\n spacesRangeStart,\n spacesRangeEnd\n );\n if (spacesRangeFont === figma.mixed) {\n const spacesRangeFont = node.getRangeFontName(\n spacesRangeStart,\n spacesRangeStart[0]\n );\n fontTree.push({\n start: spacesRangeStart,\n delimiter: \" \",\n family: spacesRangeFont.family,\n style: spacesRangeFont.style,\n });\n } else {\n fontTree.push({\n start: spacesRangeStart,\n delimiter: \" \",\n family: spacesRangeFont.family,\n style: spacesRangeFont.style,\n });\n }\n });\n } else {\n fontTree.push({\n start: newLinesRangeStart,\n delimiter: \"\\n\",\n family: newLinesRangeFont.family,\n style: newLinesRangeFont.style,\n });\n }\n });\n return fontTree\n .sort((a, b) => +a.start - +b.start)\n .map(({ family, style, delimiter }) => ({ family, style, delimiter }));\n};\n\nconst setCharactersWithSmartMatchFont = async (\n node,\n characters,\n fallbackFont\n) => {\n const rangeTree = buildLinearOrder(node);\n const fontsToLoad = uniqBy(\n rangeTree,\n ({ family, style }) => `${family}::${style}`\n ).map(({ family, style }) => ({\n family,\n style,\n }));\n\n await Promise.all([...fontsToLoad, fallbackFont].map(figma.loadFontAsync));\n\n node.fontName = fallbackFont;\n node.characters = characters;\n\n let prevPos = 0;\n rangeTree.forEach(({ family, style, delimiter }) => {\n if (prevPos < node.characters.length) {\n const delimeterPos = node.characters.indexOf(delimiter, prevPos);\n const endPos =\n delimeterPos > prevPos ? delimeterPos : node.characters.length;\n const matchedFont = {\n family,\n style,\n };\n node.setRangeFontName(prevPos, endPos, matchedFont);\n prevPos = endPos + 1;\n }\n });\n return true;\n};\n\n// Add the cloneNode function implementation\nasync function cloneNode(params) {\n const { nodeId, x, y } = params || {};\n\n if (!nodeId) {\n throw new Error(\"Missing nodeId parameter\");\n }\n\n const node = await figma.getNodeByIdAsync(nodeId);\n if (!node) {\n throw new Error(`Node not found with ID: ${nodeId}`);\n }\n\n // Clone the node\n const clone = node.clone();\n\n // If x and y are provided, move the clone to that position\n if (x !== undefined && y !== undefined) {\n if (!(\"x\" in clone) || !(\"y\" in clone)) {\n throw new Error(`Cloned node does not support position: ${nodeId}`);\n }\n clone.x = x;\n clone.y = y;\n }\n\n // Add the clone to the same parent as the original node\n if (node.parent) {\n node.parent.appendChild(clone);\n } else {\n figma.currentPage.appendChild(clone);\n }\n\n return {\n id: clone.id,\n name: clone.name,\n x: \"x\" in clone ? clone.x : undefined,\n y: \"y\" in clone ? clone.y : undefined,\n width: \"width\" in clone ? clone.width : undefined,\n height: \"height\" in clone ? clone.height : undefined,\n };\n}\n\nasync function scanTextNodes(params) {\n console.log(`Starting to scan text nodes from node ID: ${params.nodeId}`);\n const {\n nodeId,\n useChunking = true,\n chunkSize = 10,\n commandId = generateCommandId(),\n } = params || {};\n\n const node = await figma.getNodeByIdAsync(nodeId);\n\n if (!node) {\n console.error(`Node with ID ${nodeId} not found`);\n // Send error progress update\n sendProgressUpdate(\n commandId,\n \"scan_text_nodes\",\n \"error\",\n 0,\n 0,\n 0,\n `Node with ID ${nodeId} not found`,\n { error: `Node not found: ${nodeId}` }\n );\n throw new Error(`Node with ID ${nodeId} not found`);\n }\n\n // If chunking is not enabled, use the original implementation\n if (!useChunking) {\n const textNodes = [];\n try {\n // Send started progress update\n sendProgressUpdate(\n commandId,\n \"scan_text_nodes\",\n \"started\",\n 0,\n 1, // Not known yet how many nodes there are\n 0,\n `Starting scan of node \"${node.name || nodeId}\" without chunking`,\n null\n );\n\n await findTextNodes(node, [], 0, textNodes);\n\n // Send completed progress update\n sendProgressUpdate(\n commandId,\n \"scan_text_nodes\",\n \"completed\",\n 100,\n textNodes.length,\n textNodes.length,\n `Scan complete. Found ${textNodes.length} text nodes.`,\n { textNodes }\n );\n\n return {\n success: true,\n message: `Scanned ${textNodes.length} text nodes.`,\n count: textNodes.length,\n textNodes: textNodes,\n commandId,\n };\n } catch (error) {\n console.error(\"Error scanning text nodes:\", error);\n\n // Send error progress update\n sendProgressUpdate(\n commandId,\n \"scan_text_nodes\",\n \"error\",\n 0,\n 0,\n 0,\n `Error scanning text nodes: ${error.message}`,\n { error: error.message }\n );\n\n throw new Error(`Error scanning text nodes: ${error.message}`);\n }\n }\n\n // Chunked implementation\n console.log(`Using chunked scanning with chunk size: ${chunkSize}`);\n\n // First, collect all nodes to process (without processing them yet)\n const nodesToProcess = [];\n\n // Send started progress update\n sendProgressUpdate(\n commandId,\n \"scan_text_nodes\",\n \"started\",\n 0,\n 0, // Not known yet how many nodes there are\n 0,\n `Starting chunked scan of node \"${node.name || nodeId}\"`,\n { chunkSize }\n );\n\n await collectNodesToProcess(node, [], 0, nodesToProcess);\n\n const totalNodes = nodesToProcess.length;\n console.log(`Found ${totalNodes} total nodes to process`);\n\n // Calculate number of chunks needed\n const totalChunks = Math.ceil(totalNodes / chunkSize);\n console.log(`Will process in ${totalChunks} chunks`);\n\n // Send update after node collection\n sendProgressUpdate(\n commandId,\n \"scan_text_nodes\",\n \"in_progress\",\n 5, // 5% progress for collection phase\n totalNodes,\n 0,\n `Found ${totalNodes} nodes to scan. Will process in ${totalChunks} chunks.`,\n {\n totalNodes,\n totalChunks,\n chunkSize,\n }\n );\n\n // Process nodes in chunks\n const allTextNodes = [];\n let processedNodes = 0;\n let chunksProcessed = 0;\n\n for (let i = 0; i < totalNodes; i += chunkSize) {\n const chunkEnd = Math.min(i + chunkSize, totalNodes);\n console.log(\n `Processing chunk ${chunksProcessed + 1}/${totalChunks} (nodes ${i} to ${chunkEnd - 1\n })`\n );\n\n // Send update before processing chunk\n sendProgressUpdate(\n commandId,\n \"scan_text_nodes\",\n \"in_progress\",\n Math.round(5 + (chunksProcessed / totalChunks) * 90), // 5-95% for processing\n totalNodes,\n processedNodes,\n `Processing chunk ${chunksProcessed + 1}/${totalChunks}`,\n {\n currentChunk: chunksProcessed + 1,\n totalChunks,\n textNodesFound: allTextNodes.length,\n }\n );\n\n const chunkNodes = nodesToProcess.slice(i, chunkEnd);\n const chunkTextNodes = [];\n\n // Process each node in this chunk\n for (const nodeInfo of chunkNodes) {\n if (nodeInfo.node.type === \"TEXT\") {\n try {\n const textNodeInfo = await processTextNode(\n nodeInfo.node,\n nodeInfo.parentPath,\n nodeInfo.depth\n );\n if (textNodeInfo) {\n chunkTextNodes.push(textNodeInfo);\n }\n } catch (error) {\n console.error(`Error processing text node: ${error.message}`);\n // Continue with other nodes\n }\n }\n\n // Brief delay to allow UI updates and prevent freezing\n await delay(5);\n }\n\n // Add results from this chunk\n allTextNodes.push(...chunkTextNodes);\n processedNodes += chunkNodes.length;\n chunksProcessed++;\n\n // Send update after processing chunk\n sendProgressUpdate(\n commandId,\n \"scan_text_nodes\",\n \"in_progress\",\n Math.round(5 + (chunksProcessed / totalChunks) * 90), // 5-95% for processing\n totalNodes,\n processedNodes,\n `Processed chunk ${chunksProcessed}/${totalChunks}. Found ${allTextNodes.length} text nodes so far.`,\n {\n currentChunk: chunksProcessed,\n totalChunks,\n processedNodes,\n textNodesFound: allTextNodes.length,\n chunkResult: chunkTextNodes,\n }\n );\n\n // Small delay between chunks to prevent UI freezing\n if (i + chunkSize < totalNodes) {\n await delay(50);\n }\n }\n\n // Send completed progress update\n sendProgressUpdate(\n commandId,\n \"scan_text_nodes\",\n \"completed\",\n 100,\n totalNodes,\n processedNodes,\n `Scan complete. Found ${allTextNodes.length} text nodes.`,\n {\n textNodes: allTextNodes,\n processedNodes,\n chunks: chunksProcessed,\n }\n );\n\n return {\n success: true,\n message: `Chunked scan complete. Found ${allTextNodes.length} text nodes.`,\n totalNodes: allTextNodes.length,\n processedNodes: processedNodes,\n chunks: chunksProcessed,\n textNodes: allTextNodes,\n commandId,\n };\n}\n\n// Helper function to collect all nodes that need to be processed\nasync function collectNodesToProcess(\n node,\n parentPath = [],\n depth = 0,\n nodesToProcess = []\n) {\n // Skip invisible nodes\n if (node.visible === false) return;\n\n // Get the path to this node\n const nodePath = [...parentPath, node.name || `Unnamed ${node.type}`];\n\n // Add this node to the processing list\n nodesToProcess.push({\n node: node,\n parentPath: nodePath,\n depth: depth,\n });\n\n // Recursively add children\n if (\"children\" in node) {\n for (const child of node.children) {\n await collectNodesToProcess(child, nodePath, depth + 1, nodesToProcess);\n }\n }\n}\n\n// Process a single text node\nasync function processTextNode(node, parentPath, depth) {\n if (node.type !== \"TEXT\") return null;\n\n try {\n // Safely extract font information\n let fontFamily = \"\";\n let fontStyle = \"\";\n\n if (node.fontName) {\n if (typeof node.fontName === \"object\") {\n if (\"family\" in node.fontName) fontFamily = node.fontName.family;\n if (\"style\" in node.fontName) fontStyle = node.fontName.style;\n }\n }\n\n // Create a safe representation of the text node\n const safeTextNode = {\n id: node.id,\n name: node.name || \"Text\",\n type: node.type,\n characters: node.characters,\n fontSize: typeof node.fontSize === \"number\" ? node.fontSize : 0,\n fontFamily: fontFamily,\n fontStyle: fontStyle,\n x: typeof node.x === \"number\" ? node.x : 0,\n y: typeof node.y === \"number\" ? node.y : 0,\n width: typeof node.width === \"number\" ? node.width : 0,\n height: typeof node.height === \"number\" ? node.height : 0,\n path: parentPath.join(\" > \"),\n depth: depth,\n };\n\n // Highlight the node briefly (optional visual feedback)\n try {\n const originalFills = JSON.parse(JSON.stringify(node.fills));\n node.fills = [\n {\n type: \"SOLID\",\n color: { r: 1, g: 0.5, b: 0 },\n opacity: 0.3,\n },\n ];\n\n // Brief delay for the highlight to be visible\n await delay(100);\n\n try {\n node.fills = originalFills;\n } catch (err) {\n console.error(\"Error resetting fills:\", err);\n }\n } catch (highlightErr) {\n console.error(\"Error highlighting text node:\", highlightErr);\n // Continue anyway, highlighting is just visual feedback\n }\n\n return safeTextNode;\n } catch (nodeErr) {\n console.error(\"Error processing text node:\", nodeErr);\n return null;\n }\n}\n\n// A delay function that returns a promise\nfunction delay(ms) {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n// Keep the original findTextNodes for backward compatibility\nasync function findTextNodes(node, parentPath = [], depth = 0, textNodes = []) {\n // Skip invisible nodes\n if (node.visible === false) return;\n\n // Get the path to this node including its name\n const nodePath = [...parentPath, node.name || `Unnamed ${node.type}`];\n\n if (node.type === \"TEXT\") {\n try {\n // Safely extract font information to avoid Symbol serialization issues\n let fontFamily = \"\";\n let fontStyle = \"\";\n\n if (node.fontName) {\n if (typeof node.fontName === \"object\") {\n if (\"family\" in node.fontName) fontFamily = node.fontName.family;\n if (\"style\" in node.fontName) fontStyle = node.fontName.style;\n }\n }\n\n // Create a safe representation of the text node with only serializable properties\n const safeTextNode = {\n id: node.id,\n name: node.name || \"Text\",\n type: node.type,\n characters: node.characters,\n fontSize: typeof node.fontSize === \"number\" ? node.fontSize : 0,\n fontFamily: fontFamily,\n fontStyle: fontStyle,\n x: typeof node.x === \"number\" ? node.x : 0,\n y: typeof node.y === \"number\" ? node.y : 0,\n width: typeof node.width === \"number\" ? node.width : 0,\n height: typeof node.height === \"number\" ? node.height : 0,\n path: nodePath.join(\" > \"),\n depth: depth,\n };\n\n // Only highlight the node if it's not being done via API\n try {\n // Safe way to create a temporary highlight without causing serialization issues\n const originalFills = JSON.parse(JSON.stringify(node.fills));\n node.fills = [\n {\n type: \"SOLID\",\n color: { r: 1, g: 0.5, b: 0 },\n opacity: 0.3,\n },\n ];\n\n // Promise-based delay instead of setTimeout\n await delay(500);\n\n try {\n node.fills = originalFills;\n } catch (err) {\n console.error(\"Error resetting fills:\", err);\n }\n } catch (highlightErr) {\n console.error(\"Error highlighting text node:\", highlightErr);\n // Continue anyway, highlighting is just visual feedback\n }\n\n textNodes.push(safeTextNode);\n } catch (nodeErr) {\n console.error(\"Error processing text node:\", nodeErr);\n // Skip this node but continue with others\n }\n }\n\n // Recursively process children of container nodes\n if (\"children\" in node) {\n for (const child of node.children) {\n await findTextNodes(child, nodePath, depth + 1, textNodes);\n }\n }\n}\n\n// Replace text in a specific node\n", "suffix_code": "\n\n// Function to generate simple UUIDs for command IDs\nfunction generateCommandId() {\n return (\n \"cmd_\" +\n Math.random().toString(36).substring(2, 15) +\n Math.random().toString(36).substring(2, 15)\n );\n}\n\nasync function getAnnotations(params) {\n try {\n const { nodeId, includeCategories = true } = params;\n\n // Get categories first if needed\n let categoriesMap = {};\n if (includeCategories) {\n const categories = await figma.annotations.getAnnotationCategoriesAsync();\n categoriesMap = categories.reduce((map, category) => {\n map[category.id] = {\n id: category.id,\n label: category.label,\n color: category.color,\n isPreset: category.isPreset,\n };\n return map;\n }, {});\n }\n\n if (nodeId) {\n // Get annotations for a specific node\n const node = await figma.getNodeByIdAsync(nodeId);\n if (!node) {\n throw new Error(`Node not found: ${nodeId}`);\n }\n\n if (!(\"annotations\" in node)) {\n throw new Error(`Node type ${node.type} does not support annotations`);\n }\n\n const result = {\n nodeId: node.id,\n name: node.name,\n annotations: node.annotations || [],\n };\n\n if (includeCategories) {\n result.categories = Object.values(categoriesMap);\n }\n\n return result;\n } else {\n // Get all annotations in the current page\n const annotations = [];\n const processNode = async (node) => {\n if (\n \"annotations\" in node &&\n node.annotations &&\n node.annotations.length > 0\n ) {\n annotations.push({\n nodeId: node.id,\n name: node.name,\n annotations: node.annotations,\n });\n }\n if (\"children\" in node) {\n for (const child of node.children) {\n await processNode(child);\n }\n }\n };\n\n // Start from current page\n await processNode(figma.currentPage);\n\n const result = {\n annotatedNodes: annotations,\n };\n\n if (includeCategories) {\n result.categories = Object.values(categoriesMap);\n }\n\n return result;\n }\n } catch (error) {\n console.error(\"Error in getAnnotations:\", error);\n throw error;\n }\n}\n\nasync function setAnnotation(params) {\n try {\n console.log(\"=== setAnnotation Debug Start ===\");\n console.log(\"Input params:\", JSON.stringify(params, null, 2));\n\n const { nodeId, annotationId, labelMarkdown, categoryId, properties } =\n params;\n\n // Validate required parameters\n if (!nodeId) {\n console.error(\"Validation failed: Missing nodeId\");\n return { success: false, error: \"Missing nodeId\" };\n }\n\n if (!labelMarkdown) {\n console.error(\"Validation failed: Missing labelMarkdown\");\n return { success: false, error: \"Missing labelMarkdown\" };\n }\n\n console.log(\"Attempting to get node:\", nodeId);\n // Get and validate node\n const node = await figma.getNodeByIdAsync(nodeId);\n console.log(\"Node lookup result:\", {\n id: nodeId,\n found: !!node,\n type: node ? node.type : undefined,\n name: node ? node.name : undefined,\n hasAnnotations: node ? \"annotations\" in node : false,\n });\n\n if (!node) {\n console.error(\"Node lookup failed:\", nodeId);\n return { success: false, error: `Node not found: ${nodeId}` };\n }\n\n // Validate node supports annotations\n if (!(\"annotations\" in node)) {\n console.error(\"Node annotation support check failed:\", {\n nodeType: node.type,\n nodeId: node.id,\n });\n return {\n success: false,\n error: `Node type ${node.type} does not support annotations`,\n };\n }\n\n // Create the annotation object\n const newAnnotation = {\n labelMarkdown,\n };\n\n // Validate and add categoryId if provided\n if (categoryId) {\n console.log(\"Adding categoryId to annotation:\", categoryId);\n newAnnotation.categoryId = categoryId;\n }\n\n // Validate and add properties if provided\n if (properties && Array.isArray(properties) && properties.length > 0) {\n console.log(\n \"Adding properties to annotation:\",\n JSON.stringify(properties, null, 2)\n );\n newAnnotation.properties = properties;\n }\n\n // Log current annotations before update\n console.log(\"Current node annotations:\", node.annotations);\n\n // Overwrite annotations\n console.log(\n \"Setting new annotation:\",\n JSON.stringify(newAnnotation, null, 2)\n );\n node.annotations = [newAnnotation];\n\n // Verify the update\n console.log(\"Updated node annotations:\", node.annotations);\n console.log(\"=== setAnnotation Debug End ===\");\n\n return {\n success: true,\n nodeId: node.id,\n name: node.name,\n annotations: node.annotations,\n };\n } catch (error) {\n console.error(\"=== setAnnotation Error ===\");\n console.error(\"Error details:\", {\n message: error.message,\n stack: error.stack,\n params: JSON.stringify(params, null, 2),\n });\n return { success: false, error: error.message };\n }\n}\n\n/**\n * Scan for nodes with specific types within a node\n * @param {Object} params - Parameters object\n * @param {string} params.nodeId - ID of the node to scan within\n * @param {Array} params.types - Array of node types to find (e.g. ['COMPONENT', 'FRAME'])\n * @returns {Object} - Object containing found nodes\n */\nasync function scanNodesByTypes(params) {\n console.log(`Starting to scan nodes by types from node ID: ${params.nodeId}`);\n const { nodeId, types = [] } = params || {};\n\n if (!types || types.length === 0) {\n throw new Error(\"No types specified to search for\");\n }\n\n const node = await figma.getNodeByIdAsync(nodeId);\n\n if (!node) {\n throw new Error(`Node with ID ${nodeId} not found`);\n }\n\n // Simple implementation without chunking\n const matchingNodes = [];\n\n // Send a single progress update to notify start\n const commandId = generateCommandId();\n sendProgressUpdate(\n commandId,\n \"scan_nodes_by_types\",\n \"started\",\n 0,\n 1,\n 0,\n `Starting scan of node \"${node.name || nodeId}\" for types: ${types.join(\n \", \"\n )}`,\n null\n );\n\n // Recursively find nodes with specified types\n await findNodesByTypes(node, types, matchingNodes);\n\n // Send completion update\n sendProgressUpdate(\n commandId,\n \"scan_nodes_by_types\",\n \"completed\",\n 100,\n matchingNodes.length,\n matchingNodes.length,\n `Scan complete. Found ${matchingNodes.length} matching nodes.`,\n { matchingNodes }\n );\n\n return {\n success: true,\n message: `Found ${matchingNodes.length} matching nodes.`,\n count: matchingNodes.length,\n matchingNodes: matchingNodes,\n searchedTypes: types,\n };\n}\n\n/**\n * Helper function to recursively find nodes with specific types\n * @param {SceneNode} node - The root node to start searching from\n * @param {Array} types - Array of node types to find\n * @param {Array} matchingNodes - Array to store found nodes\n */\nasync function findNodesByTypes(node, types, matchingNodes = []) {\n // Skip invisible nodes\n if (node.visible === false) return;\n\n // Check if this node is one of the specified types\n if (types.includes(node.type)) {\n // Create a minimal representation with just ID, type and bbox\n matchingNodes.push({\n id: node.id,\n name: node.name || `Unnamed ${node.type}`,\n type: node.type,\n // Basic bounding box info\n bbox: {\n x: typeof node.x === \"number\" ? node.x : 0,\n y: typeof node.y === \"number\" ? node.y : 0,\n width: typeof node.width === \"number\" ? node.width : 0,\n height: typeof node.height === \"number\" ? node.height : 0,\n },\n });\n }\n\n // Recursively process children of container nodes\n if (\"children\" in node) {\n for (const child of node.children) {\n await findNodesByTypes(child, types, matchingNodes);\n }\n }\n}\n\n// Set multiple annotations with async progress updates\nasync function setMultipleAnnotations(params) {\n console.log(\"=== setMultipleAnnotations Debug Start ===\");\n console.log(\"Input params:\", JSON.stringify(params, null, 2));\n\n const { nodeId, annotations } = params;\n\n if (!annotations || annotations.length === 0) {\n console.error(\"Validation failed: No annotations provided\");\n return { success: false, error: \"No annotations provided\" };\n }\n\n console.log(\n `Processing ${annotations.length} annotations for node ${nodeId}`\n );\n\n const results = [];\n let successCount = 0;\n let failureCount = 0;\n\n // Process annotations sequentially\n for (let i = 0; i < annotations.length; i++) {\n const annotation = annotations[i];\n console.log(\n `\\nProcessing annotation ${i + 1}/${annotations.length}:`,\n JSON.stringify(annotation, null, 2)\n );\n\n try {\n console.log(\"Calling setAnnotation with params:\", {\n nodeId: annotation.nodeId,\n labelMarkdown: annotation.labelMarkdown,\n categoryId: annotation.categoryId,\n properties: annotation.properties,\n });\n\n const result = await setAnnotation({\n nodeId: annotation.nodeId,\n labelMarkdown: annotation.labelMarkdown,\n categoryId: annotation.categoryId,\n properties: annotation.properties,\n });\n\n console.log(\"setAnnotation result:\", JSON.stringify(result, null, 2));\n\n if (result.success) {\n successCount++;\n results.push({ success: true, nodeId: annotation.nodeId });\n console.log(`✓ Annotation ${i + 1} applied successfully`);\n } else {\n failureCount++;\n results.push({\n success: false,\n nodeId: annotation.nodeId,\n error: result.error,\n });\n console.error(`✗ Annotation ${i + 1} failed:`, result.error);\n }\n } catch (error) {\n failureCount++;\n const errorResult = {\n success: false,\n nodeId: annotation.nodeId,\n error: error.message,\n };\n results.push(errorResult);\n console.error(`✗ Annotation ${i + 1} failed with error:`, error);\n console.error(\"Error details:\", {\n message: error.message,\n stack: error.stack,\n });\n }\n }\n\n const summary = {\n success: successCount > 0,\n annotationsApplied: successCount,\n annotationsFailed: failureCount,\n totalAnnotations: annotations.length,\n results: results,\n };\n\n console.log(\"\\n=== setMultipleAnnotations Summary ===\");\n console.log(JSON.stringify(summary, null, 2));\n console.log(\"=== setMultipleAnnotations Debug End ===\");\n\n return summary;\n}\n\nasync function deleteMultipleNodes(params) {\n const { nodeIds } = params || {};\n const commandId = generateCommandId();\n\n if (!nodeIds || !Array.isArray(nodeIds) || nodeIds.length === 0) {\n const errorMsg = \"Missing or invalid nodeIds parameter\";\n sendProgressUpdate(\n commandId,\n \"delete_multiple_nodes\",\n \"error\",\n 0,\n 0,\n 0,\n errorMsg,\n { error: errorMsg }\n );\n throw new Error(errorMsg);\n }\n\n console.log(`Starting deletion of ${nodeIds.length} nodes`);\n\n // Send started progress update\n sendProgressUpdate(\n commandId,\n \"delete_multiple_nodes\",\n \"started\",\n 0,\n nodeIds.length,\n 0,\n `Starting deletion of ${nodeIds.length} nodes`,\n { totalNodes: nodeIds.length }\n );\n\n const results = [];\n let successCount = 0;\n let failureCount = 0;\n\n // Process nodes in chunks of 5 to avoid overwhelming Figma\n const CHUNK_SIZE = 5;\n const chunks = [];\n\n for (let i = 0; i < nodeIds.length; i += CHUNK_SIZE) {\n chunks.push(nodeIds.slice(i, i + CHUNK_SIZE));\n }\n\n console.log(`Split ${nodeIds.length} deletions into ${chunks.length} chunks`);\n\n // Send chunking info update\n sendProgressUpdate(\n commandId,\n \"delete_multiple_nodes\",\n \"in_progress\",\n 5,\n nodeIds.length,\n 0,\n `Preparing to delete ${nodeIds.length} nodes using ${chunks.length} chunks`,\n {\n totalNodes: nodeIds.length,\n chunks: chunks.length,\n chunkSize: CHUNK_SIZE,\n }\n );\n\n // Process each chunk sequentially\n for (let chunkIndex = 0; chunkIndex < chunks.length; chunkIndex++) {\n const chunk = chunks[chunkIndex];\n console.log(\n `Processing chunk ${chunkIndex + 1}/${chunks.length} with ${chunk.length\n } nodes`\n );\n\n // Send chunk processing start update\n sendProgressUpdate(\n commandId,\n \"delete_multiple_nodes\",\n \"in_progress\",\n Math.round(5 + (chunkIndex / chunks.length) * 90),\n nodeIds.length,\n successCount + failureCount,\n `Processing deletion chunk ${chunkIndex + 1}/${chunks.length}`,\n {\n currentChunk: chunkIndex + 1,\n totalChunks: chunks.length,\n successCount,\n failureCount,\n }\n );\n\n // Process deletions within a chunk in parallel\n const chunkPromises = chunk.map(async (nodeId) => {\n try {\n const node = await figma.getNodeByIdAsync(nodeId);\n\n if (!node) {\n console.error(`Node not found: ${nodeId}`);\n return {\n success: false,\n nodeId: nodeId,\n error: `Node not found: ${nodeId}`,\n };\n }\n\n // Save node info before deleting\n const nodeInfo = {\n id: node.id,\n name: node.name,\n type: node.type,\n };\n\n // Delete the node\n node.remove();\n\n console.log(`Successfully deleted node: ${nodeId}`);\n return {\n success: true,\n nodeId: nodeId,\n nodeInfo: nodeInfo,\n };\n } catch (error) {\n console.error(`Error deleting node ${nodeId}: ${error.message}`);\n return {\n success: false,\n nodeId: nodeId,\n error: error.message,\n };\n }\n });\n\n // Wait for all deletions in this chunk to complete\n const chunkResults = await Promise.all(chunkPromises);\n\n // Process results for this chunk\n chunkResults.forEach((result) => {\n if (result.success) {\n successCount++;\n } else {\n failureCount++;\n }\n results.push(result);\n });\n\n // Send chunk processing complete update\n sendProgressUpdate(\n commandId,\n \"delete_multiple_nodes\",\n \"in_progress\",\n Math.round(5 + ((chunkIndex + 1) / chunks.length) * 90),\n nodeIds.length,\n successCount + failureCount,\n `Completed chunk ${chunkIndex + 1}/${chunks.length\n }. ${successCount} successful, ${failureCount} failed so far.`,\n {\n currentChunk: chunkIndex + 1,\n totalChunks: chunks.length,\n successCount,\n failureCount,\n chunkResults: chunkResults,\n }\n );\n\n // Add a small delay between chunks\n if (chunkIndex < chunks.length - 1) {\n console.log(\"Pausing between chunks...\");\n await delay(1000);\n }\n }\n\n console.log(\n `Deletion complete: ${successCount} successful, ${failureCount} failed`\n );\n\n // Send completed progress update\n sendProgressUpdate(\n commandId,\n \"delete_multiple_nodes\",\n \"completed\",\n 100,\n nodeIds.length,\n successCount + failureCount,\n `Node deletion complete: ${successCount} successful, ${failureCount} failed`,\n {\n totalNodes: nodeIds.length,\n nodesDeleted: successCount,\n nodesFailed: failureCount,\n completedInChunks: chunks.length,\n results: results,\n }\n );\n\n return {\n success: successCount > 0,\n nodesDeleted: successCount,\n nodesFailed: failureCount,\n totalNodes: nodeIds.length,\n results: results,\n completedInChunks: chunks.length,\n commandId,\n };\n}\n\n// Implementation for getInstanceOverrides function\nasync function getInstanceOverrides(instanceNode = null) {\n console.log(\"=== getInstanceOverrides called ===\");\n\n let sourceInstance = null;\n\n // Check if an instance node was passed directly\n if (instanceNode) {\n console.log(\"Using provided instance node\");\n\n // Validate that the provided node is an instance\n if (instanceNode.type !== \"INSTANCE\") {\n console.error(\"Provided node is not an instance\");\n figma.notify(\"Provided node is not a component instance\");\n return { success: false, message: \"Provided node is not a component instance\" };\n }\n\n sourceInstance = instanceNode;\n } else {\n // No node provided, use selection\n console.log(\"No node provided, using current selection\");\n\n // Get the current selection\n const selection = figma.currentPage.selection;\n\n // Check if there's anything selected\n if (selection.length === 0) {\n console.log(\"No nodes selected\");\n figma.notify(\"Please select at least one instance\");\n return { success: false, message: \"No nodes selected\" };\n }\n\n // Filter for instances in the selection\n const instances = selection.filter(node => node.type === \"INSTANCE\");\n\n if (instances.length === 0) {\n console.log(\"No instances found in selection\");\n figma.notify(\"Please select at least one component instance\");\n return { success: false, message: \"No instances found in selection\" };\n }\n\n // Take the first instance from the selection\n sourceInstance = instances[0];\n }\n\n try {\n console.log(`Getting instance information:`);\n console.log(sourceInstance);\n\n // Get component overrides and main component\n const overrides = sourceInstance.overrides || [];\n console.log(` Raw Overrides:`, overrides);\n\n // Get main component\n const mainComponent = await sourceInstance.getMainComponentAsync();\n if (!mainComponent) {\n console.error(\"Failed to get main component\");\n figma.notify(\"Failed to get main component\");\n return { success: false, message: \"Failed to get main component\" };\n }\n\n // return data to MCP server\n const returnData = {\n success: true,\n message: `Got component information from \"${sourceInstance.name}\" for overrides.length: ${overrides.length}`,\n sourceInstanceId: sourceInstance.id,\n mainComponentId: mainComponent.id,\n overridesCount: overrides.length\n };\n\n console.log(\"Data to return to MCP server:\", returnData);\n figma.notify(`Got component information from \"${sourceInstance.name}\"`);\n\n return returnData;\n } catch (error) {\n console.error(\"Error in getInstanceOverrides:\", error);\n figma.notify(`Error: ${error.message}`);\n return {\n success: false,\n message: `Error: ${error.message}`\n };\n }\n}\n\n/**\n * Helper function to validate and get target instances\n * @param {string[]} targetNodeIds - Array of instance node IDs\n * @returns {instanceNode[]} targetInstances - Array of target instances\n */\nasync function getValidTargetInstances(targetNodeIds) {\n let targetInstances = [];\n\n // Handle array of instances or single instance\n if (Array.isArray(targetNodeIds)) {\n if (targetNodeIds.length === 0) {\n return { success: false, message: \"No instances provided\" };\n }\n for (const targetNodeId of targetNodeIds) {\n const targetNode = await figma.getNodeByIdAsync(targetNodeId);\n if (targetNode && targetNode.type === \"INSTANCE\") {\n targetInstances.push(targetNode);\n }\n }\n if (targetInstances.length === 0) {\n return { success: false, message: \"No valid instances provided\" };\n }\n } else {\n return { success: false, message: \"Invalid target node IDs provided\" };\n }\n\n\n return { success: true, message: \"Valid target instances provided\", targetInstances };\n}\n\n/**\n * Helper function to validate and get saved override data\n * @param {string} sourceInstanceId - Source instance ID\n * @returns {Promise} - Validation result with source instance data or error\n */\nasync function getSourceInstanceData(sourceInstanceId) {\n if (!sourceInstanceId) {\n return { success: false, message: \"Missing source instance ID\" };\n }\n\n // Get source instance by ID\n const sourceInstance = await figma.getNodeByIdAsync(sourceInstanceId);\n if (!sourceInstance) {\n return {\n success: false,\n message: \"Source instance not found. The original instance may have been deleted.\"\n };\n }\n\n // Verify it's an instance\n if (sourceInstance.type !== \"INSTANCE\") {\n return {\n success: false,\n message: \"Source node is not a component instance.\"\n };\n }\n\n // Get main component\n const mainComponent = await sourceInstance.getMainComponentAsync();\n if (!mainComponent) {\n return {\n success: false,\n message: \"Failed to get main component from source instance.\"\n };\n }\n\n return {\n success: true,\n sourceInstance,\n mainComponent,\n overrides: sourceInstance.overrides || []\n };\n}\n\n/**\n * Sets saved overrides to the selected component instance(s)\n * @param {InstanceNode[] | null} targetInstances - Array of instance nodes to set overrides to\n * @param {Object} sourceResult - Source instance data from getSourceInstanceData\n * @returns {Promise} - Result of the set operation\n */\nasync function setInstanceOverrides(targetInstances, sourceResult) {\n try {\n\n\n const { sourceInstance, mainComponent, overrides } = sourceResult;\n\n console.log(`Processing ${targetInstances.length} instances with ${overrides.length} overrides`);\n console.log(`Source instance: ${sourceInstance.id}, Main component: ${mainComponent.id}`);\n console.log(`Overrides:`, overrides);\n\n // Process all instances\n const results = [];\n let totalAppliedCount = 0;\n\n for (const targetInstance of targetInstances) {\n try {\n // // Skip if trying to apply to the source instance itself\n // if (targetInstance.id === sourceInstance.id) {\n // console.log(`Skipping source instance itself: ${targetInstance.id}`);\n // results.push({\n // success: false,\n // instanceId: targetInstance.id,\n // instanceName: targetInstance.name,\n // message: \"This is the source instance itself, skipping\"\n // });\n // continue;\n // }\n\n // Swap component\n try {\n targetInstance.swapComponent(mainComponent);\n console.log(`Swapped component for instance \"${targetInstance.name}\"`);\n } catch (error) {\n console.error(`Error swapping component for instance \"${targetInstance.name}\":`, error);\n results.push({\n success: false,\n instanceId: targetInstance.id,\n instanceName: targetInstance.name,\n message: `Error: ${error.message}`\n });\n }\n\n // Prepare overrides by replacing node IDs\n let appliedCount = 0;\n\n // Apply each override\n for (const override of overrides) {\n // Skip if no ID or overriddenFields\n if (!override.id || !override.overriddenFields || override.overriddenFields.length === 0) {\n continue;\n }\n\n // Replace source instance ID with target instance ID in the node path\n const overrideNodeId = override.id.replace(sourceInstance.id, targetInstance.id);\n const overrideNode = await figma.getNodeByIdAsync(overrideNodeId);\n\n if (!overrideNode) {\n console.log(`Override node not found: ${overrideNodeId}`);\n continue;\n }\n\n // Get source node to copy properties from\n const sourceNode = await figma.getNodeByIdAsync(override.id);\n if (!sourceNode) {\n console.log(`Source node not found: ${override.id}`);\n continue;\n }\n\n // Apply each overridden field\n let fieldApplied = false;\n for (const field of override.overriddenFields) {\n try {\n if (field === \"componentProperties\") {\n // Apply component properties\n if (sourceNode.componentProperties && overrideNode.componentProperties) {\n const properties = {};\n for (const key in sourceNode.componentProperties) {\n // if INSTANCE_SWAP use id, otherwise use value\n if (sourceNode.componentProperties[key].type === 'INSTANCE_SWAP') {\n properties[key] = sourceNode.componentProperties[key].value;\n \n } else {\n properties[key] = sourceNode.componentProperties[key].value;\n }\n }\n overrideNode.setProperties(properties);\n fieldApplied = true;\n }\n } else if (field === \"characters\" && overrideNode.type === \"TEXT\") {\n // For text nodes, need to load fonts first\n await figma.loadFontAsync(overrideNode.fontName);\n overrideNode.characters = sourceNode.characters;\n fieldApplied = true;\n } else if (field in overrideNode) {\n // Direct property assignment\n overrideNode[field] = sourceNode[field];\n fieldApplied = true;\n }\n } catch (fieldError) {\n console.error(`Error applying field ${field}:`, fieldError);\n }\n }\n\n if (fieldApplied) {\n appliedCount++;\n }\n }\n\n if (appliedCount > 0) {\n totalAppliedCount += appliedCount;\n results.push({\n success: true,\n instanceId: targetInstance.id,\n instanceName: targetInstance.name,\n appliedCount\n });\n console.log(`Applied ${appliedCount} overrides to \"${targetInstance.name}\"`);\n } else {\n results.push({\n success: false,\n instanceId: targetInstance.id,\n instanceName: targetInstance.name,\n message: \"No overrides were applied\"\n });\n }\n } catch (instanceError) {\n console.error(`Error processing instance \"${targetInstance.name}\":`, instanceError);\n results.push({\n success: false,\n instanceId: targetInstance.id,\n instanceName: targetInstance.name,\n message: `Error: ${instanceError.message}`\n });\n }\n }\n\n // Return results\n if (totalAppliedCount > 0) {\n const instanceCount = results.filter(r => r.success).length;\n const message = `Applied ${totalAppliedCount} overrides to ${instanceCount} instances`;\n figma.notify(message);\n return {\n success: true,\n message,\n totalCount: totalAppliedCount,\n results\n };\n } else {\n const message = \"No overrides applied to any instance\";\n figma.notify(message);\n return { success: false, message, results };\n }\n\n } catch (error) {\n console.error(\"Error in setInstanceOverrides:\", error);\n const message = `Error: ${error.message}`;\n figma.notify(message);\n return { success: false, message };\n }\n}\n\nasync function setLayoutMode(params) {\n const { nodeId, layoutMode = \"NONE\", layoutWrap = \"NO_WRAP\" } = params || {};\n\n // Get the target node\n const node = await figma.getNodeByIdAsync(nodeId);\n if (!node) {\n throw new Error(`Node with ID ${nodeId} not found`);\n }\n\n // Check if node is a frame or component that supports layoutMode\n if (\n node.type !== \"FRAME\" &&\n node.type !== \"COMPONENT\" &&\n node.type !== \"COMPONENT_SET\" &&\n node.type !== \"INSTANCE\"\n ) {\n throw new Error(`Node type ${node.type} does not support layoutMode`);\n }\n\n // Set layout mode\n node.layoutMode = layoutMode;\n\n // Set layoutWrap if applicable\n if (layoutMode !== \"NONE\") {\n node.layoutWrap = layoutWrap;\n }\n\n return {\n id: node.id,\n name: node.name,\n layoutMode: node.layoutMode,\n layoutWrap: node.layoutWrap,\n };\n}\n\nasync function setPadding(params) {\n const { nodeId, paddingTop, paddingRight, paddingBottom, paddingLeft } =\n params || {};\n\n // Get the target node\n const node = await figma.getNodeByIdAsync(nodeId);\n if (!node) {\n throw new Error(`Node with ID ${nodeId} not found`);\n }\n\n // Check if node is a frame or component that supports padding\n if (\n node.type !== \"FRAME\" &&\n node.type !== \"COMPONENT\" &&\n node.type !== \"COMPONENT_SET\" &&\n node.type !== \"INSTANCE\"\n ) {\n throw new Error(`Node type ${node.type} does not support padding`);\n }\n\n // Check if the node has auto-layout enabled\n if (node.layoutMode === \"NONE\") {\n throw new Error(\n \"Padding can only be set on auto-layout frames (layoutMode must not be NONE)\"\n );\n }\n\n // Set padding values if provided\n if (paddingTop !== undefined) node.paddingTop = paddingTop;\n if (paddingRight !== undefined) node.paddingRight = paddingRight;\n if (paddingBottom !== undefined) node.paddingBottom = paddingBottom;\n if (paddingLeft !== undefined) node.paddingLeft = paddingLeft;\n\n return {\n id: node.id,\n name: node.name,\n paddingTop: node.paddingTop,\n paddingRight: node.paddingRight,\n paddingBottom: node.paddingBottom,\n paddingLeft: node.paddingLeft,\n };\n}\n\nasync function setAxisAlign(params) {\n const { nodeId, primaryAxisAlignItems, counterAxisAlignItems } = params || {};\n\n // Get the target node\n const node = await figma.getNodeByIdAsync(nodeId);\n if (!node) {\n throw new Error(`Node with ID ${nodeId} not found`);\n }\n\n // Check if node is a frame or component that supports axis alignment\n if (\n node.type !== \"FRAME\" &&\n node.type !== \"COMPONENT\" &&\n node.type !== \"COMPONENT_SET\" &&\n node.type !== \"INSTANCE\"\n ) {\n throw new Error(`Node type ${node.type} does not support axis alignment`);\n }\n\n // Check if the node has auto-layout enabled\n if (node.layoutMode === \"NONE\") {\n throw new Error(\n \"Axis alignment can only be set on auto-layout frames (layoutMode must not be NONE)\"\n );\n }\n\n // Validate and set primaryAxisAlignItems if provided\n if (primaryAxisAlignItems !== undefined) {\n if (\n ![\"MIN\", \"MAX\", \"CENTER\", \"SPACE_BETWEEN\"].includes(primaryAxisAlignItems)\n ) {\n throw new Error(\n \"Invalid primaryAxisAlignItems value. Must be one of: MIN, MAX, CENTER, SPACE_BETWEEN\"\n );\n }\n node.primaryAxisAlignItems = primaryAxisAlignItems;\n }\n\n // Validate and set counterAxisAlignItems if provided\n if (counterAxisAlignItems !== undefined) {\n if (![\"MIN\", \"MAX\", \"CENTER\", \"BASELINE\"].includes(counterAxisAlignItems)) {\n throw new Error(\n \"Invalid counterAxisAlignItems value. Must be one of: MIN, MAX, CENTER, BASELINE\"\n );\n }\n // BASELINE is only valid for horizontal layout\n if (\n counterAxisAlignItems === \"BASELINE\" &&\n node.layoutMode !== \"HORIZONTAL\"\n ) {\n throw new Error(\n \"BASELINE alignment is only valid for horizontal auto-layout frames\"\n );\n }\n node.counterAxisAlignItems = counterAxisAlignItems;\n }\n\n return {\n id: node.id,\n name: node.name,\n primaryAxisAlignItems: node.primaryAxisAlignItems,\n counterAxisAlignItems: node.counterAxisAlignItems,\n layoutMode: node.layoutMode,\n };\n}\n\nasync function setLayoutSizing(params) {\n const { nodeId, layoutSizingHorizontal, layoutSizingVertical } = params || {};\n\n // Get the target node\n const node = await figma.getNodeByIdAsync(nodeId);\n if (!node) {\n throw new Error(`Node with ID ${nodeId} not found`);\n }\n\n // Check if node is a frame or component that supports layout sizing\n if (\n node.type !== \"FRAME\" &&\n node.type !== \"COMPONENT\" &&\n node.type !== \"COMPONENT_SET\" &&\n node.type !== \"INSTANCE\"\n ) {\n throw new Error(`Node type ${node.type} does not support layout sizing`);\n }\n\n // Check if the node has auto-layout enabled\n if (node.layoutMode === \"NONE\") {\n throw new Error(\n \"Layout sizing can only be set on auto-layout frames (layoutMode must not be NONE)\"\n );\n }\n\n // Validate and set layoutSizingHorizontal if provided\n if (layoutSizingHorizontal !== undefined) {\n if (![\"FIXED\", \"HUG\", \"FILL\"].includes(layoutSizingHorizontal)) {\n throw new Error(\n \"Invalid layoutSizingHorizontal value. Must be one of: FIXED, HUG, FILL\"\n );\n }\n // HUG is only valid on auto-layout frames and text nodes\n if (\n layoutSizingHorizontal === \"HUG\" &&\n ![\"FRAME\", \"TEXT\"].includes(node.type)\n ) {\n throw new Error(\n \"HUG sizing is only valid on auto-layout frames and text nodes\"\n );\n }\n // FILL is only valid on auto-layout children\n if (\n layoutSizingHorizontal === \"FILL\" &&\n (!node.parent || node.parent.layoutMode === \"NONE\")\n ) {\n throw new Error(\"FILL sizing is only valid on auto-layout children\");\n }\n node.layoutSizingHorizontal = layoutSizingHorizontal;\n }\n\n // Validate and set layoutSizingVertical if provided\n if (layoutSizingVertical !== undefined) {\n if (![\"FIXED\", \"HUG\", \"FILL\"].includes(layoutSizingVertical)) {\n throw new Error(\n \"Invalid layoutSizingVertical value. Must be one of: FIXED, HUG, FILL\"\n );\n }\n // HUG is only valid on auto-layout frames and text nodes\n if (\n layoutSizingVertical === \"HUG\" &&\n ![\"FRAME\", \"TEXT\"].includes(node.type)\n ) {\n throw new Error(\n \"HUG sizing is only valid on auto-layout frames and text nodes\"\n );\n }\n // FILL is only valid on auto-layout children\n if (\n layoutSizingVertical === \"FILL\" &&\n (!node.parent || node.parent.layoutMode === \"NONE\")\n ) {\n throw new Error(\"FILL sizing is only valid on auto-layout children\");\n }\n node.layoutSizingVertical = layoutSizingVertical;\n }\n\n return {\n id: node.id,\n name: node.name,\n layoutSizingHorizontal: node.layoutSizingHorizontal,\n layoutSizingVertical: node.layoutSizingVertical,\n layoutMode: node.layoutMode,\n };\n}\n\nasync function setItemSpacing(params) {\n const { nodeId, itemSpacing } = params || {};\n\n // Get the target node\n const node = await figma.getNodeByIdAsync(nodeId);\n if (!node) {\n throw new Error(`Node with ID ${nodeId} not found`);\n }\n\n // Check if node is a frame or component that supports item spacing\n if (\n node.type !== \"FRAME\" &&\n node.type !== \"COMPONENT\" &&\n node.type !== \"COMPONENT_SET\" &&\n node.type !== \"INSTANCE\"\n ) {\n throw new Error(`Node type ${node.type} does not support item spacing`);\n }\n\n // Check if the node has auto-layout enabled\n if (node.layoutMode === \"NONE\") {\n throw new Error(\n \"Item spacing can only be set on auto-layout frames (layoutMode must not be NONE)\"\n );\n }\n\n // Set item spacing\n if (itemSpacing !== undefined) {\n if (typeof itemSpacing !== \"number\") {\n throw new Error(\"Item spacing must be a number\");\n }\n node.itemSpacing = itemSpacing;\n }\n\n return {\n id: node.id,\n name: node.name,\n itemSpacing: node.itemSpacing,\n layoutMode: node.layoutMode,\n };\n}\n\nasync function setDefaultConnector(params) {\n const { connectorId } = params || {};\n \n // If connectorId is provided, search and set by that ID (do not check existing storage)\n if (connectorId) {\n // Get node by specified ID\n const node = await figma.getNodeByIdAsync(connectorId);\n if (!node) {\n throw new Error(`Connector node not found with ID: ${connectorId}`);\n }\n \n // Check node type\n if (node.type !== 'CONNECTOR') {\n throw new Error(`Node is not a connector: ${connectorId}`);\n }\n \n // Set the found connector as the default connector\n await figma.clientStorage.setAsync('defaultConnectorId', connectorId);\n \n return {\n success: true,\n message: `Default connector set to: ${connectorId}`,\n connectorId: connectorId\n };\n } \n // If connectorId is not provided, check existing storage\n else {\n // Check if there is an existing default connector in client storage\n try {\n const existingConnectorId = await figma.clientStorage.getAsync('defaultConnectorId');\n \n // If there is an existing connector ID, check if the node is still valid\n if (existingConnectorId) {\n try {\n const existingConnector = await figma.getNodeByIdAsync(existingConnectorId);\n \n // If the stored connector still exists and is of type CONNECTOR\n if (existingConnector && existingConnector.type === 'CONNECTOR') {\n return {\n success: true,\n message: `Default connector is already set to: ${existingConnectorId}`,\n connectorId: existingConnectorId,\n exists: true\n };\n }\n // The stored connector is no longer valid - find a new connector\n else {\n console.log(`Stored connector ID ${existingConnectorId} is no longer valid, finding a new connector...`);\n }\n } catch (error) {\n console.log(`Error finding stored connector: ${error.message}. Will try to set a new one.`);\n }\n }\n } catch (error) {\n console.log(`Error checking for existing connector: ${error.message}`);\n }\n \n // If there is no stored default connector or it is invalid, find one in the current page\n try {\n // Find CONNECTOR type nodes in the current page\n const currentPageConnectors = figma.currentPage.findAllWithCriteria({ types: ['CONNECTOR'] });\n \n if (currentPageConnectors && currentPageConnectors.length > 0) {\n // Use the first connector found\n const foundConnector = currentPageConnectors[0];\n const autoFoundId = foundConnector.id;\n \n // Set the found connector as the default connector\n await figma.clientStorage.setAsync('defaultConnectorId', autoFoundId);\n \n return {\n success: true,\n message: `Automatically found and set default connector to: ${autoFoundId}`,\n connectorId: autoFoundId,\n autoSelected: true\n };\n } else {\n // If no connector is found in the current page, show a guide message\n throw new Error('No connector found in the current page. Please create a connector in Figma first or specify a connector ID.');\n }\n } catch (error) {\n // Error occurred while running findAllWithCriteria\n throw new Error(`Failed to find a connector: ${error.message}`);\n }\n }\n}\n\nasync function createCursorNode(targetNodeId) {\n const svgString = `\n \n `;\n try {\n const targetNode = await figma.getNodeByIdAsync(targetNodeId);\n if (!targetNode) throw new Error(\"Target node not found\");\n\n // The targetNodeId has semicolons since it is a nested node.\n // So we need to get the parent node ID from the target node ID and check if we can appendChild to it or not.\n let parentNodeId = targetNodeId.includes(';') \n ? targetNodeId.split(';')[0] \n : targetNodeId;\n if (!parentNodeId) throw new Error(\"Could not determine parent node ID\");\n\n // Find the parent node to append cursor node as child\n let parentNode = await figma.getNodeByIdAsync(parentNodeId);\n if (!parentNode) throw new Error(\"Parent node not found\");\n\n // If the parent node is not eligible to appendChild, set the parentNode to the parent of the parentNode\n if (parentNode.type === 'INSTANCE' || parentNode.type === 'COMPONENT' || parentNode.type === 'COMPONENT_SET') {\n parentNode = parentNode.parent;\n if (!parentNode) throw new Error(\"Parent node not found\");\n }\n\n // Create the cursor node\n const importedNode = await figma.createNodeFromSvg(svgString);\n if (!importedNode || !importedNode.id) {\n throw new Error(\"Failed to create imported cursor node\");\n }\n importedNode.name = \"TTF_Connector / Mouse Cursor\";\n importedNode.resize(48, 48);\n\n const cursorNode = importedNode.findOne(node => node.type === 'VECTOR');\n if (cursorNode) {\n cursorNode.fills = [{\n type: 'SOLID',\n color: { r: 0, g: 0, b: 0 },\n opacity: 1\n }];\n cursorNode.strokes = [{\n type: 'SOLID',\n color: { r: 1, g: 1, b: 1 },\n opacity: 1\n }];\n cursorNode.strokeWeight = 2;\n cursorNode.strokeAlign = 'OUTSIDE';\n cursorNode.effects = [{\n type: \"DROP_SHADOW\",\n color: { r: 0, g: 0, b: 0, a: 0.3 },\n offset: { x: 1, y: 1 },\n radius: 2,\n spread: 0,\n visible: true,\n blendMode: \"NORMAL\"\n }];\n }\n\n // Append the cursor node to the parent node\n parentNode.appendChild(importedNode);\n\n // if the parentNode has auto-layout enabled, set the layoutPositioning to ABSOLUTE\n if ('layoutMode' in parentNode && parentNode.layoutMode !== 'NONE') {\n importedNode.layoutPositioning = 'ABSOLUTE';\n }\n\n // Adjust the importedNode's position to the targetNode's position\n if (\n targetNode.absoluteBoundingBox &&\n parentNode.absoluteBoundingBox\n ) {\n // if the targetNode has absoluteBoundingBox, set the importedNode's absoluteBoundingBox to the targetNode's absoluteBoundingBox\n console.log('targetNode.absoluteBoundingBox', targetNode.absoluteBoundingBox);\n console.log('parentNode.absoluteBoundingBox', parentNode.absoluteBoundingBox);\n importedNode.x = targetNode.absoluteBoundingBox.x - parentNode.absoluteBoundingBox.x + targetNode.absoluteBoundingBox.width / 2 - 48 / 2\n importedNode.y = targetNode.absoluteBoundingBox.y - parentNode.absoluteBoundingBox.y + targetNode.absoluteBoundingBox.height / 2 - 48 / 2;\n } else if (\n 'x' in targetNode && 'y' in targetNode && 'width' in targetNode && 'height' in targetNode) {\n // if the targetNode has x, y, width, height, calculate center based on relative position\n console.log('targetNode.x/y/width/height', targetNode.x, targetNode.y, targetNode.width, targetNode.height);\n importedNode.x = targetNode.x + targetNode.width / 2 - 48 / 2;\n importedNode.y = targetNode.y + targetNode.height / 2 - 48 / 2;\n } else {\n // Fallback: Place at top-left of target if possible, otherwise at (0,0) relative to parent\n if ('x' in targetNode && 'y' in targetNode) {\n console.log('Fallback to targetNode x/y');\n importedNode.x = targetNode.x;\n importedNode.y = targetNode.y;\n } else {\n console.log('Fallback to (0,0)');\n importedNode.x = 0;\n importedNode.y = 0;\n }\n }\n\n // get the importedNode ID and the importedNode\n console.log('importedNode', importedNode);\n\n\n return { id: importedNode.id, node: importedNode };\n \n } catch (error) {\n console.error(\"Error creating cursor from SVG:\", error);\n return { id: null, node: null, error: error.message };\n }\n}\n\nasync function createConnections(params) {\n if (!params || !params.connections || !Array.isArray(params.connections)) {\n throw new Error('Missing or invalid connections parameter');\n }\n \n const { connections } = params;\n \n // Command ID for progress tracking\n const commandId = generateCommandId();\n sendProgressUpdate(\n commandId,\n \"create_connections\",\n \"started\",\n 0,\n connections.length,\n 0,\n `Starting to create ${connections.length} connections`\n );\n \n // Get default connector ID from client storage\n const defaultConnectorId = await figma.clientStorage.getAsync('defaultConnectorId');\n if (!defaultConnectorId) {\n throw new Error('No default connector set. Please try one of the following options to create connections:\\n1. Create a connector in FigJam and copy/paste it to your current page, then run the \"set_default_connector\" command.\\n2. Select an existing connector on the current page, then run the \"set_default_connector\" command.');\n }\n \n // Get the default connector\n const defaultConnector = await figma.getNodeByIdAsync(defaultConnectorId);\n if (!defaultConnector) {\n throw new Error(`Default connector not found with ID: ${defaultConnectorId}`);\n }\n if (defaultConnector.type !== 'CONNECTOR') {\n throw new Error(`Node is not a connector: ${defaultConnectorId}`);\n }\n \n // Results array for connection creation\n const results = [];\n let processedCount = 0;\n const totalCount = connections.length;\n \n // Preload fonts (used for text if provided)\n let fontLoaded = false;\n \n for (let i = 0; i < connections.length; i++) {\n try {\n const { startNodeId: originalStartId, endNodeId: originalEndId, text } = connections[i];\n let startId = originalStartId;\n let endId = originalEndId;\n\n // Check and potentially replace start node ID\n if (startId.includes(';')) {\n console.log(`Nested start node detected: ${startId}. Creating cursor node.`);\n const cursorResult = await createCursorNode(startId);\n if (!cursorResult || !cursorResult.id) {\n throw new Error(`Failed to create cursor node for nested start node: ${startId}`);\n }\n startId = cursorResult.id; \n } \n \n const startNode = await figma.getNodeByIdAsync(startId);\n if (!startNode) throw new Error(`Start node not found with ID: ${startId}`);\n\n // Check and potentially replace end node ID\n if (endId.includes(';')) {\n console.log(`Nested end node detected: ${endId}. Creating cursor node.`);\n const cursorResult = await createCursorNode(endId);\n if (!cursorResult || !cursorResult.id) {\n throw new Error(`Failed to create cursor node for nested end node: ${endId}`);\n }\n endId = cursorResult.id;\n }\n const endNode = await figma.getNodeByIdAsync(endId);\n if (!endNode) throw new Error(`End node not found with ID: ${endId}`);\n\n \n // Clone the default connector\n const clonedConnector = defaultConnector.clone();\n \n // Update connector name using potentially replaced node names\n clonedConnector.name = `TTF_Connector/${startNode.id}/${endNode.id}`;\n \n // Set start and end points using potentially replaced IDs\n clonedConnector.connectorStart = {\n endpointNodeId: startId,\n magnet: 'AUTO'\n };\n \n clonedConnector.connectorEnd = {\n endpointNodeId: endId,\n magnet: 'AUTO'\n };\n \n // Add text (if provided)\n if (text) {\n try {\n // Try to load the necessary fonts\n try {\n // First check if default connector has font and use the same\n if (defaultConnector.text && defaultConnector.text.fontName) {\n const fontName = defaultConnector.text.fontName;\n await figma.loadFontAsync(fontName);\n clonedConnector.text.fontName = fontName;\n } else {\n // Try default Inter font\n await figma.loadFontAsync({ family: \"Inter\", style: \"Regular\" });\n }\n } catch (fontError) {\n // If first font load fails, try another font style\n try {\n await figma.loadFontAsync({ family: \"Inter\", style: \"Medium\" });\n } catch (mediumFontError) {\n // If second font fails, try system font\n try {\n await figma.loadFontAsync({ family: \"System\", style: \"Regular\" });\n } catch (systemFontError) {\n // If all font loading attempts fail, throw error\n throw new Error(`Failed to load any font: ${fontError.message}`);\n }\n }\n }\n \n // Set the text\n clonedConnector.text.characters = text;\n } catch (textError) {\n console.error(\"Error setting text:\", textError);\n // Continue with connection even if text setting fails\n results.push({\n id: clonedConnector.id,\n startNodeId: startNodeId,\n endNodeId: endNodeId,\n text: \"\",\n textError: textError.message\n });\n \n // Continue to next connection\n continue;\n }\n }\n \n // Add to results (using the *original* IDs for reference if needed)\n results.push({\n id: clonedConnector.id,\n originalStartNodeId: originalStartId,\n originalEndNodeId: originalEndId,\n usedStartNodeId: startId, // ID actually used for connection\n usedEndNodeId: endId, // ID actually used for connection\n text: text || \"\"\n });\n \n // Update progress\n processedCount++;\n sendProgressUpdate(\n commandId,\n \"create_connections\",\n \"in_progress\",\n processedCount / totalCount,\n totalCount,\n processedCount,\n `Created connection ${processedCount}/${totalCount}`\n );\n \n } catch (error) {\n console.error(\"Error creating connection\", error);\n // Continue processing remaining connections even if an error occurs\n processedCount++;\n sendProgressUpdate(\n commandId,\n \"create_connections\",\n \"in_progress\",\n processedCount / totalCount,\n totalCount,\n processedCount,\n `Error creating connection: ${error.message}`\n );\n \n results.push({\n error: error.message,\n connectionInfo: connections[i]\n });\n }\n }\n \n // Completion update\n sendProgressUpdate(\n commandId,\n \"create_connections\",\n \"completed\",\n 1,\n totalCount,\n totalCount,\n `Completed creating ${results.length} connections`\n );\n \n return {\n success: true,\n count: results.length,\n connections: results\n };\n}\n", "middle_code": "async function setMultipleTextContents(params) {\n const { nodeId, text } = params || {};\n const commandId = params.commandId || generateCommandId();\n if (!nodeId || !text || !Array.isArray(text)) {\n const errorMsg = \"Missing required parameters: nodeId and text array\";\n sendProgressUpdate(\n commandId,\n \"set_multiple_text_contents\",\n \"error\",\n 0,\n 0,\n 0,\n errorMsg,\n { error: errorMsg }\n );\n throw new Error(errorMsg);\n }\n console.log(\n `Starting text replacement for node: ${nodeId} with ${text.length} text replacements`\n );\n sendProgressUpdate(\n commandId,\n \"set_multiple_text_contents\",\n \"started\",\n 0,\n text.length,\n 0,\n `Starting text replacement for ${text.length} nodes`,\n { totalReplacements: text.length }\n );\n const results = [];\n let successCount = 0;\n let failureCount = 0;\n const CHUNK_SIZE = 5;\n const chunks = [];\n for (let i = 0; i < text.length; i += CHUNK_SIZE) {\n chunks.push(text.slice(i, i + CHUNK_SIZE));\n }\n console.log(`Split ${text.length} replacements into ${chunks.length} chunks`);\n sendProgressUpdate(\n commandId,\n \"set_multiple_text_contents\",\n \"in_progress\",\n 5, \n text.length,\n 0,\n `Preparing to replace text in ${text.length} nodes using ${chunks.length} chunks`,\n {\n totalReplacements: text.length,\n chunks: chunks.length,\n chunkSize: CHUNK_SIZE,\n }\n );\n for (let chunkIndex = 0; chunkIndex < chunks.length; chunkIndex++) {\n const chunk = chunks[chunkIndex];\n console.log(\n `Processing chunk ${chunkIndex + 1}/${chunks.length} with ${chunk.length\n } replacements`\n );\n sendProgressUpdate(\n commandId,\n \"set_multiple_text_contents\",\n \"in_progress\",\n Math.round(5 + (chunkIndex / chunks.length) * 90), \n text.length,\n successCount + failureCount,\n `Processing text replacements chunk ${chunkIndex + 1}/${chunks.length}`,\n {\n currentChunk: chunkIndex + 1,\n totalChunks: chunks.length,\n successCount,\n failureCount,\n }\n );\n const chunkPromises = chunk.map(async (replacement) => {\n if (!replacement.nodeId || replacement.text === undefined) {\n console.error(`Missing nodeId or text for replacement`);\n return {\n success: false,\n nodeId: replacement.nodeId || \"unknown\",\n error: \"Missing nodeId or text in replacement entry\",\n };\n }\n try {\n console.log(\n `Attempting to replace text in node: ${replacement.nodeId}`\n );\n const textNode = await figma.getNodeByIdAsync(replacement.nodeId);\n if (!textNode) {\n console.error(`Text node not found: ${replacement.nodeId}`);\n return {\n success: false,\n nodeId: replacement.nodeId,\n error: `Node not found: ${replacement.nodeId}`,\n };\n }\n if (textNode.type !== \"TEXT\") {\n console.error(\n `Node is not a text node: ${replacement.nodeId} (type: ${textNode.type})`\n );\n return {\n success: false,\n nodeId: replacement.nodeId,\n error: `Node is not a text node: ${replacement.nodeId} (type: ${textNode.type})`,\n };\n }\n const originalText = textNode.characters;\n console.log(`Original text: \"${originalText}\"`);\n console.log(`Will translate to: \"${replacement.text}\"`);\n let originalFills;\n try {\n originalFills = JSON.parse(JSON.stringify(textNode.fills));\n textNode.fills = [\n {\n type: \"SOLID\",\n color: { r: 1, g: 0.5, b: 0 },\n opacity: 0.3,\n },\n ];\n } catch (highlightErr) {\n console.error(\n `Error highlighting text node: ${highlightErr.message}`\n );\n }\n await setTextContent({\n nodeId: replacement.nodeId,\n text: replacement.text,\n });\n if (originalFills) {\n try {\n await delay(500);\n textNode.fills = originalFills;\n } catch (restoreErr) {\n console.error(`Error restoring fills: ${restoreErr.message}`);\n }\n }\n console.log(\n `Successfully replaced text in node: ${replacement.nodeId}`\n );\n return {\n success: true,\n nodeId: replacement.nodeId,\n originalText: originalText,\n translatedText: replacement.text,\n };\n } catch (error) {\n console.error(\n `Error replacing text in node ${replacement.nodeId}: ${error.message}`\n );\n return {\n success: false,\n nodeId: replacement.nodeId,\n error: `Error applying replacement: ${error.message}`,\n };\n }\n });\n const chunkResults = await Promise.all(chunkPromises);\n chunkResults.forEach((result) => {\n if (result.success) {\n successCount++;\n } else {\n failureCount++;\n }\n results.push(result);\n });\n sendProgressUpdate(\n commandId,\n \"set_multiple_text_contents\",\n \"in_progress\",\n Math.round(5 + ((chunkIndex + 1) / chunks.length) * 90), \n text.length,\n successCount + failureCount,\n `Completed chunk ${chunkIndex + 1}/${chunks.length\n }. ${successCount} successful, ${failureCount} failed so far.`,\n {\n currentChunk: chunkIndex + 1,\n totalChunks: chunks.length,\n successCount,\n failureCount,\n chunkResults: chunkResults,\n }\n );\n if (chunkIndex < chunks.length - 1) {\n console.log(\"Pausing between chunks to avoid overloading Figma...\");\n await delay(1000); \n }\n }\n console.log(\n `Replacement complete: ${successCount} successful, ${failureCount} failed`\n );\n sendProgressUpdate(\n commandId,\n \"set_multiple_text_contents\",\n \"completed\",\n 100,\n text.length,\n successCount + failureCount,\n `Text replacement complete: ${successCount} successful, ${failureCount} failed`,\n {\n totalReplacements: text.length,\n replacementsApplied: successCount,\n replacementsFailed: failureCount,\n completedInChunks: chunks.length,\n results: results,\n }\n );\n return {\n success: successCount > 0,\n nodeId: nodeId,\n replacementsApplied: successCount,\n replacementsFailed: failureCount,\n totalReplacements: text.length,\n results: results,\n completedInChunks: chunks.length,\n commandId,\n };\n}", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "javascript", "sub_task_type": null}, "context_code": [["/cursor-talk-to-figma-mcp/src/cursor_mcp_plugin/setcharacters.js", "function uniqBy(arr, predicate) {\n const cb = typeof predicate === \"function\" ? predicate : (o) => o[predicate];\n return [\n ...arr\n .reduce((map, item) => {\n const key = item === null || item === undefined ? item : cb(item);\n\n map.has(key) || map.set(key, item);\n\n return map;\n }, new Map())\n .values(),\n ];\n}\nexport const setCharacters = async (node, characters, options) => {\n const fallbackFont = options?.fallbackFont || {\n family: \"Roboto\",\n style: \"Regular\",\n };\n try {\n if (node.fontName === figma.mixed) {\n if (options?.smartStrategy === \"prevail\") {\n const fontHashTree = {};\n for (let i = 1; i < node.characters.length; i++) {\n const charFont = node.getRangeFontName(i - 1, i);\n const key = `${charFont.family}::${charFont.style}`;\n fontHashTree[key] = fontHashTree[key] ? fontHashTree[key] + 1 : 1;\n }\n const prevailedTreeItem = Object.entries(fontHashTree).sort(\n (a, b) => b[1] - a[1]\n )[0];\n const [family, style] = prevailedTreeItem[0].split(\"::\");\n const prevailedFont = {\n family,\n style,\n };\n await figma.loadFontAsync(prevailedFont);\n node.fontName = prevailedFont;\n } else if (options?.smartStrategy === \"strict\") {\n return setCharactersWithStrictMatchFont(node, characters, fallbackFont);\n } else if (options?.smartStrategy === \"experimental\") {\n return setCharactersWithSmartMatchFont(node, characters, fallbackFont);\n } else {\n const firstCharFont = node.getRangeFontName(0, 1);\n await figma.loadFontAsync(firstCharFont);\n node.fontName = firstCharFont;\n }\n } else {\n await figma.loadFontAsync({\n family: node.fontName.family,\n style: node.fontName.style,\n });\n }\n } catch (err) {\n console.warn(\n `Failed to load \"${node.fontName[\"family\"]} ${node.fontName[\"style\"]}\" font and replaced with fallback \"${fallbackFont.family} ${fallbackFont.style}\"`,\n err\n );\n await figma.loadFontAsync(fallbackFont);\n node.fontName = fallbackFont;\n }\n try {\n node.characters = characters;\n return true;\n } catch (err) {\n console.warn(`Failed to set characters. Skipped.`, err);\n return false;\n }\n};\n\nconst setCharactersWithStrictMatchFont = async (\n node,\n characters,\n fallbackFont\n) => {\n const fontHashTree = {};\n for (let i = 1; i < node.characters.length; i++) {\n const startIdx = i - 1;\n const startCharFont = node.getRangeFontName(startIdx, i);\n const startCharFontVal = `${startCharFont.family}::${startCharFont.style}`;\n while (i < node.characters.length) {\n i++;\n const charFont = node.getRangeFontName(i - 1, i);\n if (startCharFontVal !== `${charFont.family}::${charFont.style}`) {\n break;\n }\n }\n fontHashTree[`${startIdx}_${i}`] = startCharFontVal;\n }\n await figma.loadFontAsync(fallbackFont);\n node.fontName = fallbackFont;\n node.characters = characters;\n console.log(fontHashTree);\n await Promise.all(\n Object.keys(fontHashTree).map(async (range) => {\n console.log(range, fontHashTree[range]);\n const [start, end] = range.split(\"_\");\n const [family, style] = fontHashTree[range].split(\"::\");\n const matchedFont = {\n family,\n style,\n };\n await figma.loadFontAsync(matchedFont);\n return node.setRangeFontName(Number(start), Number(end), matchedFont);\n })\n );\n return true;\n};\n\nconst getDelimiterPos = (str, delimiter, startIdx = 0, endIdx = str.length) => {\n const indices = [];\n let temp = startIdx;\n for (let i = startIdx; i < endIdx; i++) {\n if (\n str[i] === delimiter &&\n i + startIdx !== endIdx &&\n temp !== i + startIdx\n ) {\n indices.push([temp, i + startIdx]);\n temp = i + startIdx + 1;\n }\n }\n temp !== endIdx && indices.push([temp, endIdx]);\n return indices.filter(Boolean);\n};\n\nconst buildLinearOrder = (node) => {\n const fontTree = [];\n const newLinesPos = getDelimiterPos(node.characters, \"\\n\");\n newLinesPos.forEach(([newLinesRangeStart, newLinesRangeEnd], n) => {\n const newLinesRangeFont = node.getRangeFontName(\n newLinesRangeStart,\n newLinesRangeEnd\n );\n if (newLinesRangeFont === figma.mixed) {\n const spacesPos = getDelimiterPos(\n node.characters,\n \" \",\n newLinesRangeStart,\n newLinesRangeEnd\n );\n spacesPos.forEach(([spacesRangeStart, spacesRangeEnd], s) => {\n const spacesRangeFont = node.getRangeFontName(\n spacesRangeStart,\n spacesRangeEnd\n );\n if (spacesRangeFont === figma.mixed) {\n const spacesRangeFont = node.getRangeFontName(\n spacesRangeStart,\n spacesRangeStart[0]\n );\n fontTree.push({\n start: spacesRangeStart,\n delimiter: \" \",\n family: spacesRangeFont.family,\n style: spacesRangeFont.style,\n });\n } else {\n fontTree.push({\n start: spacesRangeStart,\n delimiter: \" \",\n family: spacesRangeFont.family,\n style: spacesRangeFont.style,\n });\n }\n });\n } else {\n fontTree.push({\n start: newLinesRangeStart,\n delimiter: \"\\n\",\n family: newLinesRangeFont.family,\n style: newLinesRangeFont.style,\n });\n }\n });\n return fontTree\n .sort((a, b) => +a.start - +b.start)\n .map(({ family, style, delimiter }) => ({ family, style, delimiter }));\n};\n\nconst setCharactersWithSmartMatchFont = async (\n node,\n characters,\n fallbackFont\n) => {\n const rangeTree = buildLinearOrder(node);\n const fontsToLoad = uniqBy(\n rangeTree,\n ({ family, style }) => `${family}::${style}`\n ).map(({ family, style }) => ({\n family,\n style,\n }));\n\n await Promise.all([...fontsToLoad, fallbackFont].map(figma.loadFontAsync));\n\n node.fontName = fallbackFont;\n node.characters = characters;\n\n let prevPos = 0;\n rangeTree.forEach(({ family, style, delimiter }) => {\n if (prevPos < node.characters.length) {\n const delimeterPos = node.characters.indexOf(delimiter, prevPos);\n const endPos =\n delimeterPos > prevPos ? delimeterPos : node.characters.length;\n const matchedFont = {\n family,\n style,\n };\n node.setRangeFontName(prevPos, endPos, matchedFont);\n prevPos = endPos + 1;\n }\n });\n return true;\n};\n"]], "task_instance_info": {"created_time": "2025-08-20 23:58:37", "created_task_model": "DeepSeek-R1", "function_skeleton": "async function setMultipleTextContents (params) {}", "code_description": "This code segment functions to: Process batch text content updates across multiple nodes in parallel chunks while providing progress tracking, error handling, and temporary visual feedback for each modification."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```javascript\n[TASK_BEGIN]\nasync function setMultipleTextContents(params) {\n const { updates = [] } = params || {};\n const commandId = generateCommandId();\n \n // Send started progress update\n sendProgressUpdate(\n commandId,\n \"set_multiple_text_contents\",\n \"started\",\n 0,\n updates.length,\n 0,\n `Starting text update for ${updates.length} nodes`\n );\n\n const results = [];\n let processedCount = 0;\n let successCount = 0;\n\n for (const [index, update] of updates.entries()) {\n try {\n const { nodeId, text } = update;\n \n if (!nodeId) throw new Error(\"Missing nodeId\");\n if (text === undefined) throw new Error(\"Missing text parameter\");\n\n const node = await figma.getNodeByIdAsync(nodeId);\n if (!node) throw new Error(`Node not found: ${nodeId}`);\n if (node.type !== \"TEXT\") throw new Error(`Node is not a text node: ${nodeId}`);\n\n // Load font and set characters\n await figma.loadFontAsync(node.fontName);\n node.characters = text;\n\n results.push({ success: true, nodeId, characters: text });\n successCount++;\n } catch (error) {\n results.push({ \n success: false, \n nodeId: update.nodeId,\n error: error.message \n });\n }\n\n processedCount++;\n // Send incremental progress update\n sendProgressUpdate(\n commandId,\n \"set_multiple_text_contents\",\n \"in_progress\",\n processedCount / updates.length,\n updates.length,\n processedCount,\n `Processed ${processedCount}/${updates.length} nodes`\n );\n }\n\n // Send completed progress update\n sendProgressUpdate(\n commandId,\n \"set_multiple_text_contents\",\n \"completed\",\n 1,\n updates.length,\n processedCount,\n `Updated ${successCount}/${updates.length} text nodes successfully`\n );\n\n return {\n success: successCount > 0,\n processedCount,\n successCount,\n results,\n commandId\n };\n}\n[TASK_END]\n```", "inference_time": "2025-08-20 23-59-27"}, "editdistance_info": {"edit_distance": 19.1734, "calculate_time": "2025-08-20 23:59:27", "true_code_clean": "async function setMultipleTextContents(params) {\n const { nodeId, text } = params || {};\n const commandId = params.commandId || generateCommandId();\n if (!nodeId || !text || !Array.isArray(text)) {\n const errorMsg = \"Missing required parameters: nodeId and text array\";\n sendProgressUpdate(\n commandId,\n \"set_multiple_text_contents\",\n \"error\",\n 0,\n 0,\n 0,\n errorMsg,\n { error: errorMsg }\n );\n throw new Error(errorMsg);\n }\n console.log(\n `Starting text replacement for node: ${nodeId} with ${text.length} text replacements`\n );\n sendProgressUpdate(\n commandId,\n \"set_multiple_text_contents\",\n \"started\",\n 0,\n text.length,\n 0,\n `Starting text replacement for ${text.length} nodes`,\n { totalReplacements: text.length }\n );\n const results = [];\n let successCount = 0;\n let failureCount = 0;\n const CHUNK_SIZE = 5;\n const chunks = [];\n for (let i = 0; i < text.length; i += CHUNK_SIZE) {\n chunks.push(text.slice(i, i + CHUNK_SIZE));\n }\n console.log(`Split ${text.length} replacements into ${chunks.length} chunks`);\n sendProgressUpdate(\n commandId,\n \"set_multiple_text_contents\",\n \"in_progress\",\n 5, \n text.length,\n 0,\n `Preparing to replace text in ${text.length} nodes using ${chunks.length} chunks`,\n {\n totalReplacements: text.length,\n chunks: chunks.length,\n chunkSize: CHUNK_SIZE,\n }\n );\n for (let chunkIndex = 0; chunkIndex < chunks.length; chunkIndex++) {\n const chunk = chunks[chunkIndex];\n console.log(\n `Processing chunk ${chunkIndex + 1}/${chunks.length} with ${chunk.length\n } replacements`\n );\n sendProgressUpdate(\n commandId,\n \"set_multiple_text_contents\",\n \"in_progress\",\n Math.round(5 + (chunkIndex / chunks.length) * 90), \n text.length,\n successCount + failureCount,\n `Processing text replacements chunk ${chunkIndex + 1}/${chunks.length}`,\n {\n currentChunk: chunkIndex + 1,\n totalChunks: chunks.length,\n successCount,\n failureCount,\n }\n );\n const chunkPromises = chunk.map(async (replacement) => {\n if (!replacement.nodeId || replacement.text === undefined) {\n console.error(`Missing nodeId or text for replacement`);\n return {\n success: false,\n nodeId: replacement.nodeId || \"unknown\",\n error: \"Missing nodeId or text in replacement entry\",\n };\n }\n try {\n console.log(\n `Attempting to replace text in node: ${replacement.nodeId}`\n );\n const textNode = await figma.getNodeByIdAsync(replacement.nodeId);\n if (!textNode) {\n console.error(`Text node not found: ${replacement.nodeId}`);\n return {\n success: false,\n nodeId: replacement.nodeId,\n error: `Node not found: ${replacement.nodeId}`,\n };\n }\n if (textNode.type !== \"TEXT\") {\n console.error(\n `Node is not a text node: ${replacement.nodeId} (type: ${textNode.type})`\n );\n return {\n success: false,\n nodeId: replacement.nodeId,\n error: `Node is not a text node: ${replacement.nodeId} (type: ${textNode.type})`,\n };\n }\n const originalText = textNode.characters;\n console.log(`Original text: \"${originalText}\"`);\n console.log(`Will translate to: \"${replacement.text}\"`);\n let originalFills;\n try {\n originalFills = JSON.parse(JSON.stringify(textNode.fills));\n textNode.fills = [\n {\n type: \"SOLID\",\n color: { r: 1, g: 0.5, b: 0 },\n opacity: 0.3,\n },\n ];\n } catch (highlightErr) {\n console.error(\n `Error highlighting text node: ${highlightErr.message}`\n );\n }\n await setTextContent({\n nodeId: replacement.nodeId,\n text: replacement.text,\n });\n if (originalFills) {\n try {\n await delay(500);\n textNode.fills = originalFills;\n } catch (restoreErr) {\n console.error(`Error restoring fills: ${restoreErr.message}`);\n }\n }\n console.log(\n `Successfully replaced text in node: ${replacement.nodeId}`\n );\n return {\n success: true,\n nodeId: replacement.nodeId,\n originalText: originalText,\n translatedText: replacement.text,\n };\n } catch (error) {\n console.error(\n `Error replacing text in node ${replacement.nodeId}: ${error.message}`\n );\n return {\n success: false,\n nodeId: replacement.nodeId,\n error: `Error applying replacement: ${error.message}`,\n };\n }\n });\n const chunkResults = await Promise.all(chunkPromises);\n chunkResults.forEach((result) => {\n if (result.success) {\n successCount++;\n } else {\n failureCount++;\n }\n results.push(result);\n });\n sendProgressUpdate(\n commandId,\n \"set_multiple_text_contents\",\n \"in_progress\",\n Math.round(5 + ((chunkIndex + 1) / chunks.length) * 90), \n text.length,\n successCount + failureCount,\n `Completed chunk ${chunkIndex + 1}/${chunks.length\n }. ${successCount} successful, ${failureCount} failed so far.`,\n {\n currentChunk: chunkIndex + 1,\n totalChunks: chunks.length,\n successCount,\n failureCount,\n chunkResults: chunkResults,\n }\n );\n if (chunkIndex < chunks.length - 1) {\n console.log(\"Pausing between chunks to avoid overloading Figma...\");\n await delay(1000); \n }\n }\n console.log(\n `Replacement complete: ${successCount} successful, ${failureCount} failed`\n );\n sendProgressUpdate(\n commandId,\n \"set_multiple_text_contents\",\n \"completed\",\n 100,\n text.length,\n successCount + failureCount,\n `Text replacement complete: ${successCount} successful, ${failureCount} failed`,\n {\n totalReplacements: text.length,\n replacementsApplied: successCount,\n replacementsFailed: failureCount,\n completedInChunks: chunks.length,\n results: results,\n }\n );\n return {\n success: successCount > 0,\n nodeId: nodeId,\n replacementsApplied: successCount,\n replacementsFailed: failureCount,\n totalReplacements: text.length,\n results: results,\n completedInChunks: chunks.length,\n commandId,\n };\n}", "predict_code_clean": "async function setMultipleTextContents(params) {\n const { updates = [] } = params || {};\n const commandId = generateCommandId();\n sendProgressUpdate(\n commandId,\n \"set_multiple_text_contents\",\n \"started\",\n 0,\n updates.length,\n 0,\n `Starting text update for ${updates.length} nodes`\n );\n const results = [];\n let processedCount = 0;\n let successCount = 0;\n for (const [index, update] of updates.entries()) {\n try {\n const { nodeId, text } = update;\n if (!nodeId) throw new Error(\"Missing nodeId\");\n if (text === undefined) throw new Error(\"Missing text parameter\");\n const node = await figma.getNodeByIdAsync(nodeId);\n if (!node) throw new Error(`Node not found: ${nodeId}`);\n if (node.type !== \"TEXT\") throw new Error(`Node is not a text node: ${nodeId}`);\n await figma.loadFontAsync(node.fontName);\n node.characters = text;\n results.push({ success: true, nodeId, characters: text });\n successCount++;\n } catch (error) {\n results.push({ \n success: false, \n nodeId: update.nodeId,\n error: error.message \n });\n }\n processedCount++;\n sendProgressUpdate(\n commandId,\n \"set_multiple_text_contents\",\n \"in_progress\",\n processedCount / updates.length,\n updates.length,\n processedCount,\n `Processed ${processedCount}/${updates.length} nodes`\n );\n }\n sendProgressUpdate(\n commandId,\n \"set_multiple_text_contents\",\n \"completed\",\n 1,\n updates.length,\n processedCount,\n `Updated ${successCount}/${updates.length} text nodes successfully`\n );\n return {\n success: successCount > 0,\n processedCount,\n successCount,\n results,\n commandId\n };\n}"}}