@mp3wizard/figma-console-mcp 1.20.2 → 1.22.1

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 (51) hide show
  1. package/README.md +10 -9
  2. package/dist/cloudflare/core/accessibility-tools.js +306 -0
  3. package/dist/cloudflare/core/cloud-websocket-connector.js +11 -0
  4. package/dist/cloudflare/core/design-code-tools.js +160 -2
  5. package/dist/cloudflare/core/figjam-tools.js +25 -7
  6. package/dist/cloudflare/core/figma-api.js +1 -10
  7. package/dist/cloudflare/core/figma-desktop-connector.js +2 -0
  8. package/dist/cloudflare/core/websocket-connector.js +11 -0
  9. package/dist/cloudflare/core/websocket-server.js +61 -3
  10. package/dist/cloudflare/core/write-tools.js +49 -4
  11. package/dist/cloudflare/index.js +17 -10
  12. package/dist/core/accessibility-tools.d.ts +21 -0
  13. package/dist/core/accessibility-tools.d.ts.map +1 -0
  14. package/dist/core/accessibility-tools.js +307 -0
  15. package/dist/core/accessibility-tools.js.map +1 -0
  16. package/dist/core/design-code-tools.d.ts.map +1 -1
  17. package/dist/core/design-code-tools.js +160 -2
  18. package/dist/core/design-code-tools.js.map +1 -1
  19. package/dist/core/figjam-tools.d.ts.map +1 -1
  20. package/dist/core/figjam-tools.js +25 -7
  21. package/dist/core/figjam-tools.js.map +1 -1
  22. package/dist/core/figma-api.d.ts.map +1 -1
  23. package/dist/core/figma-api.js +1 -10
  24. package/dist/core/figma-api.js.map +1 -1
  25. package/dist/core/figma-connector.d.ts +1 -0
  26. package/dist/core/figma-connector.d.ts.map +1 -1
  27. package/dist/core/figma-desktop-connector.d.ts +1 -0
  28. package/dist/core/figma-desktop-connector.d.ts.map +1 -1
  29. package/dist/core/figma-desktop-connector.js +2 -0
  30. package/dist/core/figma-desktop-connector.js.map +1 -1
  31. package/dist/core/types/design-code.d.ts +8 -0
  32. package/dist/core/types/design-code.d.ts.map +1 -1
  33. package/dist/core/websocket-connector.d.ts +1 -0
  34. package/dist/core/websocket-connector.d.ts.map +1 -1
  35. package/dist/core/websocket-connector.js +11 -0
  36. package/dist/core/websocket-connector.js.map +1 -1
  37. package/dist/core/websocket-server.d.ts +18 -1
  38. package/dist/core/websocket-server.d.ts.map +1 -1
  39. package/dist/core/websocket-server.js +61 -3
  40. package/dist/core/websocket-server.js.map +1 -1
  41. package/dist/core/write-tools.d.ts.map +1 -1
  42. package/dist/core/write-tools.js +49 -4
  43. package/dist/core/write-tools.js.map +1 -1
  44. package/dist/local.d.ts +13 -0
  45. package/dist/local.d.ts.map +1 -1
  46. package/dist/local.js +181 -23
  47. package/dist/local.js.map +1 -1
  48. package/figma-desktop-bridge/code.js +1020 -1
  49. package/figma-desktop-bridge/ui-full.html +37 -0
  50. package/figma-desktop-bridge/ui.html +15 -2
  51. package/package.json +7 -99
package/README.md CHANGED
@@ -24,6 +24,7 @@ Figma Console MCP connects AI assistants (like Claude) to Figma, enabling:
24
24
  - **🔧 Variable management** - Create, update, rename, and delete design tokens
25
25
  - **⚡ Real-time monitoring** - Watch logs as plugins execute
26
26
  - **📌 FigJam boards** - Create stickies, flowcharts, tables, and code blocks on collaborative boards
27
+ - **♿ Accessibility scanning** - 13 WCAG design checks, component scorecards, axe-core code scanning, design-to-code parity
27
28
  - **☁️ Cloud Write Relay** - Web AI clients (Claude.ai, v0, Replit) can design in Figma via cloud pairing
28
29
  - **🔄 Four ways to connect** - Remote SSE, Cloud Mode, NPX, or Local Git
29
30
 
@@ -54,9 +55,9 @@ Figma Console MCP connects AI assistants (like Claude) to Figma, enabling:
54
55
  | Real-time monitoring (console, selection) | ✅ | ❌ | ❌ |
55
56
  | Desktop Bridge plugin | ✅ | ✅ | ❌ |
56
57
  | Requires Node.js | Yes | **No** | No |
57
- | **Total tools available** | **92+** | **43** | **22** |
58
+ | **Total tools available** | **94+** | **43** | **22** |
58
59
 
59
- > **Bottom line:** Remote SSE is **read-only** with ~38% of the tools. **Cloud Mode** unlocks write access from web AI clients without Node.js. NPX/Local Git gives the full 92+ tools with real-time monitoring.
60
+ > **Bottom line:** Remote SSE is **read-only** with ~38% of the tools. **Cloud Mode** unlocks write access from web AI clients without Node.js. NPX/Local Git gives the full 94+ tools with real-time monitoring.
60
61
 
61
62
  ---
62
63
 
@@ -64,7 +65,7 @@ Figma Console MCP connects AI assistants (like Claude) to Figma, enabling:
64
65
 
65
66
  **Best for:** Designers who want full AI-assisted design capabilities.
66
67
 
67
- **What you get:** All 92+ tools including design creation, variable management, and component instantiation.
68
+ **What you get:** All 94+ tools including design creation, variable management, and component instantiation.
68
69
 
69
70
  #### Prerequisites
70
71
 
@@ -159,7 +160,7 @@ Create a simple frame with a blue background
159
160
 
160
161
  **Best for:** Developers who want to modify source code or contribute to the project.
161
162
 
162
- **What you get:** Same 92+ tools as NPX, plus full source code access.
163
+ **What you get:** Same 94+ tools as NPX, plus full source code access.
163
164
 
164
165
  #### Quick Setup
165
166
 
@@ -248,7 +249,7 @@ Ready for design creation? Follow the [NPX Setup](#-npx-setup-recommended) guide
248
249
 
249
250
  **Best for:** Using Claude.ai, v0, Replit, or Lovable to create and modify Figma designs — no Node.js required.
250
251
 
251
- **What you get:** 82 tools including full write access — design creation, variable management, component instantiation, and all REST API tools. Only real-time monitoring (console logs, selection tracking, document changes) requires Local Mode.
252
+ **What you get:** 83 tools including full write access — design creation, variable management, component instantiation, and all REST API tools. Only real-time monitoring (console logs, selection tracking, document changes) requires Local Mode.
252
253
 
253
254
  #### Prerequisites
254
255
 
@@ -305,7 +306,7 @@ AI Client → Cloud MCP Server → Durable Object Relay → Desktop Bridge Plugi
305
306
  | Feature | NPX (Recommended) | Cloud Mode | Local Git | Remote SSE |
306
307
  |---------|-------------------|------------|-----------|------------|
307
308
  | **Setup time** | ~10 minutes | ~5 minutes | ~15 minutes | ~2 minutes |
308
- | **Total tools** | **92+** | **43** | **92+** | **22** (read-only) |
309
+ | **Total tools** | **94+** | **43** | **94+** | **22** (read-only) |
309
310
  | **Design creation** | ✅ | ✅ | ✅ | ❌ |
310
311
  | **Variable management** | ✅ | ✅ | ✅ | ❌ |
311
312
  | **Component instantiation** | ✅ | ✅ | ✅ | ❌ |
@@ -320,7 +321,7 @@ AI Client → Cloud MCP Server → Durable Object Relay → Desktop Bridge Plugi
320
321
  | **Automatic updates** | ✅ (`@latest`) | ✅ | Manual (`git pull`) | ✅ |
321
322
  | **Source code access** | ❌ | ❌ | ✅ | ❌ |
322
323
 
323
- > **Key insight:** Remote SSE is read-only. Cloud Mode adds write access for web AI clients without Node.js. NPX/Local Git give the full 92+ tools.
324
+ > **Key insight:** Remote SSE is read-only. Cloud Mode adds write access for web AI clients without Node.js. NPX/Local Git give the full 94+ tools.
324
325
 
325
326
  **📖 [Complete Feature Comparison](docs/mode-comparison.md)**
326
327
 
@@ -654,7 +655,7 @@ The **Figma Desktop Bridge** plugin is the recommended way to connect Figma to t
654
655
  - The MCP server communicates via **WebSocket** through the Desktop Bridge plugin
655
656
  - The server tries port 9223 first, then automatically falls back through ports 9224–9232 if needed
656
657
  - The plugin scans all ports in the range and connects to every active server it finds
657
- - All 92+ tools work through the WebSocket transport
658
+ - All 94+ tools work through the WebSocket transport
658
659
 
659
660
  **Multiple files:** The WebSocket server supports multiple simultaneous plugin connections — one per open Figma file. Each connection is tracked by file key with independent state (selection, document changes, console logs).
660
661
 
@@ -791,7 +792,7 @@ The architecture supports adding new apps with minimal boilerplate — each app
791
792
 
792
793
  ## 🛤️ Roadmap
793
794
 
794
- **Current Status:** v1.17.0 (Stable) - Production-ready with FigJam + Slides support, Cloud Write Relay, Design System Kit, WebSocket-only connectivity, smart multi-file tracking, 92+ tools, Comments API, and MCP Apps
795
+ **Current Status:** v1.17.0 (Stable) - Production-ready with FigJam + Slides support, Cloud Write Relay, Design System Kit, WebSocket-only connectivity, smart multi-file tracking, 94+ tools, Comments API, and MCP Apps
795
796
 
796
797
  **Recent Releases:**
797
798
  - [x] **v1.17.0** - Figma Slides Support: 15 new tools for managing presentations — slides, transitions, content, reordering, and navigation. Inspired by Toni Haidamous (PR #11).
@@ -0,0 +1,306 @@
1
+ /**
2
+ * Code-side accessibility scanning via axe-core + JSDOM.
3
+ *
4
+ * Delegates all rule logic to axe-core (Deque) — the MCP never owns
5
+ * a rule database. JSDOM provides a lightweight DOM for structural checks
6
+ * (~50 rules: ARIA, semantics, alt text, form labels, headings, landmarks).
7
+ *
8
+ * Visual rules (color contrast, focus-visible) are NOT available via JSDOM —
9
+ * those are handled by the design-side figma_lint_design tool.
10
+ */
11
+ import { z } from "zod";
12
+ import { logger } from "./logger.js";
13
+ // Lazy-load axe-core and jsdom to keep them optional
14
+ let axeCore = null;
15
+ let JSDOM = null;
16
+ let depsLoaded = false;
17
+ let depsError = null;
18
+ async function loadDeps() {
19
+ if (depsLoaded)
20
+ return;
21
+ try {
22
+ axeCore = await import("axe-core");
23
+ // axe-core's default export structure
24
+ if (axeCore.default)
25
+ axeCore = axeCore.default;
26
+ const jsdomModule = await import("jsdom");
27
+ JSDOM = jsdomModule.JSDOM;
28
+ depsLoaded = true;
29
+ }
30
+ catch (e) {
31
+ depsError = `axe-core or jsdom not installed. Run: npm install axe-core jsdom\n${e.message}`;
32
+ throw new Error(depsError);
33
+ }
34
+ }
35
+ /**
36
+ * Run axe-core against an HTML string using JSDOM.
37
+ *
38
+ * JSDOM limitations: no computed styles, no layout, no visual rendering.
39
+ * This means ~50-60 structural rules work, but visual rules
40
+ * (color-contrast, focus-visible, etc.) will report as "incomplete".
41
+ */
42
+ async function scanHtmlWithAxe(html, options = {}) {
43
+ await loadDeps();
44
+ // Wrap HTML fragment in a full document if needed
45
+ const fullHtml = html.includes("<html") || html.includes("<!DOCTYPE")
46
+ ? html
47
+ : `<!DOCTYPE html><html lang="en"><head><title>Scan</title></head><body>${html}</body></html>`;
48
+ const dom = new JSDOM(fullHtml, {
49
+ runScripts: "dangerously",
50
+ pretendToBeVisual: true,
51
+ url: "http://localhost",
52
+ });
53
+ const { document, window } = dom.window;
54
+ // Inject axe-core into the JSDOM window
55
+ const axeSource = axeCore.source;
56
+ const scriptEl = document.createElement("script");
57
+ scriptEl.textContent = axeSource;
58
+ document.head.appendChild(scriptEl);
59
+ // Configure axe run options
60
+ const runOptions = {};
61
+ if (options.tags && options.tags.length > 0) {
62
+ runOptions.runOnly = { type: "tag", values: options.tags };
63
+ }
64
+ // Disable rules that require visual rendering (always fail/incomplete in JSDOM)
65
+ if (options.disableVisualRules !== false) {
66
+ runOptions.rules = {
67
+ "color-contrast": { enabled: false },
68
+ "color-contrast-enhanced": { enabled: false },
69
+ "link-in-text-block": { enabled: false },
70
+ };
71
+ }
72
+ // Determine scan context
73
+ const context = options.context || document;
74
+ try {
75
+ const results = await window.axe.run(context, runOptions);
76
+ // Clean up
77
+ dom.window.close();
78
+ return results;
79
+ }
80
+ catch (err) {
81
+ dom.window.close();
82
+ throw new Error(`axe-core scan failed: ${err.message}`);
83
+ }
84
+ }
85
+ /**
86
+ * Extract a CodeSpec.accessibility object from HTML + axe-core results.
87
+ * This bridges Phase 3 (code scanning) → Phase 4 (parity comparison).
88
+ *
89
+ * Parses the HTML to extract semantic element, ARIA attributes, and states.
90
+ * Uses axe-core results to infer what the code supports.
91
+ */
92
+ export function axeResultsToCodeSpec(html, axeResults) {
93
+ const spec = {};
94
+ // Parse HTML to extract attributes (lightweight regex-based, no DOM needed)
95
+ const htmlLower = html.toLowerCase();
96
+ // Semantic element: find the root/first meaningful element
97
+ const rootElementMatch = html.match(/<(button|a|input|select|textarea|details|dialog|nav|main|form|label|fieldset)\b/i);
98
+ if (rootElementMatch) {
99
+ spec.semanticElement = rootElementMatch[1].toLowerCase();
100
+ }
101
+ else {
102
+ const firstElementMatch = html.match(/<(\w+)[\s>]/);
103
+ if (firstElementMatch && !["div", "span", "html", "head", "body", "script", "style", "!doctype"].includes(firstElementMatch[1].toLowerCase())) {
104
+ spec.semanticElement = firstElementMatch[1].toLowerCase();
105
+ }
106
+ else {
107
+ spec.semanticElement = "div";
108
+ }
109
+ }
110
+ // ARIA role
111
+ const roleMatch = html.match(/role=["']([^"']+)["']/i);
112
+ if (roleMatch) {
113
+ spec.role = roleMatch[1];
114
+ }
115
+ // ARIA label
116
+ const ariaLabelMatch = html.match(/aria-label=["']([^"']+)["']/i);
117
+ if (ariaLabelMatch) {
118
+ spec.ariaLabel = ariaLabelMatch[1];
119
+ }
120
+ // Focus visible: check for :focus-visible or :focus in inline styles/class names,
121
+ // or infer from element type (native interactive elements have default focus)
122
+ const nativeFocusElements = ["button", "a", "input", "select", "textarea"];
123
+ const hasFocusCSS = /focus-visible|:focus\b|outline.*focus|ring.*focus|focus.*ring/i.test(html);
124
+ spec.focusVisible = hasFocusCSS || nativeFocusElements.includes(spec.semanticElement || "");
125
+ // Disabled support: only assert true when we find positive evidence.
126
+ // Absence of disabled/aria-disabled in a single HTML snapshot does NOT mean
127
+ // the component lacks disabled support — it may be in a non-disabled state.
128
+ if (/\bdisabled\b|aria-disabled/i.test(htmlLower)) {
129
+ spec.supportsDisabled = true;
130
+ }
131
+ // (leave undefined when not found — absence ≠ lack of support)
132
+ // Error support: same principle — only assert true on positive evidence.
133
+ // A default-state HTML snippet won't have aria-invalid; that doesn't mean
134
+ // the component can't enter an error state.
135
+ if (/aria-invalid|aria-errormessage|aria-describedby.*error/i.test(htmlLower)) {
136
+ spec.supportsError = true;
137
+ }
138
+ // (leave undefined when not found — scan a different state to confirm)
139
+ // Required: check for required or aria-required attributes
140
+ if (/aria-required=["']true["']|required(?!=)/i.test(html)) {
141
+ spec.ariaRequired = true;
142
+ }
143
+ else if (/aria-required=["']false["']/i.test(html)) {
144
+ spec.ariaRequired = false;
145
+ }
146
+ // Keyboard interactions: infer from element type
147
+ const keyboardInteractions = [];
148
+ if (spec.semanticElement === "button" || spec.role === "button") {
149
+ keyboardInteractions.push("Enter", "Space");
150
+ }
151
+ else if (spec.semanticElement === "a" || spec.role === "link") {
152
+ keyboardInteractions.push("Enter");
153
+ }
154
+ else if (spec.semanticElement === "input" || spec.semanticElement === "textarea") {
155
+ keyboardInteractions.push("Tab (focus)", "Type (input)");
156
+ }
157
+ else if (spec.semanticElement === "select" || spec.role === "listbox") {
158
+ keyboardInteractions.push("Arrow keys", "Enter", "Space");
159
+ }
160
+ else if (spec.role === "checkbox" || spec.role === "switch") {
161
+ keyboardInteractions.push("Space");
162
+ }
163
+ else if (spec.role === "tab") {
164
+ keyboardInteractions.push("Arrow keys");
165
+ }
166
+ // Check HTML for custom keyboard handlers
167
+ if (/onkeydown|onkeyup|onkeypress|@keydown|@keyup|v-on:keydown/i.test(html)) {
168
+ if (!keyboardInteractions.includes("Custom key handler")) {
169
+ keyboardInteractions.push("Custom key handler");
170
+ }
171
+ }
172
+ if (keyboardInteractions.length > 0) {
173
+ spec.keyboardInteractions = keyboardInteractions;
174
+ }
175
+ // Use axe-core results to refine: if certain violations exist, it tells us what's missing
176
+ if (axeResults?.violations) {
177
+ for (const v of axeResults.violations) {
178
+ // If button-name violation exists, the button has no accessible name
179
+ if (v.id === "button-name") {
180
+ spec.ariaLabel = undefined; // Explicitly missing
181
+ }
182
+ // If label violation exists, input lacks a label
183
+ if (v.id === "label") {
184
+ spec.ariaLabel = undefined;
185
+ }
186
+ }
187
+ }
188
+ return spec;
189
+ }
190
+ /**
191
+ * Format axe-core results into our standard lint-like output structure.
192
+ */
193
+ function formatAxeResults(axeResults) {
194
+ const categories = [];
195
+ const severityMap = {
196
+ critical: "critical",
197
+ serious: "critical",
198
+ moderate: "warning",
199
+ minor: "info",
200
+ };
201
+ // Group violations
202
+ for (const violation of axeResults.violations || []) {
203
+ const severity = severityMap[violation.impact] || "warning";
204
+ const nodes = violation.nodes.map((node) => ({
205
+ html: node.html?.substring(0, 200),
206
+ target: node.target,
207
+ failureSummary: node.failureSummary?.substring(0, 300),
208
+ }));
209
+ categories.push({
210
+ rule: violation.id,
211
+ severity,
212
+ count: violation.nodes.length,
213
+ description: violation.help,
214
+ wcagTags: violation.tags.filter((t) => t.startsWith("wcag") || t.startsWith("best-practice")),
215
+ helpUrl: violation.helpUrl,
216
+ nodes: nodes.slice(0, 10), // Cap at 10 per rule
217
+ });
218
+ }
219
+ // Sort: critical first, then by count
220
+ categories.sort((a, b) => {
221
+ const sevOrder = { critical: 0, warning: 1, info: 2 };
222
+ if (sevOrder[a.severity] !== sevOrder[b.severity]) {
223
+ return sevOrder[a.severity] - sevOrder[b.severity];
224
+ }
225
+ return b.count - a.count;
226
+ });
227
+ // Summary
228
+ const summary = { critical: 0, warning: 0, info: 0, total: 0 };
229
+ for (const cat of categories) {
230
+ summary[cat.severity] += cat.count;
231
+ summary.total += cat.count;
232
+ }
233
+ return {
234
+ engine: "axe-core",
235
+ version: axeResults.testEngine?.version || "unknown",
236
+ mode: "jsdom-structural",
237
+ note: "JSDOM mode: structural/semantic checks only. Visual rules (color contrast, focus visibility) are disabled — use figma_lint_design for visual accessibility checks.",
238
+ categories,
239
+ summary,
240
+ passes: axeResults.passes?.length || 0,
241
+ incomplete: axeResults.incomplete?.length || 0,
242
+ inapplicable: axeResults.inapplicable?.length || 0,
243
+ };
244
+ }
245
+ export function registerAccessibilityTools(server) {
246
+ server.tool("figma_scan_code_accessibility", "Scan HTML code for accessibility violations using axe-core (Deque). " +
247
+ "Runs structural/semantic checks via JSDOM: ARIA attributes, roles, labels, alt text, " +
248
+ "form labels, heading order, landmarks, semantic HTML, tabindex, duplicate IDs, lang attribute, and ~50 more rules. " +
249
+ "Visual checks (color contrast, focus visibility) are disabled in this mode — use figma_lint_design for visual a11y on the design side. " +
250
+ "Together, these two tools provide full-spectrum accessibility coverage across design and code. " +
251
+ "Pass component HTML directly or use with figma_check_design_parity for design-to-code a11y comparison. " +
252
+ "No Figma connection required — this is a standalone code analysis tool.", {
253
+ html: z.string().describe("HTML string to scan. Can be a full document or a component fragment (will be wrapped in a valid document)."),
254
+ tags: z.array(z.string()).optional().describe("WCAG tag filter. Examples: ['wcag2a'], ['wcag2aa'], ['wcag21aa'], ['wcag22aa'], ['best-practice']. " +
255
+ "Defaults to all structural rules if omitted."),
256
+ context: z.string().optional().describe("CSS selector to scope the scan to a specific element (e.g., '#my-component', '.card'). Scans entire document if omitted."),
257
+ includePassingRules: z.boolean().optional().describe("If true, includes count of passing and incomplete rules in the response (default: false)."),
258
+ mapToCodeSpec: z.boolean().optional().describe("If true, includes a codeSpec.accessibility object auto-extracted from the HTML + scan results. " +
259
+ "Pass this directly into figma_check_design_parity's codeSpec.accessibility field for automated design-to-code a11y parity checking."),
260
+ }, async ({ html, tags, context, includePassingRules, mapToCodeSpec }) => {
261
+ try {
262
+ const axeResults = await scanHtmlWithAxe(html, {
263
+ tags: tags || undefined,
264
+ context: context || undefined,
265
+ });
266
+ const formatted = formatAxeResults(axeResults);
267
+ // Optionally strip pass/incomplete counts to save tokens
268
+ if (!includePassingRules) {
269
+ delete formatted.passes;
270
+ delete formatted.incomplete;
271
+ delete formatted.inapplicable;
272
+ }
273
+ // Auto-generate CodeSpec.accessibility from HTML + results
274
+ if (mapToCodeSpec) {
275
+ formatted.codeSpecAccessibility = axeResultsToCodeSpec(html, axeResults);
276
+ formatted.codeSpecAccessibility._usage = "Pass this object as codeSpec.accessibility in figma_check_design_parity for automated a11y parity checking.";
277
+ }
278
+ return {
279
+ content: [
280
+ {
281
+ type: "text",
282
+ text: JSON.stringify(formatted, null, 2),
283
+ },
284
+ ],
285
+ };
286
+ }
287
+ catch (error) {
288
+ const isDepsError = error.message?.includes("not installed");
289
+ logger.error({ error }, "Failed to scan code accessibility");
290
+ return {
291
+ content: [
292
+ {
293
+ type: "text",
294
+ text: JSON.stringify({
295
+ error: error.message,
296
+ hint: isDepsError
297
+ ? "Install dependencies: npm install axe-core jsdom"
298
+ : "Check that the HTML is valid. For visual accessibility checks, use figma_lint_design instead.",
299
+ }),
300
+ },
301
+ ],
302
+ isError: true,
303
+ };
304
+ }
305
+ });
306
+ }
@@ -262,6 +262,17 @@ export class CloudWebSocketConnector {
262
262
  return this.sendCommand('LINT_DESIGN', params, 120000);
263
263
  }
264
264
  // ============================================================================
265
+ // Component accessibility audit
266
+ // ============================================================================
267
+ async auditComponentAccessibility(nodeId, targetSize) {
268
+ const params = {};
269
+ if (nodeId)
270
+ params.nodeId = nodeId;
271
+ if (targetSize !== undefined)
272
+ params.targetSize = targetSize;
273
+ return this.sendCommand('AUDIT_COMPONENT_ACCESSIBILITY', params, 120000);
274
+ }
275
+ // ============================================================================
265
276
  // FigJam operations
266
277
  // ============================================================================
267
278
  async createSticky(params) {
@@ -990,7 +990,9 @@ function compareAccessibility(node, codeSpec, discrepancies) {
990
990
  return;
991
991
  // Check description/annotations for accessibility hints
992
992
  const description = node.descriptionMarkdown || node.description || "";
993
- const hasAriaAnnotation = description.toLowerCase().includes("aria") || description.toLowerCase().includes("accessibility");
993
+ const descLower = description.toLowerCase();
994
+ const hasAriaAnnotation = descLower.includes("aria") || descLower.includes("accessibility");
995
+ // ---- 1. ARIA Role Parity ----
994
996
  if (ca.role && !hasAriaAnnotation) {
995
997
  discrepancies.push({
996
998
  category: "accessibility",
@@ -1002,6 +1004,35 @@ function compareAccessibility(node, codeSpec, discrepancies) {
1002
1004
  suggestion: "Add accessibility annotations in Figma description",
1003
1005
  });
1004
1006
  }
1007
+ // ---- 2. Semantic Element vs Component Name ----
1008
+ if (ca.semanticElement) {
1009
+ const nodeName = (node.name || "").toLowerCase();
1010
+ const element = ca.semanticElement.toLowerCase();
1011
+ // Check if interactive component uses correct semantic element
1012
+ const interactivePattern = /button|link|input|checkbox|radio|switch|toggle|tab|select/i;
1013
+ if (interactivePattern.test(nodeName)) {
1014
+ const elementMatchesDesign = (nodeName.includes("button") && (element === "button" || ca.role === "button")) ||
1015
+ (nodeName.includes("link") && (element === "a" || ca.role === "link")) ||
1016
+ (nodeName.includes("input") && (element === "input" || element === "textarea")) ||
1017
+ (nodeName.includes("checkbox") && (element === "input" || ca.role === "checkbox")) ||
1018
+ (nodeName.includes("radio") && (element === "input" || ca.role === "radio")) ||
1019
+ (nodeName.includes("switch") && (ca.role === "switch" || element === "input")) ||
1020
+ (nodeName.includes("select") && (element === "select" || ca.role === "listbox")) ||
1021
+ (nodeName.includes("tab") && (ca.role === "tab" || element === "button"));
1022
+ if (!elementMatchesDesign) {
1023
+ discrepancies.push({
1024
+ category: "accessibility",
1025
+ property: "semanticElement",
1026
+ severity: "major",
1027
+ designValue: nodeName,
1028
+ codeValue: `<${element}>${ca.role ? ` role="${ca.role}"` : ""}`,
1029
+ message: `Design component "${node.name}" may not match code element <${element}>`,
1030
+ suggestion: `Verify that <${element}> is the correct semantic element for a component named "${node.name}". Use native HTML elements over ARIA roles where possible.`,
1031
+ });
1032
+ }
1033
+ }
1034
+ }
1035
+ // ---- 3. Contrast Ratio ----
1005
1036
  if (ca.contrastRatio !== undefined && ca.contrastRatio < 4.5) {
1006
1037
  discrepancies.push({
1007
1038
  category: "accessibility",
@@ -1013,6 +1044,129 @@ function compareAccessibility(node, codeSpec, discrepancies) {
1013
1044
  suggestion: "Increase contrast ratio to at least 4.5:1",
1014
1045
  });
1015
1046
  }
1047
+ // ---- 4. Focus Indicator Parity ----
1048
+ // Check if design has a focus variant but code doesn't implement focus-visible
1049
+ const variants = node.children || [];
1050
+ const hasFocusVariant = variants.some((v) => /focus|focused/i.test(v.name || ""));
1051
+ if (hasFocusVariant && ca.focusVisible === false) {
1052
+ discrepancies.push({
1053
+ category: "accessibility",
1054
+ property: "focusVisible",
1055
+ severity: "critical",
1056
+ designValue: "focus variant exists",
1057
+ codeValue: "focusVisible: false",
1058
+ message: "Design has a focus variant but code does not implement :focus-visible styles",
1059
+ suggestion: "Add :focus-visible CSS with a visible focus ring matching the design's focus variant (WCAG 2.4.7)",
1060
+ });
1061
+ }
1062
+ else if (!hasFocusVariant && ca.focusVisible === true) {
1063
+ discrepancies.push({
1064
+ category: "accessibility",
1065
+ property: "focusVisible",
1066
+ severity: "minor",
1067
+ designValue: "no focus variant",
1068
+ codeValue: "focusVisible: true",
1069
+ message: "Code implements :focus-visible but design has no focus variant to specify the visual treatment",
1070
+ suggestion: "Add a focus/focused variant in Figma to document the intended focus indicator design",
1071
+ });
1072
+ }
1073
+ // ---- 5. Disabled State Parity ----
1074
+ const hasDisabledVariant = variants.some((v) => /disabled|inactive/i.test(v.name || ""));
1075
+ if (hasDisabledVariant && ca.supportsDisabled === false) {
1076
+ discrepancies.push({
1077
+ category: "accessibility",
1078
+ property: "disabled",
1079
+ severity: "major",
1080
+ designValue: "disabled variant exists",
1081
+ codeValue: "supportsDisabled: false",
1082
+ message: "Design has a disabled variant but code does not support disabled/aria-disabled state",
1083
+ suggestion: "Implement disabled or aria-disabled attribute support in the component",
1084
+ });
1085
+ }
1086
+ else if (!hasDisabledVariant && ca.supportsDisabled === true) {
1087
+ discrepancies.push({
1088
+ category: "accessibility",
1089
+ property: "disabled",
1090
+ severity: "minor",
1091
+ designValue: "no disabled variant",
1092
+ codeValue: "supportsDisabled: true",
1093
+ message: "Code supports disabled state but design has no disabled variant",
1094
+ suggestion: "Add a disabled variant in Figma showing the visual treatment for disabled state",
1095
+ });
1096
+ }
1097
+ // ---- 6. Error State Parity ----
1098
+ const hasErrorVariant = variants.some((v) => /error|invalid|danger/i.test(v.name || ""));
1099
+ if (hasErrorVariant && ca.supportsError === false) {
1100
+ discrepancies.push({
1101
+ category: "accessibility",
1102
+ property: "errorState",
1103
+ severity: "major",
1104
+ designValue: "error variant exists",
1105
+ codeValue: "supportsError: false",
1106
+ message: "Design has an error variant but code does not support aria-invalid or error messaging",
1107
+ suggestion: "Implement aria-invalid attribute and associated error message (aria-describedby) in the component",
1108
+ });
1109
+ }
1110
+ // ---- 7. Required Field Parity ----
1111
+ if (ca.ariaRequired !== undefined) {
1112
+ const hasRequiredVariant = variants.some((v) => /required/i.test(v.name || ""));
1113
+ const hasRequiredInDescription = descLower.includes("required");
1114
+ if (ca.ariaRequired && !hasRequiredVariant && !hasRequiredInDescription) {
1115
+ discrepancies.push({
1116
+ category: "accessibility",
1117
+ property: "required",
1118
+ severity: "minor",
1119
+ designValue: "no required indicator",
1120
+ codeValue: "ariaRequired: true",
1121
+ message: "Code marks field as required but design has no visual required indicator",
1122
+ suggestion: "Add a required indicator (asterisk, label text) in the design and/or a required variant",
1123
+ });
1124
+ }
1125
+ }
1126
+ // ---- 8. Target Size Parity ----
1127
+ if (ca.renderedSize) {
1128
+ const [codeWidth, codeHeight] = ca.renderedSize;
1129
+ const designWidth = node.absoluteBoundingBox?.width || node.size?.x;
1130
+ const designHeight = node.absoluteBoundingBox?.height || node.size?.y;
1131
+ if (designWidth && designHeight) {
1132
+ // Check if code size is significantly smaller than design (>20% reduction)
1133
+ if (codeWidth < designWidth * 0.8 || codeHeight < designHeight * 0.8) {
1134
+ discrepancies.push({
1135
+ category: "accessibility",
1136
+ property: "targetSize",
1137
+ severity: "major",
1138
+ designValue: `${Math.round(designWidth)}x${Math.round(designHeight)}`,
1139
+ codeValue: `${codeWidth}x${codeHeight}`,
1140
+ message: `Code renders significantly smaller (${codeWidth}x${codeHeight}px) than design (${Math.round(designWidth)}x${Math.round(designHeight)}px)`,
1141
+ suggestion: "Ensure rendered component meets the design's touch target size. Check CSS min-width/min-height.",
1142
+ });
1143
+ }
1144
+ // Check WCAG 2.5.8 minimum (24x24)
1145
+ if (codeWidth < 24 || codeHeight < 24) {
1146
+ discrepancies.push({
1147
+ category: "accessibility",
1148
+ property: "targetSize",
1149
+ severity: "critical",
1150
+ designValue: `${Math.round(designWidth)}x${Math.round(designHeight)}`,
1151
+ codeValue: `${codeWidth}x${codeHeight}`,
1152
+ message: `Code renders below WCAG 2.5.8 minimum (24x24px): ${codeWidth}x${codeHeight}px`,
1153
+ suggestion: "Increase touch target size to at least 24x24px",
1154
+ });
1155
+ }
1156
+ }
1157
+ }
1158
+ // ---- 9. Keyboard Interactions ----
1159
+ if (ca.keyboardInteractions && ca.keyboardInteractions.length > 0 && !descLower.includes("keyboard")) {
1160
+ discrepancies.push({
1161
+ category: "accessibility",
1162
+ property: "keyboardInteractions",
1163
+ severity: "info",
1164
+ designValue: null,
1165
+ codeValue: ca.keyboardInteractions.join(", "),
1166
+ message: `Code defines keyboard interactions (${ca.keyboardInteractions.join(", ")}) but design has no keyboard documentation`,
1167
+ suggestion: "Document keyboard interactions in the Figma component description for developer handoff",
1168
+ });
1169
+ }
1016
1170
  }
1017
1171
  function compareNaming(node, codeSpec, discrepancies) {
1018
1172
  const cm = codeSpec.metadata;
@@ -2023,7 +2177,11 @@ const codeSpecSchema = z.object({
2023
2177
  keyboardInteractions: z.array(z.string()).optional(),
2024
2178
  contrastRatio: z.number().optional(),
2025
2179
  focusVisible: z.boolean().optional(),
2026
- }).optional().describe("Accessibility properties from code"),
2180
+ semanticElement: z.string().optional().describe("Semantic HTML element (e.g., 'button', 'a', 'input')"),
2181
+ supportsDisabled: z.boolean().optional().describe("Whether code supports disabled/aria-disabled state"),
2182
+ supportsError: z.boolean().optional().describe("Whether code supports aria-invalid/error state"),
2183
+ renderedSize: z.tuple([z.number(), z.number()]).optional().describe("Rendered size [width, height] in px"),
2184
+ }).optional().describe("Accessibility properties from code. Tip: use figma_scan_code_accessibility with mapToCodeSpec:true to auto-generate this from component HTML."),
2027
2185
  metadata: z.object({
2028
2186
  name: z.string().optional(),
2029
2187
  description: z.string().optional(),
@@ -340,9 +340,24 @@ Nodes must exist on the board (stickies, shapes, etc.). Use their node IDs from
340
340
  server.tool("figjam_create_code_block", `Create a code block on a FigJam board. Use for sharing code snippets, config examples, or technical documentation in collaborative boards.`, {
341
341
  code: z.string().max(MAX_CODE_LENGTH).describe("The code content"),
342
342
  language: z
343
- .string()
343
+ .enum([
344
+ "TYPESCRIPT",
345
+ "JAVASCRIPT",
346
+ "HTML",
347
+ "CSS",
348
+ "JSON",
349
+ "PYTHON",
350
+ "RUBY",
351
+ "COFFEESCRIPT",
352
+ "SWIFT",
353
+ "KOTLIN",
354
+ "DART",
355
+ "BASH",
356
+ "SQL",
357
+ "PLAIN_TEXT",
358
+ ])
344
359
  .optional()
345
- .describe("Programming language (e.g., 'JAVASCRIPT', 'PYTHON', 'TYPESCRIPT', 'JSON', 'HTML', 'CSS')"),
360
+ .describe("Programming language for syntax highlighting. Must be one of the supported Figma CodeLanguage values."),
346
361
  x: z.number().optional().describe("X position on canvas"),
347
362
  y: z.number().optional().describe("Y position on canvas"),
348
363
  }, async ({ code, language, x, y }) => {
@@ -401,17 +416,20 @@ Nodes must exist on the board (stickies, shapes, etc.). Use their node IDs from
401
416
  const connector = await getDesktopConnector();
402
417
  // Compute grid columns safely on the server side — no string interpolation
403
418
  const gridCols = columns || Math.ceil(Math.sqrt(nodeIds.length));
404
- // Pass all parameters as a JSON object to avoid code injection.
405
- // The plugin code reads from the params object, not interpolated strings.
419
+ // SECURITY CONTRACT: All user-controlled values (nodeIds, layout, spacing,
420
+ // gridCols) MUST be passed through this JSON round-trip never interpolated
421
+ // directly into the code template string. JSON.stringify produces a
422
+ // properly-escaped JS string literal that handles all control characters,
423
+ // including \u2028/\u2029 line terminators that break naive string escaping.
424
+ // Any future addition of parameters MUST follow this same pattern.
406
425
  const paramsJson = JSON.stringify({
407
426
  nodeIds,
408
427
  layout,
409
428
  spacing,
410
429
  gridCols,
411
430
  });
412
- // Use JSON.stringify to produce a properly-escaped double-quoted JS string literal.
413
- // This handles all control characters including \u2028/\u2029 that manual
414
- // single-quote escaping would miss.
431
+ // Double-JSON-encode: paramsJson is a string; wrapping it in JSON.stringify
432
+ // again embeds it as a quoted, fully-escaped JS literal inside the code template.
415
433
  const code = `
416
434
  const params = JSON.parse(${JSON.stringify(paramsJson)});
417
435
  const nodes = [];