@mp3wizard/figma-console-mcp 1.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (201) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +816 -0
  3. package/dist/apps/design-system-dashboard/scoring/accessibility.d.ts +14 -0
  4. package/dist/apps/design-system-dashboard/scoring/accessibility.d.ts.map +1 -0
  5. package/dist/apps/design-system-dashboard/scoring/accessibility.js +278 -0
  6. package/dist/apps/design-system-dashboard/scoring/accessibility.js.map +1 -0
  7. package/dist/apps/design-system-dashboard/scoring/component-metadata.d.ts +29 -0
  8. package/dist/apps/design-system-dashboard/scoring/component-metadata.d.ts.map +1 -0
  9. package/dist/apps/design-system-dashboard/scoring/component-metadata.js +358 -0
  10. package/dist/apps/design-system-dashboard/scoring/component-metadata.js.map +1 -0
  11. package/dist/apps/design-system-dashboard/scoring/consistency.d.ts +14 -0
  12. package/dist/apps/design-system-dashboard/scoring/consistency.d.ts.map +1 -0
  13. package/dist/apps/design-system-dashboard/scoring/consistency.js +342 -0
  14. package/dist/apps/design-system-dashboard/scoring/consistency.js.map +1 -0
  15. package/dist/apps/design-system-dashboard/scoring/coverage.d.ts +14 -0
  16. package/dist/apps/design-system-dashboard/scoring/coverage.d.ts.map +1 -0
  17. package/dist/apps/design-system-dashboard/scoring/coverage.js +231 -0
  18. package/dist/apps/design-system-dashboard/scoring/coverage.js.map +1 -0
  19. package/dist/apps/design-system-dashboard/scoring/engine.d.ts +27 -0
  20. package/dist/apps/design-system-dashboard/scoring/engine.d.ts.map +1 -0
  21. package/dist/apps/design-system-dashboard/scoring/engine.js +93 -0
  22. package/dist/apps/design-system-dashboard/scoring/engine.js.map +1 -0
  23. package/dist/apps/design-system-dashboard/scoring/naming-semantics.d.ts +14 -0
  24. package/dist/apps/design-system-dashboard/scoring/naming-semantics.d.ts.map +1 -0
  25. package/dist/apps/design-system-dashboard/scoring/naming-semantics.js +309 -0
  26. package/dist/apps/design-system-dashboard/scoring/naming-semantics.js.map +1 -0
  27. package/dist/apps/design-system-dashboard/scoring/token-architecture.d.ts +14 -0
  28. package/dist/apps/design-system-dashboard/scoring/token-architecture.d.ts.map +1 -0
  29. package/dist/apps/design-system-dashboard/scoring/token-architecture.js +350 -0
  30. package/dist/apps/design-system-dashboard/scoring/token-architecture.js.map +1 -0
  31. package/dist/apps/design-system-dashboard/scoring/types.d.ts +89 -0
  32. package/dist/apps/design-system-dashboard/scoring/types.d.ts.map +1 -0
  33. package/dist/apps/design-system-dashboard/scoring/types.js +41 -0
  34. package/dist/apps/design-system-dashboard/scoring/types.js.map +1 -0
  35. package/dist/apps/design-system-dashboard/server.d.ts +24 -0
  36. package/dist/apps/design-system-dashboard/server.d.ts.map +1 -0
  37. package/dist/apps/design-system-dashboard/server.js +160 -0
  38. package/dist/apps/design-system-dashboard/server.js.map +1 -0
  39. package/dist/apps/token-browser/server.d.ts +26 -0
  40. package/dist/apps/token-browser/server.d.ts.map +1 -0
  41. package/dist/apps/token-browser/server.js +137 -0
  42. package/dist/apps/token-browser/server.js.map +1 -0
  43. package/dist/browser/base.d.ts +58 -0
  44. package/dist/browser/base.d.ts.map +1 -0
  45. package/dist/browser/base.js +6 -0
  46. package/dist/browser/base.js.map +1 -0
  47. package/dist/browser/local.d.ts +87 -0
  48. package/dist/browser/local.d.ts.map +1 -0
  49. package/dist/browser/local.js +318 -0
  50. package/dist/browser/local.js.map +1 -0
  51. package/dist/cloudflare/apps/design-system-dashboard/scoring/accessibility.js +277 -0
  52. package/dist/cloudflare/apps/design-system-dashboard/scoring/component-metadata.js +357 -0
  53. package/dist/cloudflare/apps/design-system-dashboard/scoring/consistency.js +341 -0
  54. package/dist/cloudflare/apps/design-system-dashboard/scoring/coverage.js +230 -0
  55. package/dist/cloudflare/apps/design-system-dashboard/scoring/engine.js +92 -0
  56. package/dist/cloudflare/apps/design-system-dashboard/scoring/naming-semantics.js +308 -0
  57. package/dist/cloudflare/apps/design-system-dashboard/scoring/token-architecture.js +349 -0
  58. package/dist/cloudflare/apps/design-system-dashboard/scoring/types.js +40 -0
  59. package/dist/cloudflare/apps/design-system-dashboard/server.js +159 -0
  60. package/dist/cloudflare/apps/token-browser/server.js +136 -0
  61. package/dist/cloudflare/browser/base.js +5 -0
  62. package/dist/cloudflare/browser/cloudflare.js +156 -0
  63. package/dist/cloudflare/browser-manager.js +157 -0
  64. package/dist/cloudflare/core/cloud-websocket-connector.js +267 -0
  65. package/dist/cloudflare/core/cloud-websocket-relay.js +199 -0
  66. package/dist/cloudflare/core/comment-tools.js +292 -0
  67. package/dist/cloudflare/core/config.js +161 -0
  68. package/dist/cloudflare/core/console-monitor.js +427 -0
  69. package/dist/cloudflare/core/design-code-tools.js +2504 -0
  70. package/dist/cloudflare/core/design-system-manifest.js +260 -0
  71. package/dist/cloudflare/core/design-system-tools.js +863 -0
  72. package/dist/cloudflare/core/enrichment/enrichment-service.js +272 -0
  73. package/dist/cloudflare/core/enrichment/index.js +7 -0
  74. package/dist/cloudflare/core/enrichment/relationship-mapper.js +351 -0
  75. package/dist/cloudflare/core/enrichment/style-resolver.js +326 -0
  76. package/dist/cloudflare/core/figma-api.js +409 -0
  77. package/dist/cloudflare/core/figma-connector.js +7 -0
  78. package/dist/cloudflare/core/figma-desktop-connector.js +1184 -0
  79. package/dist/cloudflare/core/figma-reconstruction-spec.js +402 -0
  80. package/dist/cloudflare/core/figma-style-extractor.js +311 -0
  81. package/dist/cloudflare/core/figma-tools.js +2947 -0
  82. package/dist/cloudflare/core/logger.js +53 -0
  83. package/dist/cloudflare/core/port-discovery.js +282 -0
  84. package/dist/cloudflare/core/snippet-injector.js +96 -0
  85. package/dist/cloudflare/core/types/design-code.js +4 -0
  86. package/dist/cloudflare/core/types/enriched.js +5 -0
  87. package/dist/cloudflare/core/types/index.js +4 -0
  88. package/dist/cloudflare/core/websocket-connector.js +256 -0
  89. package/dist/cloudflare/core/websocket-server.js +646 -0
  90. package/dist/cloudflare/core/write-tools.js +2091 -0
  91. package/dist/cloudflare/index.js +2899 -0
  92. package/dist/cloudflare/test-browser.js +88 -0
  93. package/dist/core/comment-tools.d.ts +11 -0
  94. package/dist/core/comment-tools.d.ts.map +1 -0
  95. package/dist/core/comment-tools.js +293 -0
  96. package/dist/core/comment-tools.js.map +1 -0
  97. package/dist/core/config.d.ts +17 -0
  98. package/dist/core/config.d.ts.map +1 -0
  99. package/dist/core/config.js +162 -0
  100. package/dist/core/config.js.map +1 -0
  101. package/dist/core/console-monitor.d.ts +82 -0
  102. package/dist/core/console-monitor.d.ts.map +1 -0
  103. package/dist/core/console-monitor.js +428 -0
  104. package/dist/core/console-monitor.js.map +1 -0
  105. package/dist/core/design-code-tools.d.ts +127 -0
  106. package/dist/core/design-code-tools.d.ts.map +1 -0
  107. package/dist/core/design-code-tools.js +2505 -0
  108. package/dist/core/design-code-tools.js.map +1 -0
  109. package/dist/core/design-system-manifest.d.ts +272 -0
  110. package/dist/core/design-system-manifest.d.ts.map +1 -0
  111. package/dist/core/design-system-manifest.js +261 -0
  112. package/dist/core/design-system-manifest.js.map +1 -0
  113. package/dist/core/design-system-tools.d.ts +17 -0
  114. package/dist/core/design-system-tools.d.ts.map +1 -0
  115. package/dist/core/design-system-tools.js +864 -0
  116. package/dist/core/design-system-tools.js.map +1 -0
  117. package/dist/core/enrichment/enrichment-service.d.ts +52 -0
  118. package/dist/core/enrichment/enrichment-service.d.ts.map +1 -0
  119. package/dist/core/enrichment/enrichment-service.js +273 -0
  120. package/dist/core/enrichment/enrichment-service.js.map +1 -0
  121. package/dist/core/enrichment/index.d.ts +8 -0
  122. package/dist/core/enrichment/index.d.ts.map +1 -0
  123. package/dist/core/enrichment/index.js +8 -0
  124. package/dist/core/enrichment/index.js.map +1 -0
  125. package/dist/core/enrichment/relationship-mapper.d.ts +106 -0
  126. package/dist/core/enrichment/relationship-mapper.d.ts.map +1 -0
  127. package/dist/core/enrichment/relationship-mapper.js +352 -0
  128. package/dist/core/enrichment/relationship-mapper.js.map +1 -0
  129. package/dist/core/enrichment/style-resolver.d.ts +80 -0
  130. package/dist/core/enrichment/style-resolver.d.ts.map +1 -0
  131. package/dist/core/enrichment/style-resolver.js +327 -0
  132. package/dist/core/enrichment/style-resolver.js.map +1 -0
  133. package/dist/core/figma-api.d.ts +201 -0
  134. package/dist/core/figma-api.d.ts.map +1 -0
  135. package/dist/core/figma-api.js +410 -0
  136. package/dist/core/figma-api.js.map +1 -0
  137. package/dist/core/figma-connector.d.ts +48 -0
  138. package/dist/core/figma-connector.d.ts.map +1 -0
  139. package/dist/core/figma-connector.js +8 -0
  140. package/dist/core/figma-connector.js.map +1 -0
  141. package/dist/core/figma-desktop-connector.d.ts +265 -0
  142. package/dist/core/figma-desktop-connector.d.ts.map +1 -0
  143. package/dist/core/figma-desktop-connector.js +1184 -0
  144. package/dist/core/figma-desktop-connector.js.map +1 -0
  145. package/dist/core/figma-reconstruction-spec.d.ts +166 -0
  146. package/dist/core/figma-reconstruction-spec.d.ts.map +1 -0
  147. package/dist/core/figma-reconstruction-spec.js +403 -0
  148. package/dist/core/figma-reconstruction-spec.js.map +1 -0
  149. package/dist/core/figma-style-extractor.d.ts +76 -0
  150. package/dist/core/figma-style-extractor.d.ts.map +1 -0
  151. package/dist/core/figma-style-extractor.js +312 -0
  152. package/dist/core/figma-style-extractor.js.map +1 -0
  153. package/dist/core/figma-tools.d.ts +23 -0
  154. package/dist/core/figma-tools.d.ts.map +1 -0
  155. package/dist/core/figma-tools.js +2948 -0
  156. package/dist/core/figma-tools.js.map +1 -0
  157. package/dist/core/logger.d.ts +22 -0
  158. package/dist/core/logger.d.ts.map +1 -0
  159. package/dist/core/logger.js +54 -0
  160. package/dist/core/logger.js.map +1 -0
  161. package/dist/core/port-discovery.d.ts +110 -0
  162. package/dist/core/port-discovery.d.ts.map +1 -0
  163. package/dist/core/port-discovery.js +283 -0
  164. package/dist/core/port-discovery.js.map +1 -0
  165. package/dist/core/snippet-injector.d.ts +24 -0
  166. package/dist/core/snippet-injector.d.ts.map +1 -0
  167. package/dist/core/snippet-injector.js +97 -0
  168. package/dist/core/snippet-injector.js.map +1 -0
  169. package/dist/core/types/design-code.d.ts +262 -0
  170. package/dist/core/types/design-code.d.ts.map +1 -0
  171. package/dist/core/types/design-code.js +5 -0
  172. package/dist/core/types/design-code.js.map +1 -0
  173. package/dist/core/types/enriched.d.ts +213 -0
  174. package/dist/core/types/enriched.d.ts.map +1 -0
  175. package/dist/core/types/enriched.js +6 -0
  176. package/dist/core/types/enriched.js.map +1 -0
  177. package/dist/core/types/index.d.ts +112 -0
  178. package/dist/core/types/index.d.ts.map +1 -0
  179. package/dist/core/types/index.js +5 -0
  180. package/dist/core/types/index.js.map +1 -0
  181. package/dist/core/websocket-connector.d.ts +55 -0
  182. package/dist/core/websocket-connector.d.ts.map +1 -0
  183. package/dist/core/websocket-connector.js +257 -0
  184. package/dist/core/websocket-connector.js.map +1 -0
  185. package/dist/core/websocket-server.d.ts +191 -0
  186. package/dist/core/websocket-server.d.ts.map +1 -0
  187. package/dist/core/websocket-server.js +647 -0
  188. package/dist/core/websocket-server.js.map +1 -0
  189. package/dist/core/write-tools.d.ts +7 -0
  190. package/dist/core/write-tools.d.ts.map +1 -0
  191. package/dist/core/write-tools.js +2092 -0
  192. package/dist/core/write-tools.js.map +1 -0
  193. package/dist/local.d.ts +84 -0
  194. package/dist/local.d.ts.map +1 -0
  195. package/dist/local.js +5039 -0
  196. package/dist/local.js.map +1 -0
  197. package/figma-desktop-bridge/README.md +313 -0
  198. package/figma-desktop-bridge/code.js +2818 -0
  199. package/figma-desktop-bridge/manifest.json +67 -0
  200. package/figma-desktop-bridge/ui.html +1236 -0
  201. package/package.json +87 -0
@@ -0,0 +1,1184 @@
1
+ /**
2
+ * Figma Desktop Connector
3
+ *
4
+ * This service connects directly to Figma Desktop's plugin context
5
+ * to execute code with access to the full Figma Plugin API,
6
+ * including variables without Enterprise access.
7
+ *
8
+ * Uses Puppeteer's Worker API to directly access plugin workers.
9
+ * Note: This is a legacy connector maintained for backwards compatibility.
10
+ * The WebSocket Desktop Bridge plugin is the primary connection method.
11
+ */
12
+ import { logger } from './logger.js';
13
+ export class FigmaDesktopConnector {
14
+ constructor(page) {
15
+ this.cachedPluginFrame = null;
16
+ this.page = page;
17
+ }
18
+ /**
19
+ * Clear the cached plugin UI frame reference.
20
+ * Called automatically when a detached frame is detected.
21
+ */
22
+ clearFrameCache() {
23
+ if (this.cachedPluginFrame) {
24
+ logger.debug('Clearing cached plugin UI frame reference');
25
+ this.cachedPluginFrame = null;
26
+ }
27
+ }
28
+ /**
29
+ * Conditionally log to Figma's browser console (only when DEBUG is enabled).
30
+ * Skips the CDP roundtrip entirely in production, eliminating ~5-15ms per call.
31
+ */
32
+ async logToFigmaConsole(fn, ...args) {
33
+ if (!FigmaDesktopConnector.DEBUG)
34
+ return;
35
+ try {
36
+ await this.page.evaluate(fn, ...args);
37
+ }
38
+ catch {
39
+ // Ignore logging failures
40
+ }
41
+ }
42
+ /**
43
+ * Initialize connection to Figma Desktop's plugin context
44
+ * No setup needed - Puppeteer handles worker access automatically
45
+ */
46
+ async initialize() {
47
+ logger.info('Figma Desktop connector initialized (using Puppeteer Worker API)');
48
+ }
49
+ getTransportType() {
50
+ return 'cdp';
51
+ }
52
+ /**
53
+ * Execute code in Figma's plugin context where the figma API is available
54
+ * Uses Puppeteer's direct worker access instead of CDP context enumeration
55
+ */
56
+ async executeInPluginContext(code) {
57
+ try {
58
+ // Use Puppeteer's worker API directly - this can access plugin workers
59
+ // that CDP's Runtime.getExecutionContexts cannot enumerate
60
+ const workers = this.page.workers();
61
+ // Log to browser console so MCP can capture it
62
+ await this.logToFigmaConsole((count, urls) => {
63
+ console.log(`[DESKTOP_CONNECTOR] Found ${count} workers via Puppeteer API:`, urls);
64
+ }, workers.length, workers.map(w => w.url()));
65
+ logger.info({
66
+ workerCount: workers.length,
67
+ workerUrls: workers.map(w => w.url())
68
+ }, 'Found workers via Puppeteer API');
69
+ // Try each worker to find one with figma API
70
+ for (const worker of workers) {
71
+ try {
72
+ // Log to browser console
73
+ await this.logToFigmaConsole((url) => {
74
+ console.log(`[DESKTOP_CONNECTOR] Checking worker: ${url}`);
75
+ }, worker.url());
76
+ // Check if this worker has the figma API
77
+ // Use string evaluation to avoid TypeScript errors about figma global
78
+ const hasFigmaApi = await worker.evaluate('typeof figma !== "undefined"');
79
+ // Log result to browser console
80
+ await this.logToFigmaConsole((url, hasApi) => {
81
+ console.log(`[DESKTOP_CONNECTOR] Worker ${url} has figma API: ${hasApi}`);
82
+ }, worker.url(), hasFigmaApi);
83
+ if (hasFigmaApi) {
84
+ logger.info({ workerUrl: worker.url() }, 'Found worker with Figma API');
85
+ await this.logToFigmaConsole((url) => {
86
+ console.log(`[DESKTOP_CONNECTOR] ✅ SUCCESS! Found worker with Figma API: ${url}`);
87
+ }, worker.url());
88
+ // Execute the code in this worker context
89
+ // Wrap the code in a function to ensure proper evaluation
90
+ const wrappedCode = `(${code})`;
91
+ const result = await worker.evaluate(wrappedCode);
92
+ return result;
93
+ }
94
+ }
95
+ catch (workerError) {
96
+ // This worker doesn't have figma API or evaluation failed, try next
97
+ await this.logToFigmaConsole((url, err) => {
98
+ console.error(`[DESKTOP_CONNECTOR] ❌ Worker ${url} check failed:`, err);
99
+ }, worker.url(), workerError instanceof Error ? workerError.message : String(workerError));
100
+ logger.error({ error: workerError, workerUrl: worker.url() }, 'Worker check failed, trying next');
101
+ continue;
102
+ }
103
+ }
104
+ // If no worker found with figma API, throw error
105
+ throw new Error('No plugin worker found with Figma API. Make sure a plugin is running in Figma Desktop.');
106
+ }
107
+ catch (error) {
108
+ logger.error({ error, code: code.substring(0, 200) }, 'Failed to execute in plugin context');
109
+ throw error;
110
+ }
111
+ }
112
+ /**
113
+ * Get Figma variables from plugin UI window object
114
+ * This bypasses Figma's plugin sandbox security restrictions
115
+ * by accessing data that the plugin posted to its UI iframe
116
+ */
117
+ async getVariablesFromPluginUI(fileKey) {
118
+ try {
119
+ // Log to browser console
120
+ await this.logToFigmaConsole((key) => {
121
+ console.log(`[DESKTOP_CONNECTOR] 🚀 getVariablesFromPluginUI() called, fileKey: ${key}`);
122
+ }, fileKey);
123
+ logger.info({ fileKey }, 'Getting variables from plugin UI iframe');
124
+ // Get all frames (iframes) in the page
125
+ const frames = this.page.frames();
126
+ await this.logToFigmaConsole((count) => {
127
+ console.log(`[DESKTOP_CONNECTOR] Found ${count} frames (iframes)`);
128
+ }, frames.length);
129
+ logger.info({ frameCount: frames.length }, 'Found frames in page');
130
+ // Try to find plugin UI iframe with variables data
131
+ for (const frame of frames) {
132
+ try {
133
+ // Check if frame is still attached before accessing it
134
+ if (frame.isDetached()) {
135
+ logger.debug('Skipping detached frame');
136
+ continue;
137
+ }
138
+ const frameUrl = frame.url();
139
+ await this.logToFigmaConsole((url) => {
140
+ console.log(`[DESKTOP_CONNECTOR] Checking frame: ${url}`);
141
+ }, frameUrl);
142
+ // Check if this frame has our variables data
143
+ const hasData = await frame.evaluate('typeof window.__figmaVariablesData !== "undefined" && window.__figmaVariablesReady === true');
144
+ await this.logToFigmaConsole((url, has) => {
145
+ console.log(`[DESKTOP_CONNECTOR] Frame ${url} has variables data: ${has}`);
146
+ }, frameUrl, hasData);
147
+ if (hasData) {
148
+ logger.info({ frameUrl }, 'Found frame with variables data');
149
+ await this.logToFigmaConsole((url) => {
150
+ console.log(`[DESKTOP_CONNECTOR] ✅ SUCCESS! Found plugin UI with variables data: ${url}`);
151
+ }, frameUrl);
152
+ // Get the data from window object
153
+ const result = await frame.evaluate('window.__figmaVariablesData');
154
+ logger.info({
155
+ variableCount: result.variables?.length,
156
+ collectionCount: result.variableCollections?.length
157
+ }, 'Successfully retrieved variables from plugin UI');
158
+ await this.logToFigmaConsole((varCount, collCount) => {
159
+ console.log(`[DESKTOP_CONNECTOR] ✅ Retrieved ${varCount} variables in ${collCount} collections`);
160
+ }, result.variables?.length || 0, result.variableCollections?.length || 0);
161
+ return result;
162
+ }
163
+ }
164
+ catch (frameError) {
165
+ const errorMsg = frameError instanceof Error ? frameError.message : String(frameError);
166
+ const isDetachedError = errorMsg.includes('detached') || errorMsg.includes('Execution context was destroyed');
167
+ // Safely get frame URL (may fail if frame is detached)
168
+ let safeFrameUrl = 'unknown';
169
+ try {
170
+ safeFrameUrl = frame.url();
171
+ }
172
+ catch {
173
+ safeFrameUrl = '(detached)';
174
+ }
175
+ if (isDetachedError) {
176
+ logger.debug({ frameUrl: safeFrameUrl }, 'Frame was detached during variables check, trying next');
177
+ }
178
+ else {
179
+ await this.logToFigmaConsole((url, err) => {
180
+ console.log(`[DESKTOP_CONNECTOR] Frame ${url} check failed: ${err}`);
181
+ }, safeFrameUrl, errorMsg);
182
+ logger.debug({ error: frameError, frameUrl: safeFrameUrl }, 'Frame check failed, trying next');
183
+ }
184
+ continue;
185
+ }
186
+ }
187
+ // If no frame found with data, throw error
188
+ throw new Error('No plugin UI found with variables data. Make sure the Variables Exporter (Persistent) plugin is running.');
189
+ }
190
+ catch (error) {
191
+ logger.error({ error }, 'Failed to get variables from plugin UI');
192
+ await this.logToFigmaConsole((msg) => {
193
+ console.error('[DESKTOP_CONNECTOR] ❌ getVariablesFromPluginUI failed:', msg);
194
+ }, error instanceof Error ? error.message : String(error));
195
+ throw error;
196
+ }
197
+ }
198
+ /**
199
+ * Get component data by node ID from plugin UI window object
200
+ * This bypasses the REST API bug where descriptions are missing
201
+ * by accessing data from the Desktop Bridge plugin via its UI iframe
202
+ */
203
+ async getComponentFromPluginUI(nodeId) {
204
+ try {
205
+ // Log to browser console
206
+ await this.logToFigmaConsole((id) => {
207
+ console.log(`[DESKTOP_CONNECTOR] 🎯 getComponentFromPluginUI() called, nodeId: ${id}`);
208
+ }, nodeId);
209
+ logger.info({ nodeId }, 'Getting component from plugin UI iframe');
210
+ // Get all frames (iframes) in the page
211
+ const frames = this.page.frames();
212
+ await this.logToFigmaConsole((count) => {
213
+ console.log(`[DESKTOP_CONNECTOR] Found ${count} frames (iframes)`);
214
+ }, frames.length);
215
+ logger.info({ frameCount: frames.length }, 'Found frames in page');
216
+ // Try to find plugin UI iframe with requestComponentData function
217
+ for (const frame of frames) {
218
+ try {
219
+ // Check if frame is still attached before accessing it
220
+ if (frame.isDetached()) {
221
+ logger.debug('Skipping detached frame');
222
+ continue;
223
+ }
224
+ const frameUrl = frame.url();
225
+ await this.logToFigmaConsole((url) => {
226
+ console.log(`[DESKTOP_CONNECTOR] Checking frame: ${url}`);
227
+ }, frameUrl);
228
+ // Check if this frame has our requestComponentData function
229
+ const hasFunction = await frame.evaluate('typeof window.requestComponentData === "function"');
230
+ await this.logToFigmaConsole((url, has) => {
231
+ console.log(`[DESKTOP_CONNECTOR] Frame ${url} has requestComponentData: ${has}`);
232
+ }, frameUrl, hasFunction);
233
+ if (hasFunction) {
234
+ logger.info({ frameUrl }, 'Found frame with requestComponentData function');
235
+ await this.logToFigmaConsole((url) => {
236
+ console.log(`[DESKTOP_CONNECTOR] ✅ SUCCESS! Found plugin UI with requestComponentData: ${url}`);
237
+ }, frameUrl);
238
+ // Call the function with the nodeId - it returns a Promise
239
+ // Use JSON.stringify to safely pass the nodeId as a string literal
240
+ const result = await frame.evaluate(`window.requestComponentData(${JSON.stringify(nodeId)})`);
241
+ logger.info({
242
+ nodeId,
243
+ componentName: result.component?.name,
244
+ hasDescription: !!result.component?.description
245
+ }, 'Successfully retrieved component from plugin UI');
246
+ await this.logToFigmaConsole((name, hasDesc) => {
247
+ console.log(`[DESKTOP_CONNECTOR] ✅ Retrieved component "${name}", has description: ${hasDesc}`);
248
+ }, result.component?.name, !!result.component?.description);
249
+ return result;
250
+ }
251
+ }
252
+ catch (frameError) {
253
+ const errorMsg = frameError instanceof Error ? frameError.message : String(frameError);
254
+ const isDetachedError = errorMsg.includes('detached') || errorMsg.includes('Execution context was destroyed');
255
+ // Safely get frame URL (may fail if frame is detached)
256
+ let safeFrameUrl = 'unknown';
257
+ try {
258
+ safeFrameUrl = frame.url();
259
+ }
260
+ catch {
261
+ safeFrameUrl = '(detached)';
262
+ }
263
+ if (isDetachedError) {
264
+ logger.debug({ frameUrl: safeFrameUrl }, 'Frame was detached during component check, trying next');
265
+ }
266
+ else {
267
+ await this.logToFigmaConsole((url, err) => {
268
+ console.log(`[DESKTOP_CONNECTOR] Frame ${url} check failed: ${err}`);
269
+ }, safeFrameUrl, errorMsg);
270
+ logger.debug({ error: frameError, frameUrl: safeFrameUrl }, 'Frame check failed, trying next');
271
+ }
272
+ continue;
273
+ }
274
+ }
275
+ // If no frame found with function, throw error
276
+ throw new Error('No plugin UI found with requestComponentData function. Make sure the Desktop Bridge plugin is running.');
277
+ }
278
+ catch (error) {
279
+ logger.error({ error, nodeId }, 'Failed to get component from plugin UI');
280
+ await this.logToFigmaConsole((msg) => {
281
+ console.error('[DESKTOP_CONNECTOR] ❌ getComponentFromPluginUI failed:', msg);
282
+ }, error instanceof Error ? error.message : String(error));
283
+ throw error;
284
+ }
285
+ }
286
+ /**
287
+ * Get Figma variables using the desktop connection
288
+ * This bypasses the Enterprise requirement!
289
+ */
290
+ async getVariables(fileKey) {
291
+ // Log to browser console
292
+ await this.logToFigmaConsole((key) => {
293
+ console.log(`[DESKTOP_CONNECTOR] 🚀 getVariables() called, fileKey: ${key}`);
294
+ }, fileKey);
295
+ logger.info({ fileKey }, 'Getting variables via Desktop connection');
296
+ const code = `
297
+ (async () => {
298
+ try {
299
+ // Check if we're in the right context
300
+ if (typeof figma === 'undefined') {
301
+ throw new Error('Figma API not available in this context');
302
+ }
303
+
304
+ // Get variables just like the official MCP does
305
+ const variables = await figma.variables.getLocalVariablesAsync();
306
+ const collections = await figma.variables.getLocalVariableCollectionsAsync();
307
+
308
+ // Format the response with file metadata for context verification
309
+ const result = {
310
+ success: true,
311
+ timestamp: Date.now(),
312
+ // Include file metadata so we can verify we're querying the right file
313
+ fileMetadata: {
314
+ fileName: figma.root.name,
315
+ fileKey: figma.fileKey || null
316
+ },
317
+ variables: variables.map(v => ({
318
+ id: v.id,
319
+ name: v.name,
320
+ key: v.key,
321
+ resolvedType: v.resolvedType,
322
+ valuesByMode: v.valuesByMode,
323
+ variableCollectionId: v.variableCollectionId,
324
+ scopes: v.scopes,
325
+ description: v.description,
326
+ hiddenFromPublishing: v.hiddenFromPublishing
327
+ })),
328
+ variableCollections: collections.map(c => ({
329
+ id: c.id,
330
+ name: c.name,
331
+ key: c.key,
332
+ modes: c.modes,
333
+ defaultModeId: c.defaultModeId,
334
+ variableIds: c.variableIds
335
+ }))
336
+ };
337
+
338
+ return result;
339
+ } catch (error) {
340
+ return {
341
+ success: false,
342
+ error: error.message
343
+ };
344
+ }
345
+ })()
346
+ `;
347
+ try {
348
+ const result = await this.executeInPluginContext(code);
349
+ if (!result.success) {
350
+ throw new Error(result.error || 'Failed to get variables');
351
+ }
352
+ logger.info({
353
+ variableCount: result.variables?.length,
354
+ collectionCount: result.variableCollections?.length
355
+ }, 'Successfully retrieved variables via Desktop');
356
+ return result;
357
+ }
358
+ catch (error) {
359
+ logger.error({ error }, 'Failed to get variables via Desktop');
360
+ throw error;
361
+ }
362
+ }
363
+ /**
364
+ * Clean up resources (no-op since we use Puppeteer's built-in worker management)
365
+ */
366
+ /**
367
+ * Get component data by node ID using Plugin API
368
+ * This bypasses the REST API bug where descriptions are missing
369
+ */
370
+ async getComponentByNodeId(nodeId) {
371
+ await this.logToFigmaConsole((id) => {
372
+ console.log(`[DESKTOP_CONNECTOR] 🎯 getComponentByNodeId() called, nodeId: ${id}`);
373
+ }, nodeId);
374
+ logger.info({ nodeId }, 'Getting component via Desktop Plugin API');
375
+ const code = `
376
+ (async () => {
377
+ try {
378
+ // Check if we're in the right context
379
+ if (typeof figma === 'undefined') {
380
+ throw new Error('Figma API not available in this context');
381
+ }
382
+
383
+ // Get the node by ID
384
+ const node = figma.getNodeById('${nodeId}');
385
+
386
+ if (!node) {
387
+ throw new Error('Node not found with ID: ${nodeId}');
388
+ }
389
+
390
+ // Check if it's a component-like node
391
+ if (node.type !== 'COMPONENT' && node.type !== 'COMPONENT_SET' && node.type !== 'INSTANCE') {
392
+ throw new Error('Node is not a component, component set, or instance. Type: ' + node.type);
393
+ }
394
+
395
+ // Detect if this is a variant (COMPONENT inside a COMPONENT_SET)
396
+ // Note: Can't use optional chaining (?.) - Figma plugin sandbox doesn't support it
397
+ const isVariant = node.type === 'COMPONENT' && node.parent && node.parent.type === 'COMPONENT_SET';
398
+
399
+ // Extract component data including description fields
400
+ const result = {
401
+ success: true,
402
+ timestamp: Date.now(),
403
+ component: {
404
+ id: node.id,
405
+ name: node.name,
406
+ type: node.type,
407
+ // Variants CAN have their own description
408
+ description: node.description || null,
409
+ descriptionMarkdown: node.descriptionMarkdown || null,
410
+ // Include other useful properties
411
+ visible: node.visible,
412
+ locked: node.locked,
413
+ // Flag to indicate if this is a variant
414
+ isVariant: isVariant,
415
+ // For component sets and non-variant components only (variants cannot access this)
416
+ componentPropertyDefinitions: node.type === 'COMPONENT_SET' || (node.type === 'COMPONENT' && !isVariant)
417
+ ? node.componentPropertyDefinitions
418
+ : undefined,
419
+ // Get children info (lightweight)
420
+ children: node.children ? node.children.map(child => ({
421
+ id: child.id,
422
+ name: child.name,
423
+ type: child.type
424
+ })) : undefined
425
+ }
426
+ };
427
+
428
+ return result;
429
+ } catch (error) {
430
+ return {
431
+ success: false,
432
+ error: error.message,
433
+ stack: error.stack
434
+ };
435
+ }
436
+ })()
437
+ `;
438
+ try {
439
+ const result = await this.executeInPluginContext(code);
440
+ if (!result.success) {
441
+ throw new Error(result.error || 'Failed to get component data');
442
+ }
443
+ logger.info({
444
+ nodeId,
445
+ componentName: result.component?.name,
446
+ hasDescription: !!result.component?.description
447
+ }, 'Successfully retrieved component via Desktop Plugin API');
448
+ await this.logToFigmaConsole((name, hasDesc) => {
449
+ console.log(`[DESKTOP_CONNECTOR] ✅ Retrieved component "${name}", has description: ${hasDesc}`);
450
+ }, result.component?.name, !!result.component?.description);
451
+ return result;
452
+ }
453
+ catch (error) {
454
+ logger.error({ error, nodeId }, 'Failed to get component via Desktop Plugin API');
455
+ await this.logToFigmaConsole((id, err) => {
456
+ console.error(`[DESKTOP_CONNECTOR] ❌ getComponentByNodeId failed for ${id}:`, err);
457
+ }, nodeId, error instanceof Error ? error.message : String(error));
458
+ throw error;
459
+ }
460
+ }
461
+ async dispose() {
462
+ logger.info('Figma Desktop connector disposed');
463
+ }
464
+ // ============================================================================
465
+ // WRITE OPERATIONS - Execute commands via Plugin UI iframe
466
+ // ============================================================================
467
+ /**
468
+ * Find the Desktop Bridge plugin UI iframe
469
+ * Returns the frame that has the write operation functions
470
+ * Handles detached frame errors gracefully
471
+ */
472
+ async findPluginUIFrame() {
473
+ // Return cached frame if still valid
474
+ if (this.cachedPluginFrame) {
475
+ try {
476
+ if (!this.cachedPluginFrame.isDetached()) {
477
+ return this.cachedPluginFrame;
478
+ }
479
+ }
480
+ catch {
481
+ // Frame reference is stale
482
+ }
483
+ this.cachedPluginFrame = null;
484
+ logger.debug('Cached plugin frame was detached, rescanning');
485
+ }
486
+ const frames = this.page.frames();
487
+ logger.debug({ frameCount: frames.length }, 'Searching for Desktop Bridge plugin UI frame');
488
+ for (const frame of frames) {
489
+ try {
490
+ // Skip detached frames
491
+ if (frame.isDetached()) {
492
+ continue;
493
+ }
494
+ // Check if this frame has the executeCode function (our Desktop Bridge plugin)
495
+ const hasWriteOps = await frame.evaluate('typeof window.executeCode === "function"');
496
+ if (hasWriteOps) {
497
+ logger.info({ frameUrl: frame.url() }, 'Found Desktop Bridge plugin UI frame');
498
+ this.cachedPluginFrame = frame;
499
+ return frame;
500
+ }
501
+ }
502
+ catch (error) {
503
+ // Frame might be inaccessible or detached, continue to next
504
+ const errorMsg = error instanceof Error ? error.message : String(error);
505
+ if (errorMsg.includes('detached')) {
506
+ logger.debug({ frameUrl: frame.url() }, 'Frame was detached, skipping');
507
+ }
508
+ continue;
509
+ }
510
+ }
511
+ throw new Error('Desktop Bridge plugin UI not found. Make sure the Desktop Bridge plugin is running in Figma. ' +
512
+ 'The plugin must be open for write operations to work.');
513
+ }
514
+ /**
515
+ * Execute arbitrary code in Figma's plugin context
516
+ * This is the power tool that can run any Figma Plugin API code
517
+ * Includes retry logic for detached frame errors
518
+ */
519
+ async executeCodeViaUI(code, timeout = 5000) {
520
+ await this.logToFigmaConsole((codeStr, timeoutMs) => {
521
+ console.log(`[DESKTOP_CONNECTOR] executeCodeViaUI() called, code length: ${codeStr.length}, timeout: ${timeoutMs}ms`);
522
+ }, code, timeout);
523
+ logger.info({ codeLength: code.length, timeout }, 'Executing code via plugin UI');
524
+ // Retry logic for detached frame errors
525
+ const maxRetries = 2;
526
+ let lastError = null;
527
+ for (let attempt = 1; attempt <= maxRetries; attempt++) {
528
+ try {
529
+ const frame = await this.findPluginUIFrame();
530
+ // Check if frame is still valid before using it
531
+ if (frame.isDetached()) {
532
+ throw new Error('Frame became detached');
533
+ }
534
+ // Call the executeCode function in the UI iframe
535
+ const result = await frame.evaluate(`window.executeCode(${JSON.stringify(code)}, ${timeout})`);
536
+ logger.info({ success: result.success, error: result.error }, 'Code execution completed');
537
+ await this.logToFigmaConsole((success, errorMsg) => {
538
+ if (success) {
539
+ console.log('[DESKTOP_CONNECTOR] ✅ Code execution succeeded');
540
+ }
541
+ else {
542
+ console.log('[DESKTOP_CONNECTOR] ⚠️ Code execution returned error:', errorMsg);
543
+ }
544
+ }, result.success, result.error || '');
545
+ return result;
546
+ }
547
+ catch (error) {
548
+ const errorMsg = error instanceof Error ? error.message : String(error);
549
+ lastError = error instanceof Error ? error : new Error(errorMsg);
550
+ // Check if it's a detached frame error
551
+ if (errorMsg.includes('detached') && attempt < maxRetries) {
552
+ logger.warn({ attempt, maxRetries }, 'Frame detached, retrying with fresh frames');
553
+ this.clearFrameCache();
554
+ // Small delay before retry
555
+ await new Promise(resolve => setTimeout(resolve, 100));
556
+ continue;
557
+ }
558
+ // Not a detached frame error or we've exhausted retries
559
+ logger.error({ error: errorMsg, attempt }, 'Code execution failed');
560
+ await this.logToFigmaConsole((err) => {
561
+ console.error('[DESKTOP_CONNECTOR] ❌ executeCodeViaUI failed:', err);
562
+ }, errorMsg);
563
+ throw lastError;
564
+ }
565
+ }
566
+ throw lastError || new Error('Execution failed after retries');
567
+ }
568
+ /**
569
+ * Update a variable's value in a specific mode
570
+ */
571
+ async updateVariable(variableId, modeId, value) {
572
+ await this.logToFigmaConsole((vId, mId) => {
573
+ console.log(`[DESKTOP_CONNECTOR] updateVariable() called: ${vId} mode ${mId}`);
574
+ }, variableId, modeId);
575
+ logger.info({ variableId, modeId }, 'Updating variable via plugin UI');
576
+ const frame = await this.findPluginUIFrame();
577
+ try {
578
+ const result = await frame.evaluate(`window.updateVariable(${JSON.stringify(variableId)}, ${JSON.stringify(modeId)}, ${JSON.stringify(value)})`);
579
+ logger.info({ success: result.success, variableName: result.variable?.name }, 'Variable updated');
580
+ await this.logToFigmaConsole((name) => {
581
+ console.log(`[DESKTOP_CONNECTOR] ✅ Variable "${name}" updated successfully`);
582
+ }, result.variable?.name || variableId);
583
+ return result;
584
+ }
585
+ catch (error) {
586
+ logger.error({ error, variableId }, 'Update variable failed');
587
+ throw error;
588
+ }
589
+ }
590
+ /**
591
+ * Create a new variable in a collection
592
+ */
593
+ async createVariable(name, collectionId, resolvedType, options) {
594
+ await this.logToFigmaConsole((n, cId, type) => {
595
+ console.log(`[DESKTOP_CONNECTOR] createVariable() called: "${n}" in collection ${cId}, type: ${type}`);
596
+ }, name, collectionId, resolvedType);
597
+ logger.info({ name, collectionId, resolvedType }, 'Creating variable via plugin UI');
598
+ const frame = await this.findPluginUIFrame();
599
+ try {
600
+ const result = await frame.evaluate(`window.createVariable(${JSON.stringify(name)}, ${JSON.stringify(collectionId)}, ${JSON.stringify(resolvedType)}, ${JSON.stringify(options || {})})`);
601
+ logger.info({ success: result.success, variableId: result.variable?.id }, 'Variable created');
602
+ await this.logToFigmaConsole((id, n) => {
603
+ console.log(`[DESKTOP_CONNECTOR] ✅ Variable "${n}" created with ID: ${id}`);
604
+ }, result.variable?.id || 'unknown', name);
605
+ return result;
606
+ }
607
+ catch (error) {
608
+ logger.error({ error, name }, 'Create variable failed');
609
+ throw error;
610
+ }
611
+ }
612
+ /**
613
+ * Create a new variable collection
614
+ */
615
+ async createVariableCollection(name, options) {
616
+ await this.logToFigmaConsole((n) => {
617
+ console.log(`[DESKTOP_CONNECTOR] createVariableCollection() called: "${n}"`);
618
+ }, name);
619
+ logger.info({ name, options }, 'Creating variable collection via plugin UI');
620
+ const frame = await this.findPluginUIFrame();
621
+ try {
622
+ const result = await frame.evaluate(`window.createVariableCollection(${JSON.stringify(name)}, ${JSON.stringify(options || {})})`);
623
+ logger.info({ success: result.success, collectionId: result.collection?.id }, 'Collection created');
624
+ await this.logToFigmaConsole((id, n) => {
625
+ console.log(`[DESKTOP_CONNECTOR] ✅ Collection "${n}" created with ID: ${id}`);
626
+ }, result.collection?.id || 'unknown', name);
627
+ return result;
628
+ }
629
+ catch (error) {
630
+ logger.error({ error, name }, 'Create collection failed');
631
+ throw error;
632
+ }
633
+ }
634
+ /**
635
+ * Delete a variable
636
+ */
637
+ async deleteVariable(variableId) {
638
+ await this.logToFigmaConsole((vId) => {
639
+ console.log(`[DESKTOP_CONNECTOR] deleteVariable() called: ${vId}`);
640
+ }, variableId);
641
+ logger.info({ variableId }, 'Deleting variable via plugin UI');
642
+ const frame = await this.findPluginUIFrame();
643
+ try {
644
+ const result = await frame.evaluate(`window.deleteVariable(${JSON.stringify(variableId)})`);
645
+ logger.info({ success: result.success, deletedName: result.deleted?.name }, 'Variable deleted');
646
+ await this.logToFigmaConsole((name) => {
647
+ console.log(`[DESKTOP_CONNECTOR] ✅ Variable "${name}" deleted`);
648
+ }, result.deleted?.name || variableId);
649
+ return result;
650
+ }
651
+ catch (error) {
652
+ logger.error({ error, variableId }, 'Delete variable failed');
653
+ throw error;
654
+ }
655
+ }
656
+ /**
657
+ * Delete a variable collection
658
+ */
659
+ async deleteVariableCollection(collectionId) {
660
+ await this.logToFigmaConsole((cId) => {
661
+ console.log(`[DESKTOP_CONNECTOR] deleteVariableCollection() called: ${cId}`);
662
+ }, collectionId);
663
+ logger.info({ collectionId }, 'Deleting collection via plugin UI');
664
+ const frame = await this.findPluginUIFrame();
665
+ try {
666
+ const result = await frame.evaluate(`window.deleteVariableCollection(${JSON.stringify(collectionId)})`);
667
+ logger.info({ success: result.success, deletedName: result.deleted?.name }, 'Collection deleted');
668
+ await this.logToFigmaConsole((name, count) => {
669
+ console.log(`[DESKTOP_CONNECTOR] ✅ Collection "${name}" deleted (had ${count} variables)`);
670
+ }, result.deleted?.name || collectionId, result.deleted?.variableCount || 0);
671
+ return result;
672
+ }
673
+ catch (error) {
674
+ logger.error({ error, collectionId }, 'Delete collection failed');
675
+ throw error;
676
+ }
677
+ }
678
+ /**
679
+ * Refresh variables data from Figma
680
+ */
681
+ async refreshVariables() {
682
+ await this.logToFigmaConsole(() => {
683
+ console.log('[DESKTOP_CONNECTOR] refreshVariables() called');
684
+ });
685
+ logger.info('Refreshing variables via plugin UI');
686
+ const frame = await this.findPluginUIFrame();
687
+ try {
688
+ const result = await frame.evaluate('window.refreshVariables()');
689
+ logger.info({
690
+ success: result.success,
691
+ variableCount: result.data?.variables?.length,
692
+ collectionCount: result.data?.variableCollections?.length
693
+ }, 'Variables refreshed');
694
+ await this.logToFigmaConsole((vCount, cCount) => {
695
+ console.log(`[DESKTOP_CONNECTOR] ✅ Variables refreshed: ${vCount} variables in ${cCount} collections`);
696
+ }, result.data?.variables?.length || 0, result.data?.variableCollections?.length || 0);
697
+ return result;
698
+ }
699
+ catch (error) {
700
+ logger.error({ error }, 'Refresh variables failed');
701
+ throw error;
702
+ }
703
+ }
704
+ /**
705
+ * Rename a variable
706
+ */
707
+ async renameVariable(variableId, newName) {
708
+ await this.logToFigmaConsole((vId, name) => {
709
+ console.log(`[DESKTOP_CONNECTOR] renameVariable() called: ${vId} -> "${name}"`);
710
+ }, variableId, newName);
711
+ logger.info({ variableId, newName }, 'Renaming variable via plugin UI');
712
+ const frame = await this.findPluginUIFrame();
713
+ try {
714
+ // Look up old name from cached variables data, then rename — single CDP roundtrip
715
+ const result = await frame.evaluate(`(async () => {
716
+ var oldName;
717
+ var vars = window.__figmaVariablesData;
718
+ if (vars && vars.variables) {
719
+ var v = vars.variables.find(function(v) { return v.id === ${JSON.stringify(variableId)}; });
720
+ if (v) oldName = v.name;
721
+ }
722
+ var result = await window.renameVariable(${JSON.stringify(variableId)}, ${JSON.stringify(newName)});
723
+ if (oldName) result.oldName = oldName;
724
+ return result;
725
+ })()`);
726
+ logger.info({ success: result.success, oldName: result.oldName, newName: result.variable?.name }, 'Variable renamed');
727
+ await this.logToFigmaConsole((oldN, newN) => {
728
+ console.log(`[DESKTOP_CONNECTOR] ✅ Variable renamed from "${oldN}" to "${newN}"`);
729
+ }, result.oldName || 'unknown', result.variable?.name || newName);
730
+ return result;
731
+ }
732
+ catch (error) {
733
+ logger.error({ error, variableId }, 'Rename variable failed');
734
+ throw error;
735
+ }
736
+ }
737
+ /**
738
+ * Set the description on a variable (not a node — variables use a separate API)
739
+ */
740
+ async setVariableDescription(variableId, description) {
741
+ await this.logToFigmaConsole((vId, desc) => {
742
+ console.log(`[DESKTOP_CONNECTOR] setVariableDescription() called: ${vId} -> "${desc}"`);
743
+ }, variableId, description);
744
+ logger.info({ variableId, description }, 'Setting variable description via plugin UI');
745
+ const frame = await this.findPluginUIFrame();
746
+ try {
747
+ const result = await frame.evaluate(`window.setVariableDescription(${JSON.stringify(variableId)}, ${JSON.stringify(description)})`);
748
+ logger.info({ success: result.success, variableId }, 'Variable description set');
749
+ await this.logToFigmaConsole((vId, success) => {
750
+ console.log(`[DESKTOP_CONNECTOR] ${success ? '✅' : '❌'} Variable description ${success ? 'set' : 'failed'} for ${vId}`);
751
+ }, variableId, result.success);
752
+ return result;
753
+ }
754
+ catch (error) {
755
+ logger.error({ error, variableId }, 'Set variable description failed');
756
+ throw error;
757
+ }
758
+ }
759
+ /**
760
+ * Add a mode to a variable collection
761
+ */
762
+ async addMode(collectionId, modeName) {
763
+ await this.logToFigmaConsole((cId, name) => {
764
+ console.log(`[DESKTOP_CONNECTOR] addMode() called: "${name}" to collection ${cId}`);
765
+ }, collectionId, modeName);
766
+ logger.info({ collectionId, modeName }, 'Adding mode via plugin UI');
767
+ const frame = await this.findPluginUIFrame();
768
+ try {
769
+ const result = await frame.evaluate(`window.addMode(${JSON.stringify(collectionId)}, ${JSON.stringify(modeName)})`);
770
+ logger.info({ success: result.success, newModeId: result.newMode?.modeId }, 'Mode added');
771
+ await this.logToFigmaConsole((name, modeId) => {
772
+ console.log(`[DESKTOP_CONNECTOR] ✅ Mode "${name}" added with ID: ${modeId}`);
773
+ }, modeName, result.newMode?.modeId || 'unknown');
774
+ return result;
775
+ }
776
+ catch (error) {
777
+ logger.error({ error, collectionId }, 'Add mode failed');
778
+ throw error;
779
+ }
780
+ }
781
+ /**
782
+ * Rename a mode in a variable collection
783
+ */
784
+ async renameMode(collectionId, modeId, newName) {
785
+ await this.logToFigmaConsole((cId, mId, name) => {
786
+ console.log(`[DESKTOP_CONNECTOR] renameMode() called: mode ${mId} in collection ${cId} -> "${name}"`);
787
+ }, collectionId, modeId, newName);
788
+ logger.info({ collectionId, modeId, newName }, 'Renaming mode via plugin UI');
789
+ const frame = await this.findPluginUIFrame();
790
+ try {
791
+ // Look up old mode name from cached variables data, then rename — single CDP roundtrip
792
+ const result = await frame.evaluate(`(async () => {
793
+ var oldName;
794
+ var vars = window.__figmaVariablesData;
795
+ var colls = vars && (vars.variableCollections || vars.collections);
796
+ if (colls) {
797
+ for (var i = 0; i < colls.length; i++) {
798
+ var c = colls[i];
799
+ if (c.id === ${JSON.stringify(collectionId)}) {
800
+ var mode = c.modes.find(function(m) { return m.modeId === ${JSON.stringify(modeId)}; });
801
+ if (mode) oldName = mode.name;
802
+ break;
803
+ }
804
+ }
805
+ }
806
+ var result = await window.renameMode(${JSON.stringify(collectionId)}, ${JSON.stringify(modeId)}, ${JSON.stringify(newName)});
807
+ if (oldName) result.oldName = oldName;
808
+ return result;
809
+ })()`);
810
+ logger.info({ success: result.success, oldName: result.oldName, newName }, 'Mode renamed');
811
+ await this.logToFigmaConsole((oldN, newN) => {
812
+ console.log(`[DESKTOP_CONNECTOR] ✅ Mode renamed from "${oldN}" to "${newN}"`);
813
+ }, result.oldName || 'unknown', newName);
814
+ return result;
815
+ }
816
+ catch (error) {
817
+ logger.error({ error, collectionId, modeId }, 'Rename mode failed');
818
+ throw error;
819
+ }
820
+ }
821
+ /**
822
+ * Get all local components for design system manifest generation
823
+ */
824
+ async getLocalComponents() {
825
+ await this.logToFigmaConsole(() => {
826
+ console.log('[DESKTOP_CONNECTOR] getLocalComponents() called');
827
+ });
828
+ logger.info('Getting local components via plugin UI');
829
+ const frame = await this.findPluginUIFrame();
830
+ try {
831
+ const result = await frame.evaluate('window.getLocalComponents()');
832
+ logger.info({
833
+ success: result.success,
834
+ componentCount: result.data?.totalComponents,
835
+ componentSetCount: result.data?.totalComponentSets
836
+ }, 'Local components retrieved');
837
+ await this.logToFigmaConsole((cCount, csCount) => {
838
+ console.log(`[DESKTOP_CONNECTOR] ✅ Found ${cCount} components and ${csCount} component sets`);
839
+ }, result.data?.totalComponents || 0, result.data?.totalComponentSets || 0);
840
+ return result;
841
+ }
842
+ catch (error) {
843
+ logger.error({ error }, 'Get local components failed');
844
+ throw error;
845
+ }
846
+ }
847
+ /**
848
+ * Instantiate a component with overrides
849
+ * Supports both published library components (by key) and local components (by nodeId)
850
+ */
851
+ async instantiateComponent(componentKey, options) {
852
+ await this.logToFigmaConsole((key, nodeId) => {
853
+ console.log(`[DESKTOP_CONNECTOR] instantiateComponent() called: key=${key}, nodeId=${nodeId}`);
854
+ }, componentKey, options?.nodeId || null);
855
+ logger.info({ componentKey, nodeId: options?.nodeId, options }, 'Instantiating component via plugin UI');
856
+ const frame = await this.findPluginUIFrame();
857
+ try {
858
+ const result = await frame.evaluate(`window.instantiateComponent(${JSON.stringify(componentKey)}, ${JSON.stringify(options || {})})`);
859
+ logger.info({ success: result.success, instanceId: result.instance?.id }, 'Component instantiated');
860
+ await this.logToFigmaConsole((instanceId, name) => {
861
+ console.log(`[DESKTOP_CONNECTOR] ✅ Component instantiated: ${name} (${instanceId})`);
862
+ }, result.instance?.id || 'unknown', result.instance?.name || 'unknown');
863
+ return result;
864
+ }
865
+ catch (error) {
866
+ logger.error({ error, componentKey }, 'Instantiate component failed');
867
+ throw error;
868
+ }
869
+ }
870
+ // ============================================================================
871
+ // NEW: COMPONENT PROPERTY MANAGEMENT
872
+ // ============================================================================
873
+ /**
874
+ * Set description on a component or style
875
+ */
876
+ async setNodeDescription(nodeId, description, descriptionMarkdown) {
877
+ logger.info({ nodeId, descriptionLength: description.length }, 'Setting node description via plugin UI');
878
+ const frame = await this.findPluginUIFrame();
879
+ try {
880
+ const result = await frame.evaluate(`window.setNodeDescription(${JSON.stringify(nodeId)}, ${JSON.stringify(description)}, ${JSON.stringify(descriptionMarkdown)})`);
881
+ logger.info({ success: result.success, nodeName: result.node?.name }, 'Description set');
882
+ return result;
883
+ }
884
+ catch (error) {
885
+ logger.error({ error, nodeId }, 'Set description failed');
886
+ throw error;
887
+ }
888
+ }
889
+ /**
890
+ * Add a component property
891
+ */
892
+ async addComponentProperty(nodeId, propertyName, type, defaultValue, options) {
893
+ logger.info({ nodeId, propertyName, type }, 'Adding component property via plugin UI');
894
+ const frame = await this.findPluginUIFrame();
895
+ try {
896
+ const result = await frame.evaluate(`window.addComponentProperty(${JSON.stringify(nodeId)}, ${JSON.stringify(propertyName)}, ${JSON.stringify(type)}, ${JSON.stringify(defaultValue)}, ${JSON.stringify(options || {})})`);
897
+ logger.info({ success: result.success, propertyName: result.propertyName }, 'Property added');
898
+ return result;
899
+ }
900
+ catch (error) {
901
+ logger.error({ error, nodeId, propertyName }, 'Add component property failed');
902
+ throw error;
903
+ }
904
+ }
905
+ /**
906
+ * Edit an existing component property
907
+ */
908
+ async editComponentProperty(nodeId, propertyName, newValue) {
909
+ logger.info({ nodeId, propertyName }, 'Editing component property via plugin UI');
910
+ const frame = await this.findPluginUIFrame();
911
+ try {
912
+ const result = await frame.evaluate(`window.editComponentProperty(${JSON.stringify(nodeId)}, ${JSON.stringify(propertyName)}, ${JSON.stringify(newValue)})`);
913
+ logger.info({ success: result.success, propertyName: result.propertyName }, 'Property edited');
914
+ return result;
915
+ }
916
+ catch (error) {
917
+ logger.error({ error, nodeId, propertyName }, 'Edit component property failed');
918
+ throw error;
919
+ }
920
+ }
921
+ /**
922
+ * Delete a component property
923
+ */
924
+ async deleteComponentProperty(nodeId, propertyName) {
925
+ logger.info({ nodeId, propertyName }, 'Deleting component property via plugin UI');
926
+ const frame = await this.findPluginUIFrame();
927
+ try {
928
+ const result = await frame.evaluate(`window.deleteComponentProperty(${JSON.stringify(nodeId)}, ${JSON.stringify(propertyName)})`);
929
+ logger.info({ success: result.success }, 'Property deleted');
930
+ return result;
931
+ }
932
+ catch (error) {
933
+ logger.error({ error, nodeId, propertyName }, 'Delete component property failed');
934
+ throw error;
935
+ }
936
+ }
937
+ // ============================================================================
938
+ // NEW: NODE MANIPULATION
939
+ // ============================================================================
940
+ /**
941
+ * Resize a node
942
+ */
943
+ async resizeNode(nodeId, width, height, withConstraints = true) {
944
+ logger.info({ nodeId, width, height, withConstraints }, 'Resizing node via plugin UI');
945
+ const frame = await this.findPluginUIFrame();
946
+ try {
947
+ const result = await frame.evaluate(`window.resizeNode(${JSON.stringify(nodeId)}, ${width}, ${height}, ${withConstraints})`);
948
+ logger.info({ success: result.success, nodeId: result.node?.id }, 'Node resized');
949
+ return result;
950
+ }
951
+ catch (error) {
952
+ logger.error({ error, nodeId }, 'Resize node failed');
953
+ throw error;
954
+ }
955
+ }
956
+ /**
957
+ * Move/position a node
958
+ */
959
+ async moveNode(nodeId, x, y) {
960
+ logger.info({ nodeId, x, y }, 'Moving node via plugin UI');
961
+ const frame = await this.findPluginUIFrame();
962
+ try {
963
+ const result = await frame.evaluate(`window.moveNode(${JSON.stringify(nodeId)}, ${x}, ${y})`);
964
+ logger.info({ success: result.success, nodeId: result.node?.id }, 'Node moved');
965
+ return result;
966
+ }
967
+ catch (error) {
968
+ logger.error({ error, nodeId }, 'Move node failed');
969
+ throw error;
970
+ }
971
+ }
972
+ /**
973
+ * Set fills (colors) on a node
974
+ */
975
+ async setNodeFills(nodeId, fills) {
976
+ logger.info({ nodeId, fillCount: fills.length }, 'Setting node fills via plugin UI');
977
+ const frame = await this.findPluginUIFrame();
978
+ try {
979
+ const result = await frame.evaluate(`window.setNodeFills(${JSON.stringify(nodeId)}, ${JSON.stringify(fills)})`);
980
+ logger.info({ success: result.success, nodeId: result.node?.id }, 'Fills set');
981
+ return result;
982
+ }
983
+ catch (error) {
984
+ logger.error({ error, nodeId }, 'Set fills failed');
985
+ throw error;
986
+ }
987
+ }
988
+ /**
989
+ * Set strokes on a node
990
+ */
991
+ async setNodeStrokes(nodeId, strokes, strokeWeight) {
992
+ logger.info({ nodeId, strokeCount: strokes.length, strokeWeight }, 'Setting node strokes via plugin UI');
993
+ const frame = await this.findPluginUIFrame();
994
+ try {
995
+ const result = await frame.evaluate(`window.setNodeStrokes(${JSON.stringify(nodeId)}, ${JSON.stringify(strokes)}, ${strokeWeight})`);
996
+ logger.info({ success: result.success, nodeId: result.node?.id }, 'Strokes set');
997
+ return result;
998
+ }
999
+ catch (error) {
1000
+ logger.error({ error, nodeId }, 'Set strokes failed');
1001
+ throw error;
1002
+ }
1003
+ }
1004
+ /**
1005
+ * Set opacity on a node
1006
+ */
1007
+ async setNodeOpacity(nodeId, opacity) {
1008
+ logger.info({ nodeId, opacity }, 'Setting node opacity via plugin UI');
1009
+ const frame = await this.findPluginUIFrame();
1010
+ try {
1011
+ const result = await frame.evaluate(`window.setNodeOpacity(${JSON.stringify(nodeId)}, ${opacity})`);
1012
+ logger.info({ success: result.success, opacity: result.node?.opacity }, 'Opacity set');
1013
+ return result;
1014
+ }
1015
+ catch (error) {
1016
+ logger.error({ error, nodeId }, 'Set opacity failed');
1017
+ throw error;
1018
+ }
1019
+ }
1020
+ /**
1021
+ * Set corner radius on a node
1022
+ */
1023
+ async setNodeCornerRadius(nodeId, radius) {
1024
+ logger.info({ nodeId, radius }, 'Setting node corner radius via plugin UI');
1025
+ const frame = await this.findPluginUIFrame();
1026
+ try {
1027
+ const result = await frame.evaluate(`window.setNodeCornerRadius(${JSON.stringify(nodeId)}, ${radius})`);
1028
+ logger.info({ success: result.success, radius: result.node?.cornerRadius }, 'Corner radius set');
1029
+ return result;
1030
+ }
1031
+ catch (error) {
1032
+ logger.error({ error, nodeId }, 'Set corner radius failed');
1033
+ throw error;
1034
+ }
1035
+ }
1036
+ /**
1037
+ * Clone/duplicate a node
1038
+ */
1039
+ async cloneNode(nodeId) {
1040
+ logger.info({ nodeId }, 'Cloning node via plugin UI');
1041
+ const frame = await this.findPluginUIFrame();
1042
+ try {
1043
+ const result = await frame.evaluate(`window.cloneNode(${JSON.stringify(nodeId)})`);
1044
+ logger.info({ success: result.success, clonedId: result.node?.id }, 'Node cloned');
1045
+ return result;
1046
+ }
1047
+ catch (error) {
1048
+ logger.error({ error, nodeId }, 'Clone node failed');
1049
+ throw error;
1050
+ }
1051
+ }
1052
+ /**
1053
+ * Delete a node
1054
+ */
1055
+ async deleteNode(nodeId) {
1056
+ logger.info({ nodeId }, 'Deleting node via plugin UI');
1057
+ const frame = await this.findPluginUIFrame();
1058
+ try {
1059
+ const result = await frame.evaluate(`window.deleteNode(${JSON.stringify(nodeId)})`);
1060
+ logger.info({ success: result.success, deletedName: result.deleted?.name }, 'Node deleted');
1061
+ return result;
1062
+ }
1063
+ catch (error) {
1064
+ logger.error({ error, nodeId }, 'Delete node failed');
1065
+ throw error;
1066
+ }
1067
+ }
1068
+ /**
1069
+ * Rename a node
1070
+ */
1071
+ async renameNode(nodeId, newName) {
1072
+ logger.info({ nodeId, newName }, 'Renaming node via plugin UI');
1073
+ const frame = await this.findPluginUIFrame();
1074
+ try {
1075
+ const result = await frame.evaluate(`window.renameNode(${JSON.stringify(nodeId)}, ${JSON.stringify(newName)})`);
1076
+ logger.info({ success: result.success, oldName: result.node?.oldName, newName: result.node?.name }, 'Node renamed');
1077
+ return result;
1078
+ }
1079
+ catch (error) {
1080
+ logger.error({ error, nodeId }, 'Rename node failed');
1081
+ throw error;
1082
+ }
1083
+ }
1084
+ /**
1085
+ * Set text content on a text node
1086
+ */
1087
+ async setTextContent(nodeId, text, options) {
1088
+ logger.info({ nodeId, textLength: text.length }, 'Setting text content via plugin UI');
1089
+ const frame = await this.findPluginUIFrame();
1090
+ try {
1091
+ const result = await frame.evaluate(`window.setTextContent(${JSON.stringify(nodeId)}, ${JSON.stringify(text)}, ${JSON.stringify(options || {})})`);
1092
+ logger.info({ success: result.success, characters: result.node?.characters?.substring(0, 50) }, 'Text content set');
1093
+ return result;
1094
+ }
1095
+ catch (error) {
1096
+ logger.error({ error, nodeId }, 'Set text content failed');
1097
+ throw error;
1098
+ }
1099
+ }
1100
+ /**
1101
+ * Create a child node
1102
+ */
1103
+ async createChildNode(parentId, nodeType, properties) {
1104
+ logger.info({ parentId, nodeType, properties }, 'Creating child node via plugin UI');
1105
+ const frame = await this.findPluginUIFrame();
1106
+ try {
1107
+ const result = await frame.evaluate(`window.createChildNode(${JSON.stringify(parentId)}, ${JSON.stringify(nodeType)}, ${JSON.stringify(properties || {})})`);
1108
+ logger.info({ success: result.success, nodeId: result.node?.id, nodeType: result.node?.type }, 'Child node created');
1109
+ return result;
1110
+ }
1111
+ catch (error) {
1112
+ logger.error({ error, parentId, nodeType }, 'Create child node failed');
1113
+ throw error;
1114
+ }
1115
+ }
1116
+ // ============================================================================
1117
+ // SCREENSHOT & INSTANCE PROPERTIES (via plugin UI)
1118
+ // ============================================================================
1119
+ /**
1120
+ * Capture screenshot via plugin's exportAsync
1121
+ */
1122
+ async captureScreenshot(nodeId, options) {
1123
+ logger.info({ nodeId, options }, 'Capturing screenshot via plugin UI');
1124
+ const frame = await this.findPluginUIFrame();
1125
+ try {
1126
+ const result = await frame.evaluate(`window.captureScreenshot(${JSON.stringify(nodeId)}, ${JSON.stringify(options || {})})`);
1127
+ logger.info({ success: result.success }, 'Screenshot captured');
1128
+ return result;
1129
+ }
1130
+ catch (error) {
1131
+ logger.error({ error, nodeId }, 'Capture screenshot failed');
1132
+ throw error;
1133
+ }
1134
+ }
1135
+ /**
1136
+ * Set component instance properties
1137
+ */
1138
+ async setInstanceProperties(nodeId, properties) {
1139
+ logger.info({ nodeId, properties: Object.keys(properties || {}) }, 'Setting instance properties via plugin UI');
1140
+ const frame = await this.findPluginUIFrame();
1141
+ try {
1142
+ const result = await frame.evaluate(`window.setInstanceProperties(${JSON.stringify(nodeId)}, ${JSON.stringify(properties)})`);
1143
+ logger.info({ success: result.success }, 'Instance properties set');
1144
+ return result;
1145
+ }
1146
+ catch (error) {
1147
+ logger.error({ error, nodeId }, 'Set instance properties failed');
1148
+ throw error;
1149
+ }
1150
+ }
1151
+ /**
1152
+ * Set image fill on one or more nodes (decodes base64 in browser bridge, sends bytes to plugin)
1153
+ */
1154
+ async setImageFill(nodeIds, imageData, scaleMode = 'FILL') {
1155
+ logger.info({ nodeIds, scaleMode, dataLength: imageData.length }, 'Setting image fill via plugin UI');
1156
+ const frame = await this.findPluginUIFrame();
1157
+ try {
1158
+ const result = await frame.evaluate(`window.setImageFill(${JSON.stringify(nodeIds)}, ${JSON.stringify(imageData)}, ${JSON.stringify(scaleMode)})`);
1159
+ logger.info({ success: result.success, imageHash: result.imageHash }, 'Image fill set');
1160
+ return result;
1161
+ }
1162
+ catch (error) {
1163
+ logger.error({ error, nodeIds }, 'Set image fill failed');
1164
+ throw error;
1165
+ }
1166
+ }
1167
+ /**
1168
+ * Lint design for accessibility and quality issues via plugin UI
1169
+ */
1170
+ async lintDesign(nodeId, rules, maxDepth, maxFindings) {
1171
+ logger.info({ nodeId, rules }, 'Linting design via plugin UI');
1172
+ const frame = await this.findPluginUIFrame();
1173
+ try {
1174
+ const result = await frame.evaluate(`window.lintDesign(${JSON.stringify(nodeId || null)}, ${JSON.stringify(rules || null)}, ${JSON.stringify(maxDepth ?? null)}, ${JSON.stringify(maxFindings ?? null)})`);
1175
+ logger.info({ success: result.success }, 'Design lint complete');
1176
+ return result;
1177
+ }
1178
+ catch (error) {
1179
+ logger.error({ error, nodeId }, 'Design lint failed');
1180
+ throw error;
1181
+ }
1182
+ }
1183
+ }
1184
+ FigmaDesktopConnector.DEBUG = process.env.DEBUG === '1' || process.env.DEBUG === 'true';