canicode 0.3.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.
- package/LICENSE +21 -0
- package/README.md +298 -0
- package/dist/cli/index.d.ts +1 -0
- package/dist/cli/index.js +4399 -0
- package/dist/cli/index.js.map +1 -0
- package/dist/index.d.ts +1104 -0
- package/dist/index.js +3513 -0
- package/dist/index.js.map +1 -0
- package/dist/mcp/server.d.ts +1 -0
- package/dist/mcp/server.js +3009 -0
- package/dist/mcp/server.js.map +1 -0
- package/package.json +63 -0
|
@@ -0,0 +1,3009 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { createRequire } from 'module';
|
|
3
|
+
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
|
|
4
|
+
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
|
|
5
|
+
import { config } from 'dotenv';
|
|
6
|
+
import { z } from 'zod';
|
|
7
|
+
import { writeFile, existsSync, mkdirSync, readFileSync } from 'fs';
|
|
8
|
+
import { exec } from 'child_process';
|
|
9
|
+
import { join, resolve, basename } from 'path';
|
|
10
|
+
import { readFile } from 'fs/promises';
|
|
11
|
+
import { homedir } from 'os';
|
|
12
|
+
|
|
13
|
+
var CategorySchema = z.enum([
|
|
14
|
+
"layout",
|
|
15
|
+
"token",
|
|
16
|
+
"component",
|
|
17
|
+
"naming",
|
|
18
|
+
"ai-readability",
|
|
19
|
+
"handoff-risk"
|
|
20
|
+
]);
|
|
21
|
+
var CATEGORIES = CategorySchema.options;
|
|
22
|
+
var CATEGORY_LABELS = {
|
|
23
|
+
layout: "Layout",
|
|
24
|
+
token: "Design Token",
|
|
25
|
+
component: "Component",
|
|
26
|
+
naming: "Naming",
|
|
27
|
+
"ai-readability": "AI Readability",
|
|
28
|
+
"handoff-risk": "Handoff Risk"
|
|
29
|
+
};
|
|
30
|
+
var SeveritySchema = z.enum([
|
|
31
|
+
"blocking",
|
|
32
|
+
"risk",
|
|
33
|
+
"missing-info",
|
|
34
|
+
"suggestion"
|
|
35
|
+
]);
|
|
36
|
+
var SEVERITY_LABELS = {
|
|
37
|
+
blocking: "Blocking",
|
|
38
|
+
risk: "Risk",
|
|
39
|
+
"missing-info": "Missing Info",
|
|
40
|
+
suggestion: "Suggestion"
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
// src/contracts/rule.ts
|
|
44
|
+
z.object({
|
|
45
|
+
id: z.string(),
|
|
46
|
+
name: z.string(),
|
|
47
|
+
category: CategorySchema,
|
|
48
|
+
why: z.string(),
|
|
49
|
+
impact: z.string(),
|
|
50
|
+
fix: z.string()
|
|
51
|
+
});
|
|
52
|
+
z.object({
|
|
53
|
+
severity: SeveritySchema,
|
|
54
|
+
score: z.number().int().max(0),
|
|
55
|
+
depthWeight: z.number().min(1).max(2).optional(),
|
|
56
|
+
enabled: z.boolean().default(true),
|
|
57
|
+
options: z.record(z.string(), z.unknown()).optional()
|
|
58
|
+
});
|
|
59
|
+
var DEPTH_WEIGHT_CATEGORIES = ["layout", "handoff-risk"];
|
|
60
|
+
function supportsDepthWeight(category) {
|
|
61
|
+
return DEPTH_WEIGHT_CATEGORIES.includes(category);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// src/rules/rule-config.ts
|
|
65
|
+
var RULE_CONFIGS = {
|
|
66
|
+
// ============================================
|
|
67
|
+
// Layout (11 rules)
|
|
68
|
+
// ============================================
|
|
69
|
+
"no-auto-layout": {
|
|
70
|
+
severity: "blocking",
|
|
71
|
+
score: -7,
|
|
72
|
+
depthWeight: 1.5,
|
|
73
|
+
enabled: true
|
|
74
|
+
},
|
|
75
|
+
"absolute-position-in-auto-layout": {
|
|
76
|
+
severity: "blocking",
|
|
77
|
+
score: -10,
|
|
78
|
+
depthWeight: 1.3,
|
|
79
|
+
enabled: true
|
|
80
|
+
},
|
|
81
|
+
"fixed-width-in-responsive-context": {
|
|
82
|
+
severity: "risk",
|
|
83
|
+
score: -4,
|
|
84
|
+
depthWeight: 1.3,
|
|
85
|
+
enabled: true
|
|
86
|
+
},
|
|
87
|
+
"missing-responsive-behavior": {
|
|
88
|
+
severity: "risk",
|
|
89
|
+
score: -4,
|
|
90
|
+
depthWeight: 1.5,
|
|
91
|
+
enabled: true
|
|
92
|
+
},
|
|
93
|
+
"group-usage": {
|
|
94
|
+
severity: "risk",
|
|
95
|
+
score: -5,
|
|
96
|
+
depthWeight: 1.2,
|
|
97
|
+
enabled: true
|
|
98
|
+
},
|
|
99
|
+
"fixed-size-in-auto-layout": {
|
|
100
|
+
severity: "risk",
|
|
101
|
+
score: -5,
|
|
102
|
+
enabled: true
|
|
103
|
+
},
|
|
104
|
+
"missing-min-width": {
|
|
105
|
+
severity: "risk",
|
|
106
|
+
score: -5,
|
|
107
|
+
enabled: true
|
|
108
|
+
},
|
|
109
|
+
"missing-max-width": {
|
|
110
|
+
severity: "risk",
|
|
111
|
+
score: -4,
|
|
112
|
+
enabled: true
|
|
113
|
+
},
|
|
114
|
+
"deep-nesting": {
|
|
115
|
+
severity: "risk",
|
|
116
|
+
score: -4,
|
|
117
|
+
enabled: true,
|
|
118
|
+
options: {
|
|
119
|
+
maxDepth: 5
|
|
120
|
+
}
|
|
121
|
+
},
|
|
122
|
+
"overflow-hidden-abuse": {
|
|
123
|
+
severity: "missing-info",
|
|
124
|
+
score: -3,
|
|
125
|
+
enabled: true
|
|
126
|
+
},
|
|
127
|
+
"inconsistent-sibling-layout-direction": {
|
|
128
|
+
severity: "missing-info",
|
|
129
|
+
score: -2,
|
|
130
|
+
enabled: true
|
|
131
|
+
},
|
|
132
|
+
// ============================================
|
|
133
|
+
// Token (7 rules)
|
|
134
|
+
// ============================================
|
|
135
|
+
"raw-color": {
|
|
136
|
+
severity: "missing-info",
|
|
137
|
+
score: -2,
|
|
138
|
+
enabled: true
|
|
139
|
+
},
|
|
140
|
+
"raw-font": {
|
|
141
|
+
severity: "blocking",
|
|
142
|
+
score: -8,
|
|
143
|
+
enabled: true
|
|
144
|
+
},
|
|
145
|
+
"inconsistent-spacing": {
|
|
146
|
+
severity: "missing-info",
|
|
147
|
+
score: -2,
|
|
148
|
+
enabled: true,
|
|
149
|
+
options: {
|
|
150
|
+
gridBase: 8
|
|
151
|
+
}
|
|
152
|
+
},
|
|
153
|
+
"magic-number-spacing": {
|
|
154
|
+
severity: "risk",
|
|
155
|
+
score: -4,
|
|
156
|
+
enabled: true,
|
|
157
|
+
options: {
|
|
158
|
+
gridBase: 8
|
|
159
|
+
}
|
|
160
|
+
},
|
|
161
|
+
"raw-shadow": {
|
|
162
|
+
severity: "missing-info",
|
|
163
|
+
score: -3,
|
|
164
|
+
enabled: true
|
|
165
|
+
},
|
|
166
|
+
"raw-opacity": {
|
|
167
|
+
severity: "missing-info",
|
|
168
|
+
score: -2,
|
|
169
|
+
enabled: true
|
|
170
|
+
},
|
|
171
|
+
"multiple-fill-colors": {
|
|
172
|
+
severity: "missing-info",
|
|
173
|
+
score: -3,
|
|
174
|
+
enabled: true,
|
|
175
|
+
options: {
|
|
176
|
+
tolerance: 10
|
|
177
|
+
}
|
|
178
|
+
},
|
|
179
|
+
// ============================================
|
|
180
|
+
// Component (6 rules)
|
|
181
|
+
// ============================================
|
|
182
|
+
"missing-component": {
|
|
183
|
+
severity: "risk",
|
|
184
|
+
score: -7,
|
|
185
|
+
enabled: true,
|
|
186
|
+
options: {
|
|
187
|
+
minRepetitions: 3
|
|
188
|
+
}
|
|
189
|
+
},
|
|
190
|
+
"detached-instance": {
|
|
191
|
+
severity: "risk",
|
|
192
|
+
score: -5,
|
|
193
|
+
enabled: true
|
|
194
|
+
},
|
|
195
|
+
"nested-instance-override": {
|
|
196
|
+
severity: "risk",
|
|
197
|
+
score: -5,
|
|
198
|
+
enabled: true
|
|
199
|
+
},
|
|
200
|
+
"variant-not-used": {
|
|
201
|
+
severity: "missing-info",
|
|
202
|
+
score: -3,
|
|
203
|
+
enabled: true
|
|
204
|
+
},
|
|
205
|
+
"component-property-unused": {
|
|
206
|
+
severity: "missing-info",
|
|
207
|
+
score: -2,
|
|
208
|
+
enabled: true
|
|
209
|
+
},
|
|
210
|
+
"single-use-component": {
|
|
211
|
+
severity: "suggestion",
|
|
212
|
+
score: -1,
|
|
213
|
+
enabled: true
|
|
214
|
+
},
|
|
215
|
+
// ============================================
|
|
216
|
+
// Naming (5 rules)
|
|
217
|
+
// ============================================
|
|
218
|
+
"default-name": {
|
|
219
|
+
severity: "missing-info",
|
|
220
|
+
score: -2,
|
|
221
|
+
enabled: true
|
|
222
|
+
},
|
|
223
|
+
"non-semantic-name": {
|
|
224
|
+
severity: "missing-info",
|
|
225
|
+
score: -2,
|
|
226
|
+
enabled: true
|
|
227
|
+
},
|
|
228
|
+
"inconsistent-naming-convention": {
|
|
229
|
+
severity: "missing-info",
|
|
230
|
+
score: -2,
|
|
231
|
+
enabled: true
|
|
232
|
+
},
|
|
233
|
+
"numeric-suffix-name": {
|
|
234
|
+
severity: "suggestion",
|
|
235
|
+
score: -1,
|
|
236
|
+
enabled: true
|
|
237
|
+
},
|
|
238
|
+
"too-long-name": {
|
|
239
|
+
severity: "suggestion",
|
|
240
|
+
score: -1,
|
|
241
|
+
enabled: true,
|
|
242
|
+
options: {
|
|
243
|
+
maxLength: 50
|
|
244
|
+
}
|
|
245
|
+
},
|
|
246
|
+
// ============================================
|
|
247
|
+
// AI Readability (5 rules)
|
|
248
|
+
// ============================================
|
|
249
|
+
"ambiguous-structure": {
|
|
250
|
+
severity: "blocking",
|
|
251
|
+
score: -10,
|
|
252
|
+
depthWeight: 1.3,
|
|
253
|
+
enabled: true
|
|
254
|
+
},
|
|
255
|
+
"z-index-dependent-layout": {
|
|
256
|
+
severity: "risk",
|
|
257
|
+
score: -5,
|
|
258
|
+
depthWeight: 1.3,
|
|
259
|
+
enabled: true
|
|
260
|
+
},
|
|
261
|
+
"missing-layout-hint": {
|
|
262
|
+
severity: "risk",
|
|
263
|
+
score: -5,
|
|
264
|
+
enabled: true
|
|
265
|
+
},
|
|
266
|
+
"invisible-layer": {
|
|
267
|
+
severity: "blocking",
|
|
268
|
+
score: -10,
|
|
269
|
+
enabled: true
|
|
270
|
+
},
|
|
271
|
+
"empty-frame": {
|
|
272
|
+
severity: "missing-info",
|
|
273
|
+
score: -2,
|
|
274
|
+
enabled: true
|
|
275
|
+
},
|
|
276
|
+
// ============================================
|
|
277
|
+
// Handoff Risk (5 rules)
|
|
278
|
+
// ============================================
|
|
279
|
+
"hardcode-risk": {
|
|
280
|
+
severity: "risk",
|
|
281
|
+
score: -5,
|
|
282
|
+
depthWeight: 1.5,
|
|
283
|
+
enabled: true
|
|
284
|
+
},
|
|
285
|
+
"text-truncation-unhandled": {
|
|
286
|
+
severity: "risk",
|
|
287
|
+
score: -5,
|
|
288
|
+
enabled: true
|
|
289
|
+
},
|
|
290
|
+
"image-no-placeholder": {
|
|
291
|
+
severity: "missing-info",
|
|
292
|
+
score: -3,
|
|
293
|
+
enabled: true
|
|
294
|
+
},
|
|
295
|
+
"prototype-link-in-design": {
|
|
296
|
+
severity: "missing-info",
|
|
297
|
+
score: -2,
|
|
298
|
+
enabled: true
|
|
299
|
+
},
|
|
300
|
+
"no-dev-status": {
|
|
301
|
+
severity: "missing-info",
|
|
302
|
+
score: -2,
|
|
303
|
+
enabled: false
|
|
304
|
+
// Disabled by default
|
|
305
|
+
}
|
|
306
|
+
};
|
|
307
|
+
function getConfigsWithPreset(preset) {
|
|
308
|
+
const configs = { ...RULE_CONFIGS };
|
|
309
|
+
switch (preset) {
|
|
310
|
+
case "relaxed":
|
|
311
|
+
for (const [id, config2] of Object.entries(configs)) {
|
|
312
|
+
if (config2.severity === "blocking") {
|
|
313
|
+
configs[id] = {
|
|
314
|
+
...config2,
|
|
315
|
+
severity: "risk",
|
|
316
|
+
score: Math.round(config2.score * 0.5)
|
|
317
|
+
};
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
break;
|
|
321
|
+
case "dev-friendly":
|
|
322
|
+
for (const [id, config2] of Object.entries(configs)) {
|
|
323
|
+
const ruleId = id;
|
|
324
|
+
if (!ruleId.includes("layout") && !ruleId.includes("handoff") && !ruleId.includes("responsive")) {
|
|
325
|
+
configs[ruleId] = { ...config2, enabled: false };
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
break;
|
|
329
|
+
case "ai-ready":
|
|
330
|
+
for (const [id, config2] of Object.entries(configs)) {
|
|
331
|
+
const ruleId = id;
|
|
332
|
+
if (ruleId.includes("ambiguous") || ruleId.includes("structure") || ruleId.includes("name")) {
|
|
333
|
+
configs[ruleId] = {
|
|
334
|
+
...config2,
|
|
335
|
+
score: Math.round(config2.score * 1.5)
|
|
336
|
+
};
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
break;
|
|
340
|
+
case "strict":
|
|
341
|
+
for (const [id, config2] of Object.entries(configs)) {
|
|
342
|
+
configs[id] = {
|
|
343
|
+
...config2,
|
|
344
|
+
enabled: true,
|
|
345
|
+
score: Math.round(config2.score * 1.5)
|
|
346
|
+
};
|
|
347
|
+
}
|
|
348
|
+
break;
|
|
349
|
+
}
|
|
350
|
+
return configs;
|
|
351
|
+
}
|
|
352
|
+
function getRuleOption(ruleId, optionKey, defaultValue) {
|
|
353
|
+
const config2 = RULE_CONFIGS[ruleId];
|
|
354
|
+
if (!config2.options) return defaultValue;
|
|
355
|
+
const value = config2.options[optionKey];
|
|
356
|
+
return value ?? defaultValue;
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
// src/rules/rule-registry.ts
|
|
360
|
+
var RuleRegistry = class {
|
|
361
|
+
rules = /* @__PURE__ */ new Map();
|
|
362
|
+
/**
|
|
363
|
+
* Register a rule
|
|
364
|
+
*/
|
|
365
|
+
register(rule) {
|
|
366
|
+
this.rules.set(rule.definition.id, rule);
|
|
367
|
+
}
|
|
368
|
+
/**
|
|
369
|
+
* Get a rule by ID
|
|
370
|
+
*/
|
|
371
|
+
get(id) {
|
|
372
|
+
return this.rules.get(id);
|
|
373
|
+
}
|
|
374
|
+
/**
|
|
375
|
+
* Get all registered rules
|
|
376
|
+
*/
|
|
377
|
+
getAll() {
|
|
378
|
+
return Array.from(this.rules.values());
|
|
379
|
+
}
|
|
380
|
+
/**
|
|
381
|
+
* Get rules by category
|
|
382
|
+
*/
|
|
383
|
+
getByCategory(category) {
|
|
384
|
+
return this.getAll().filter((rule) => rule.definition.category === category);
|
|
385
|
+
}
|
|
386
|
+
/**
|
|
387
|
+
* Get enabled rules with their configs
|
|
388
|
+
*/
|
|
389
|
+
getEnabled(configs = RULE_CONFIGS) {
|
|
390
|
+
return this.getAll().filter((rule) => {
|
|
391
|
+
const config2 = configs[rule.definition.id];
|
|
392
|
+
return config2?.enabled ?? true;
|
|
393
|
+
});
|
|
394
|
+
}
|
|
395
|
+
/**
|
|
396
|
+
* Get config for a rule
|
|
397
|
+
*/
|
|
398
|
+
getConfig(id, configs = RULE_CONFIGS) {
|
|
399
|
+
return configs[id];
|
|
400
|
+
}
|
|
401
|
+
/**
|
|
402
|
+
* Check if a rule is registered
|
|
403
|
+
*/
|
|
404
|
+
has(id) {
|
|
405
|
+
return this.rules.has(id);
|
|
406
|
+
}
|
|
407
|
+
/**
|
|
408
|
+
* Get count of registered rules
|
|
409
|
+
*/
|
|
410
|
+
get size() {
|
|
411
|
+
return this.rules.size;
|
|
412
|
+
}
|
|
413
|
+
};
|
|
414
|
+
var ruleRegistry = new RuleRegistry();
|
|
415
|
+
function defineRule(rule) {
|
|
416
|
+
ruleRegistry.register(rule);
|
|
417
|
+
return rule;
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
// src/core/rule-engine.ts
|
|
421
|
+
function calculateMaxDepth(node, currentDepth = 0) {
|
|
422
|
+
if (!node.children || node.children.length === 0) {
|
|
423
|
+
return currentDepth;
|
|
424
|
+
}
|
|
425
|
+
let maxChildDepth = currentDepth;
|
|
426
|
+
for (const child of node.children) {
|
|
427
|
+
const childDepth = calculateMaxDepth(child, currentDepth + 1);
|
|
428
|
+
if (childDepth > maxChildDepth) {
|
|
429
|
+
maxChildDepth = childDepth;
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
return maxChildDepth;
|
|
433
|
+
}
|
|
434
|
+
function countNodes(node) {
|
|
435
|
+
let count = 1;
|
|
436
|
+
if (node.children) {
|
|
437
|
+
for (const child of node.children) {
|
|
438
|
+
count += countNodes(child);
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
return count;
|
|
442
|
+
}
|
|
443
|
+
function findNodeById(node, nodeId) {
|
|
444
|
+
const normalizedId = nodeId.replace(/-/g, ":");
|
|
445
|
+
if (node.id === normalizedId) {
|
|
446
|
+
return node;
|
|
447
|
+
}
|
|
448
|
+
if (node.children) {
|
|
449
|
+
for (const child of node.children) {
|
|
450
|
+
const found = findNodeById(child, nodeId);
|
|
451
|
+
if (found) return found;
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
return null;
|
|
455
|
+
}
|
|
456
|
+
function calcDepthWeight(depth, maxDepth, depthWeight) {
|
|
457
|
+
if (!depthWeight || depthWeight <= 1) return 1;
|
|
458
|
+
if (maxDepth === 0) return depthWeight;
|
|
459
|
+
const ratio = depth / maxDepth;
|
|
460
|
+
return depthWeight - (depthWeight - 1) * ratio;
|
|
461
|
+
}
|
|
462
|
+
var RuleEngine = class {
|
|
463
|
+
configs;
|
|
464
|
+
enabledRuleIds;
|
|
465
|
+
disabledRuleIds;
|
|
466
|
+
targetNodeId;
|
|
467
|
+
constructor(options = {}) {
|
|
468
|
+
this.configs = options.configs ?? RULE_CONFIGS;
|
|
469
|
+
this.enabledRuleIds = options.enabledRules ? new Set(options.enabledRules) : null;
|
|
470
|
+
this.disabledRuleIds = new Set(options.disabledRules ?? []);
|
|
471
|
+
this.targetNodeId = options.targetNodeId;
|
|
472
|
+
}
|
|
473
|
+
/**
|
|
474
|
+
* Analyze a Figma file and return issues
|
|
475
|
+
*/
|
|
476
|
+
analyze(file) {
|
|
477
|
+
let rootNode = file.document;
|
|
478
|
+
if (this.targetNodeId) {
|
|
479
|
+
const targetNode = findNodeById(file.document, this.targetNodeId);
|
|
480
|
+
if (!targetNode) {
|
|
481
|
+
throw new Error(`Node not found: ${this.targetNodeId}`);
|
|
482
|
+
}
|
|
483
|
+
rootNode = targetNode;
|
|
484
|
+
}
|
|
485
|
+
const maxDepth = calculateMaxDepth(rootNode);
|
|
486
|
+
const nodeCount = countNodes(rootNode);
|
|
487
|
+
const issues = [];
|
|
488
|
+
const enabledRules = this.getEnabledRules();
|
|
489
|
+
this.traverseAndCheck(
|
|
490
|
+
rootNode,
|
|
491
|
+
file,
|
|
492
|
+
enabledRules,
|
|
493
|
+
maxDepth,
|
|
494
|
+
issues,
|
|
495
|
+
0,
|
|
496
|
+
[],
|
|
497
|
+
void 0,
|
|
498
|
+
void 0
|
|
499
|
+
);
|
|
500
|
+
return {
|
|
501
|
+
file,
|
|
502
|
+
issues,
|
|
503
|
+
maxDepth,
|
|
504
|
+
nodeCount,
|
|
505
|
+
analyzedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
506
|
+
};
|
|
507
|
+
}
|
|
508
|
+
/**
|
|
509
|
+
* Get rules that should be run based on configuration
|
|
510
|
+
*/
|
|
511
|
+
getEnabledRules() {
|
|
512
|
+
return ruleRegistry.getAll().filter((rule) => {
|
|
513
|
+
const ruleId = rule.definition.id;
|
|
514
|
+
if (this.disabledRuleIds.has(ruleId)) return false;
|
|
515
|
+
if (this.enabledRuleIds && !this.enabledRuleIds.has(ruleId)) return false;
|
|
516
|
+
const config2 = this.configs[ruleId];
|
|
517
|
+
return config2?.enabled ?? true;
|
|
518
|
+
});
|
|
519
|
+
}
|
|
520
|
+
/**
|
|
521
|
+
* Recursively traverse the tree and run rules
|
|
522
|
+
*/
|
|
523
|
+
traverseAndCheck(node, file, rules, maxDepth, issues, depth, path, parent, siblings) {
|
|
524
|
+
const nodePath = [...path, node.name];
|
|
525
|
+
const context = {
|
|
526
|
+
file,
|
|
527
|
+
parent,
|
|
528
|
+
depth,
|
|
529
|
+
maxDepth,
|
|
530
|
+
path: nodePath,
|
|
531
|
+
siblings
|
|
532
|
+
};
|
|
533
|
+
for (const rule of rules) {
|
|
534
|
+
const ruleId = rule.definition.id;
|
|
535
|
+
const config2 = this.configs[ruleId];
|
|
536
|
+
const options = config2?.options;
|
|
537
|
+
try {
|
|
538
|
+
const violation = rule.check(node, context, options);
|
|
539
|
+
if (violation) {
|
|
540
|
+
let calculatedScore = config2.score;
|
|
541
|
+
if (supportsDepthWeight(rule.definition.category) && config2.depthWeight) {
|
|
542
|
+
const weight = calcDepthWeight(depth, maxDepth, config2.depthWeight);
|
|
543
|
+
calculatedScore = Math.round(config2.score * weight);
|
|
544
|
+
}
|
|
545
|
+
issues.push({
|
|
546
|
+
violation,
|
|
547
|
+
rule,
|
|
548
|
+
config: config2,
|
|
549
|
+
depth,
|
|
550
|
+
maxDepth,
|
|
551
|
+
calculatedScore
|
|
552
|
+
});
|
|
553
|
+
}
|
|
554
|
+
} catch (error) {
|
|
555
|
+
console.error(`Rule "${ruleId}" threw error on node "${node.name}":`, error);
|
|
556
|
+
}
|
|
557
|
+
}
|
|
558
|
+
if (node.children && node.children.length > 0) {
|
|
559
|
+
for (const child of node.children) {
|
|
560
|
+
this.traverseAndCheck(
|
|
561
|
+
child,
|
|
562
|
+
file,
|
|
563
|
+
rules,
|
|
564
|
+
maxDepth,
|
|
565
|
+
issues,
|
|
566
|
+
depth + 1,
|
|
567
|
+
nodePath,
|
|
568
|
+
node,
|
|
569
|
+
node.children
|
|
570
|
+
);
|
|
571
|
+
}
|
|
572
|
+
}
|
|
573
|
+
}
|
|
574
|
+
};
|
|
575
|
+
function createRuleEngine(options) {
|
|
576
|
+
return new RuleEngine(options);
|
|
577
|
+
}
|
|
578
|
+
function analyzeFile(file, options) {
|
|
579
|
+
const engine = createRuleEngine(options);
|
|
580
|
+
return engine.analyze(file);
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
// src/adapters/figma-client.ts
|
|
584
|
+
var FIGMA_API_BASE = "https://api.figma.com/v1";
|
|
585
|
+
var FigmaClient = class _FigmaClient {
|
|
586
|
+
token;
|
|
587
|
+
constructor(options) {
|
|
588
|
+
this.token = options.token;
|
|
589
|
+
}
|
|
590
|
+
static fromEnv() {
|
|
591
|
+
const token = process.env["FIGMA_TOKEN"];
|
|
592
|
+
if (!token) {
|
|
593
|
+
throw new FigmaClientError(
|
|
594
|
+
"FIGMA_TOKEN environment variable is not set"
|
|
595
|
+
);
|
|
596
|
+
}
|
|
597
|
+
return new _FigmaClient({ token });
|
|
598
|
+
}
|
|
599
|
+
async getFile(fileKey) {
|
|
600
|
+
const url = `${FIGMA_API_BASE}/files/${fileKey}`;
|
|
601
|
+
const response = await fetch(url, {
|
|
602
|
+
headers: {
|
|
603
|
+
"X-Figma-Token": this.token
|
|
604
|
+
}
|
|
605
|
+
});
|
|
606
|
+
if (!response.ok) {
|
|
607
|
+
const error = await response.json().catch(() => ({}));
|
|
608
|
+
throw new FigmaClientError(
|
|
609
|
+
`Failed to fetch file: ${response.status} ${response.statusText}`,
|
|
610
|
+
response.status,
|
|
611
|
+
error
|
|
612
|
+
);
|
|
613
|
+
}
|
|
614
|
+
return response.json();
|
|
615
|
+
}
|
|
616
|
+
/**
|
|
617
|
+
* Get rendered images for specific nodes
|
|
618
|
+
* Returns a map of nodeId → image URL
|
|
619
|
+
*/
|
|
620
|
+
async getNodeImages(fileKey, nodeIds, options) {
|
|
621
|
+
const format = options?.format ?? "png";
|
|
622
|
+
const scale = options?.scale ?? 2;
|
|
623
|
+
const BATCH_SIZE = 50;
|
|
624
|
+
const allImages = {};
|
|
625
|
+
for (let i = 0; i < nodeIds.length; i += BATCH_SIZE) {
|
|
626
|
+
const batch = nodeIds.slice(i, i + BATCH_SIZE);
|
|
627
|
+
const ids = batch.join(",");
|
|
628
|
+
const url = `${FIGMA_API_BASE}/images/${fileKey}?ids=${encodeURIComponent(ids)}&format=${format}&scale=${scale}`;
|
|
629
|
+
const response = await fetch(url, {
|
|
630
|
+
headers: {
|
|
631
|
+
"X-Figma-Token": this.token
|
|
632
|
+
}
|
|
633
|
+
});
|
|
634
|
+
if (!response.ok) {
|
|
635
|
+
const error = await response.json().catch(() => ({}));
|
|
636
|
+
throw new FigmaClientError(
|
|
637
|
+
`Failed to fetch images: ${response.status} ${response.statusText}`,
|
|
638
|
+
response.status,
|
|
639
|
+
error
|
|
640
|
+
);
|
|
641
|
+
}
|
|
642
|
+
const data = await response.json();
|
|
643
|
+
for (const [nodeId, imageUrl] of Object.entries(data.images)) {
|
|
644
|
+
allImages[nodeId] = imageUrl;
|
|
645
|
+
}
|
|
646
|
+
}
|
|
647
|
+
return allImages;
|
|
648
|
+
}
|
|
649
|
+
/**
|
|
650
|
+
* Download an image URL and return as base64
|
|
651
|
+
*/
|
|
652
|
+
async fetchImageAsBase64(imageUrl) {
|
|
653
|
+
const response = await fetch(imageUrl);
|
|
654
|
+
if (!response.ok) {
|
|
655
|
+
throw new FigmaClientError(
|
|
656
|
+
`Failed to download image: ${response.status}`,
|
|
657
|
+
response.status
|
|
658
|
+
);
|
|
659
|
+
}
|
|
660
|
+
const buffer = await response.arrayBuffer();
|
|
661
|
+
return Buffer.from(buffer).toString("base64");
|
|
662
|
+
}
|
|
663
|
+
async getFileNodes(fileKey, nodeIds) {
|
|
664
|
+
const ids = nodeIds.join(",");
|
|
665
|
+
const url = `${FIGMA_API_BASE}/files/${fileKey}/nodes?ids=${encodeURIComponent(ids)}`;
|
|
666
|
+
const response = await fetch(url, {
|
|
667
|
+
headers: {
|
|
668
|
+
"X-Figma-Token": this.token
|
|
669
|
+
}
|
|
670
|
+
});
|
|
671
|
+
if (!response.ok) {
|
|
672
|
+
const error = await response.json().catch(() => ({}));
|
|
673
|
+
throw new FigmaClientError(
|
|
674
|
+
`Failed to fetch nodes: ${response.status} ${response.statusText}`,
|
|
675
|
+
response.status,
|
|
676
|
+
error
|
|
677
|
+
);
|
|
678
|
+
}
|
|
679
|
+
return response.json();
|
|
680
|
+
}
|
|
681
|
+
};
|
|
682
|
+
var FigmaClientError = class extends Error {
|
|
683
|
+
constructor(message, statusCode, responseBody) {
|
|
684
|
+
super(message);
|
|
685
|
+
this.statusCode = statusCode;
|
|
686
|
+
this.responseBody = responseBody;
|
|
687
|
+
this.name = "FigmaClientError";
|
|
688
|
+
}
|
|
689
|
+
};
|
|
690
|
+
|
|
691
|
+
// src/adapters/figma-transformer.ts
|
|
692
|
+
function transformFigmaResponse(fileKey, response) {
|
|
693
|
+
return {
|
|
694
|
+
fileKey,
|
|
695
|
+
name: response.name,
|
|
696
|
+
lastModified: response.lastModified,
|
|
697
|
+
version: response.version,
|
|
698
|
+
document: transformNode(response.document),
|
|
699
|
+
components: transformComponents(response.components),
|
|
700
|
+
styles: transformStyles(response.styles)
|
|
701
|
+
};
|
|
702
|
+
}
|
|
703
|
+
function transformNode(node) {
|
|
704
|
+
const base = {
|
|
705
|
+
id: node.id,
|
|
706
|
+
name: node.name,
|
|
707
|
+
type: node.type,
|
|
708
|
+
visible: "visible" in node ? node.visible ?? true : true
|
|
709
|
+
};
|
|
710
|
+
if ("layoutMode" in node && node.layoutMode) {
|
|
711
|
+
base.layoutMode = node.layoutMode;
|
|
712
|
+
}
|
|
713
|
+
if ("layoutAlign" in node && node.layoutAlign) {
|
|
714
|
+
base.layoutAlign = node.layoutAlign;
|
|
715
|
+
}
|
|
716
|
+
if ("layoutPositioning" in node && node.layoutPositioning) {
|
|
717
|
+
base.layoutPositioning = node.layoutPositioning;
|
|
718
|
+
}
|
|
719
|
+
if ("primaryAxisAlignItems" in node) {
|
|
720
|
+
base.primaryAxisAlignItems = node.primaryAxisAlignItems;
|
|
721
|
+
}
|
|
722
|
+
if ("counterAxisAlignItems" in node) {
|
|
723
|
+
base.counterAxisAlignItems = node.counterAxisAlignItems;
|
|
724
|
+
}
|
|
725
|
+
if ("itemSpacing" in node) {
|
|
726
|
+
base.itemSpacing = node.itemSpacing;
|
|
727
|
+
}
|
|
728
|
+
if ("paddingLeft" in node) {
|
|
729
|
+
base.paddingLeft = node.paddingLeft;
|
|
730
|
+
}
|
|
731
|
+
if ("paddingRight" in node) {
|
|
732
|
+
base.paddingRight = node.paddingRight;
|
|
733
|
+
}
|
|
734
|
+
if ("paddingTop" in node) {
|
|
735
|
+
base.paddingTop = node.paddingTop;
|
|
736
|
+
}
|
|
737
|
+
if ("paddingBottom" in node) {
|
|
738
|
+
base.paddingBottom = node.paddingBottom;
|
|
739
|
+
}
|
|
740
|
+
if ("absoluteBoundingBox" in node && node.absoluteBoundingBox) {
|
|
741
|
+
base.absoluteBoundingBox = node.absoluteBoundingBox;
|
|
742
|
+
}
|
|
743
|
+
if ("componentId" in node) {
|
|
744
|
+
base.componentId = node.componentId;
|
|
745
|
+
}
|
|
746
|
+
if ("componentPropertyDefinitions" in node) {
|
|
747
|
+
base.componentPropertyDefinitions = node.componentPropertyDefinitions;
|
|
748
|
+
}
|
|
749
|
+
if ("componentProperties" in node) {
|
|
750
|
+
base.componentProperties = node.componentProperties;
|
|
751
|
+
}
|
|
752
|
+
if ("styles" in node) {
|
|
753
|
+
base.styles = node.styles;
|
|
754
|
+
}
|
|
755
|
+
if ("fills" in node) {
|
|
756
|
+
base.fills = node.fills;
|
|
757
|
+
}
|
|
758
|
+
if ("strokes" in node) {
|
|
759
|
+
base.strokes = node.strokes;
|
|
760
|
+
}
|
|
761
|
+
if ("effects" in node) {
|
|
762
|
+
base.effects = node.effects;
|
|
763
|
+
}
|
|
764
|
+
if ("boundVariables" in node && node.boundVariables) {
|
|
765
|
+
base.boundVariables = node.boundVariables;
|
|
766
|
+
}
|
|
767
|
+
if ("characters" in node) {
|
|
768
|
+
base.characters = node.characters;
|
|
769
|
+
}
|
|
770
|
+
if ("style" in node) {
|
|
771
|
+
base.style = node.style;
|
|
772
|
+
}
|
|
773
|
+
if ("devStatus" in node && node.devStatus) {
|
|
774
|
+
base.devStatus = node.devStatus;
|
|
775
|
+
}
|
|
776
|
+
if ("children" in node && Array.isArray(node.children)) {
|
|
777
|
+
base.children = node.children.map(transformNode);
|
|
778
|
+
}
|
|
779
|
+
return base;
|
|
780
|
+
}
|
|
781
|
+
function transformComponents(components) {
|
|
782
|
+
const result = {};
|
|
783
|
+
for (const [id, component] of Object.entries(components)) {
|
|
784
|
+
result[id] = {
|
|
785
|
+
key: component.key,
|
|
786
|
+
name: component.name,
|
|
787
|
+
description: component.description
|
|
788
|
+
};
|
|
789
|
+
}
|
|
790
|
+
return result;
|
|
791
|
+
}
|
|
792
|
+
function transformStyles(styles) {
|
|
793
|
+
const result = {};
|
|
794
|
+
for (const [id, style] of Object.entries(styles)) {
|
|
795
|
+
result[id] = {
|
|
796
|
+
key: style.key,
|
|
797
|
+
name: style.name,
|
|
798
|
+
styleType: style.styleType
|
|
799
|
+
};
|
|
800
|
+
}
|
|
801
|
+
return result;
|
|
802
|
+
}
|
|
803
|
+
|
|
804
|
+
// src/adapters/figma-file-loader.ts
|
|
805
|
+
async function loadFigmaFileFromJson(filePath) {
|
|
806
|
+
const content = await readFile(filePath, "utf-8");
|
|
807
|
+
const data = JSON.parse(content);
|
|
808
|
+
const fileKey = basename(filePath, ".json");
|
|
809
|
+
return transformFigmaResponse(fileKey, data);
|
|
810
|
+
}
|
|
811
|
+
z.object({
|
|
812
|
+
fileKey: z.string(),
|
|
813
|
+
nodeId: z.string().optional(),
|
|
814
|
+
fileName: z.string().optional()
|
|
815
|
+
});
|
|
816
|
+
var FIGMA_URL_PATTERNS = [
|
|
817
|
+
// https://www.figma.com/design/FILE_KEY/FILE_NAME?node-id=NODE_ID
|
|
818
|
+
/figma\.com\/design\/([a-zA-Z0-9]+)(?:\/([^?]+))?(?:\?.*node-id=([^&]+))?/,
|
|
819
|
+
// https://www.figma.com/file/FILE_KEY/FILE_NAME?node-id=NODE_ID
|
|
820
|
+
/figma\.com\/file\/([a-zA-Z0-9]+)(?:\/([^?]+))?(?:\?.*node-id=([^&]+))?/,
|
|
821
|
+
// https://www.figma.com/proto/FILE_KEY/FILE_NAME?node-id=NODE_ID
|
|
822
|
+
/figma\.com\/proto\/([a-zA-Z0-9]+)(?:\/([^?]+))?(?:\?.*node-id=([^&]+))?/
|
|
823
|
+
];
|
|
824
|
+
function parseFigmaUrl(url) {
|
|
825
|
+
for (const pattern of FIGMA_URL_PATTERNS) {
|
|
826
|
+
const match = url.match(pattern);
|
|
827
|
+
if (match) {
|
|
828
|
+
const [, fileKey, fileName, nodeId] = match;
|
|
829
|
+
if (!fileKey) {
|
|
830
|
+
throw new FigmaUrlParseError(`Invalid Figma URL: missing file key`);
|
|
831
|
+
}
|
|
832
|
+
return {
|
|
833
|
+
fileKey,
|
|
834
|
+
fileName: fileName ? decodeURIComponent(fileName) : void 0,
|
|
835
|
+
nodeId: nodeId ? decodeURIComponent(nodeId) : void 0
|
|
836
|
+
};
|
|
837
|
+
}
|
|
838
|
+
}
|
|
839
|
+
throw new FigmaUrlParseError(
|
|
840
|
+
`Invalid Figma URL format. Expected: https://www.figma.com/design/FILE_KEY/...`
|
|
841
|
+
);
|
|
842
|
+
}
|
|
843
|
+
var FigmaUrlParseError = class extends Error {
|
|
844
|
+
constructor(message) {
|
|
845
|
+
super(message);
|
|
846
|
+
this.name = "FigmaUrlParseError";
|
|
847
|
+
}
|
|
848
|
+
};
|
|
849
|
+
function buildFigmaDeepLink(fileKey, nodeId) {
|
|
850
|
+
return `https://www.figma.com/design/${fileKey}?node-id=${encodeURIComponent(nodeId)}`;
|
|
851
|
+
}
|
|
852
|
+
|
|
853
|
+
// src/adapters/figma-mcp-adapter.ts
|
|
854
|
+
var TAG_TYPE_MAP = {
|
|
855
|
+
canvas: "CANVAS",
|
|
856
|
+
frame: "FRAME",
|
|
857
|
+
group: "GROUP",
|
|
858
|
+
section: "SECTION",
|
|
859
|
+
component: "COMPONENT",
|
|
860
|
+
"component-set": "COMPONENT_SET",
|
|
861
|
+
instance: "INSTANCE",
|
|
862
|
+
rectangle: "RECTANGLE",
|
|
863
|
+
"rounded-rectangle": "RECTANGLE",
|
|
864
|
+
ellipse: "ELLIPSE",
|
|
865
|
+
vector: "VECTOR",
|
|
866
|
+
text: "TEXT",
|
|
867
|
+
line: "LINE",
|
|
868
|
+
"boolean-operation": "BOOLEAN_OPERATION",
|
|
869
|
+
star: "STAR",
|
|
870
|
+
"regular-polygon": "REGULAR_POLYGON",
|
|
871
|
+
slice: "SLICE",
|
|
872
|
+
sticky: "STICKY",
|
|
873
|
+
table: "TABLE",
|
|
874
|
+
"table-cell": "TABLE_CELL",
|
|
875
|
+
symbol: "COMPONENT",
|
|
876
|
+
slot: "FRAME"
|
|
877
|
+
};
|
|
878
|
+
function parseXml(xml) {
|
|
879
|
+
const nodes = [];
|
|
880
|
+
const stack = [];
|
|
881
|
+
const tagRegex = /<(\/?)([\w-]+)([^>]*?)(\/?)>/g;
|
|
882
|
+
let match;
|
|
883
|
+
while ((match = tagRegex.exec(xml)) !== null) {
|
|
884
|
+
const isClosing = match[1] === "/";
|
|
885
|
+
const tagName = match[2];
|
|
886
|
+
const attrString = match[3] ?? "";
|
|
887
|
+
const isSelfClosing = match[4] === "/";
|
|
888
|
+
if (isClosing) {
|
|
889
|
+
const finished = stack.pop();
|
|
890
|
+
if (finished) {
|
|
891
|
+
const parent = stack[stack.length - 1];
|
|
892
|
+
if (parent) {
|
|
893
|
+
parent.children.push(finished);
|
|
894
|
+
} else {
|
|
895
|
+
nodes.push(finished);
|
|
896
|
+
}
|
|
897
|
+
}
|
|
898
|
+
} else {
|
|
899
|
+
const attrs = parseAttributes(attrString);
|
|
900
|
+
const node = { tag: tagName, attrs, children: [] };
|
|
901
|
+
if (isSelfClosing) {
|
|
902
|
+
const parent = stack[stack.length - 1];
|
|
903
|
+
if (parent) {
|
|
904
|
+
parent.children.push(node);
|
|
905
|
+
} else {
|
|
906
|
+
nodes.push(node);
|
|
907
|
+
}
|
|
908
|
+
} else {
|
|
909
|
+
stack.push(node);
|
|
910
|
+
}
|
|
911
|
+
}
|
|
912
|
+
}
|
|
913
|
+
while (stack.length > 0) {
|
|
914
|
+
const finished = stack.pop();
|
|
915
|
+
const parent = stack[stack.length - 1];
|
|
916
|
+
if (parent) {
|
|
917
|
+
parent.children.push(finished);
|
|
918
|
+
} else {
|
|
919
|
+
nodes.push(finished);
|
|
920
|
+
}
|
|
921
|
+
}
|
|
922
|
+
return nodes;
|
|
923
|
+
}
|
|
924
|
+
function parseAttributes(attrString) {
|
|
925
|
+
const attrs = {};
|
|
926
|
+
const attrRegex = /([\w-]+)="([^"]*)"/g;
|
|
927
|
+
let match;
|
|
928
|
+
while ((match = attrRegex.exec(attrString)) !== null) {
|
|
929
|
+
const key = match[1];
|
|
930
|
+
const value = match[2];
|
|
931
|
+
if (key && value !== void 0) {
|
|
932
|
+
attrs[key] = value;
|
|
933
|
+
}
|
|
934
|
+
}
|
|
935
|
+
return attrs;
|
|
936
|
+
}
|
|
937
|
+
function toAnalysisNode(xmlNode) {
|
|
938
|
+
const type = TAG_TYPE_MAP[xmlNode.tag] ?? "FRAME";
|
|
939
|
+
const id = xmlNode.attrs["id"] ?? "0:0";
|
|
940
|
+
const name = xmlNode.attrs["name"] ?? xmlNode.tag;
|
|
941
|
+
const hidden = xmlNode.attrs["hidden"] === "true";
|
|
942
|
+
const x = parseFloat(xmlNode.attrs["x"] ?? "0");
|
|
943
|
+
const y = parseFloat(xmlNode.attrs["y"] ?? "0");
|
|
944
|
+
const width = parseFloat(xmlNode.attrs["width"] ?? "0");
|
|
945
|
+
const height = parseFloat(xmlNode.attrs["height"] ?? "0");
|
|
946
|
+
const node = {
|
|
947
|
+
id,
|
|
948
|
+
name,
|
|
949
|
+
type,
|
|
950
|
+
visible: !hidden,
|
|
951
|
+
absoluteBoundingBox: { x, y, width, height }
|
|
952
|
+
};
|
|
953
|
+
if (xmlNode.children.length > 0) {
|
|
954
|
+
node.children = xmlNode.children.map(toAnalysisNode);
|
|
955
|
+
}
|
|
956
|
+
return node;
|
|
957
|
+
}
|
|
958
|
+
function parseMcpMetadataXml(xml, fileKey, fileName) {
|
|
959
|
+
const parsed = parseXml(xml);
|
|
960
|
+
const children = parsed.map(toAnalysisNode);
|
|
961
|
+
let document;
|
|
962
|
+
if (children.length === 1 && children[0]) {
|
|
963
|
+
document = children[0];
|
|
964
|
+
} else {
|
|
965
|
+
document = {
|
|
966
|
+
id: "0:0",
|
|
967
|
+
name: "Document",
|
|
968
|
+
type: "DOCUMENT",
|
|
969
|
+
visible: true,
|
|
970
|
+
children
|
|
971
|
+
};
|
|
972
|
+
}
|
|
973
|
+
return {
|
|
974
|
+
fileKey,
|
|
975
|
+
name: fileName ?? fileKey,
|
|
976
|
+
lastModified: (/* @__PURE__ */ new Date()).toISOString(),
|
|
977
|
+
version: "mcp",
|
|
978
|
+
document,
|
|
979
|
+
components: {},
|
|
980
|
+
styles: {}
|
|
981
|
+
};
|
|
982
|
+
}
|
|
983
|
+
var AIREADY_DIR = join(homedir(), ".canicode");
|
|
984
|
+
var CONFIG_PATH = join(AIREADY_DIR, "config.json");
|
|
985
|
+
var REPORTS_DIR = join(AIREADY_DIR, "reports");
|
|
986
|
+
function ensureDir(dir) {
|
|
987
|
+
if (!existsSync(dir)) {
|
|
988
|
+
mkdirSync(dir, { recursive: true });
|
|
989
|
+
}
|
|
990
|
+
}
|
|
991
|
+
function readConfig() {
|
|
992
|
+
if (!existsSync(CONFIG_PATH)) {
|
|
993
|
+
return {};
|
|
994
|
+
}
|
|
995
|
+
try {
|
|
996
|
+
const raw = readFileSync(CONFIG_PATH, "utf-8");
|
|
997
|
+
return JSON.parse(raw);
|
|
998
|
+
} catch {
|
|
999
|
+
return {};
|
|
1000
|
+
}
|
|
1001
|
+
}
|
|
1002
|
+
function getFigmaToken() {
|
|
1003
|
+
return process.env["FIGMA_TOKEN"] ?? readConfig().figmaToken;
|
|
1004
|
+
}
|
|
1005
|
+
function getReportsDir() {
|
|
1006
|
+
return REPORTS_DIR;
|
|
1007
|
+
}
|
|
1008
|
+
function ensureReportsDir() {
|
|
1009
|
+
ensureDir(REPORTS_DIR);
|
|
1010
|
+
}
|
|
1011
|
+
|
|
1012
|
+
// src/core/loader.ts
|
|
1013
|
+
function isFigmaUrl(input) {
|
|
1014
|
+
return input.includes("figma.com/");
|
|
1015
|
+
}
|
|
1016
|
+
function isJsonFile(input) {
|
|
1017
|
+
return input.endsWith(".json");
|
|
1018
|
+
}
|
|
1019
|
+
async function loadFile(input, token, mode = "auto") {
|
|
1020
|
+
if (isJsonFile(input)) {
|
|
1021
|
+
const filePath = resolve(input);
|
|
1022
|
+
if (!existsSync(filePath)) {
|
|
1023
|
+
throw new Error(`File not found: ${filePath}`);
|
|
1024
|
+
}
|
|
1025
|
+
console.log(`Loading from JSON: ${filePath}`);
|
|
1026
|
+
return { file: await loadFigmaFileFromJson(filePath) };
|
|
1027
|
+
}
|
|
1028
|
+
if (isFigmaUrl(input)) {
|
|
1029
|
+
const { fileKey, nodeId, fileName } = parseFigmaUrl(input);
|
|
1030
|
+
if (mode === "mcp") {
|
|
1031
|
+
return loadFromMcp(fileKey, nodeId, fileName);
|
|
1032
|
+
}
|
|
1033
|
+
if (mode === "api") {
|
|
1034
|
+
return loadFromApi(fileKey, nodeId, token);
|
|
1035
|
+
}
|
|
1036
|
+
try {
|
|
1037
|
+
console.log("Auto-detecting data source... trying MCP first.");
|
|
1038
|
+
return await loadFromMcp(fileKey, nodeId, fileName);
|
|
1039
|
+
} catch (mcpError) {
|
|
1040
|
+
const mcpMsg = mcpError instanceof Error ? mcpError.message : String(mcpError);
|
|
1041
|
+
console.log(`MCP unavailable (${mcpMsg}). Falling back to REST API.`);
|
|
1042
|
+
return loadFromApi(fileKey, nodeId, token);
|
|
1043
|
+
}
|
|
1044
|
+
}
|
|
1045
|
+
throw new Error(
|
|
1046
|
+
`Invalid input: ${input}. Provide a Figma URL or JSON file path.`
|
|
1047
|
+
);
|
|
1048
|
+
}
|
|
1049
|
+
async function loadFromMcp(fileKey, nodeId, fileName) {
|
|
1050
|
+
console.log(`Loading via MCP: ${fileKey} (node: ${nodeId ?? "root"})`);
|
|
1051
|
+
const file = await loadViaMcp(fileKey, nodeId ?? "0:1", fileName);
|
|
1052
|
+
return { file, nodeId };
|
|
1053
|
+
}
|
|
1054
|
+
async function loadFromApi(fileKey, nodeId, token) {
|
|
1055
|
+
console.log(`Fetching from Figma REST API: ${fileKey}`);
|
|
1056
|
+
if (nodeId) {
|
|
1057
|
+
console.log(`Target node: ${nodeId}`);
|
|
1058
|
+
}
|
|
1059
|
+
const figmaToken = token ?? getFigmaToken();
|
|
1060
|
+
if (!figmaToken) {
|
|
1061
|
+
throw new Error(
|
|
1062
|
+
"Figma token required. Run 'canicode init --token YOUR_TOKEN' or set FIGMA_TOKEN env var."
|
|
1063
|
+
);
|
|
1064
|
+
}
|
|
1065
|
+
const client = new FigmaClient({ token: figmaToken });
|
|
1066
|
+
const response = await client.getFile(fileKey);
|
|
1067
|
+
return {
|
|
1068
|
+
file: transformFigmaResponse(fileKey, response),
|
|
1069
|
+
nodeId
|
|
1070
|
+
};
|
|
1071
|
+
}
|
|
1072
|
+
async function loadViaMcp(fileKey, nodeId, fileName) {
|
|
1073
|
+
const { execSync } = await import('child_process');
|
|
1074
|
+
const result = execSync(
|
|
1075
|
+
`claude --print "Use the mcp__figma__get_metadata tool with fileKey=\\"${fileKey}\\" and nodeId=\\"${nodeId.replace(/-/g, ":")}\\" \u2014 return ONLY the raw XML output, nothing else."`,
|
|
1076
|
+
{ encoding: "utf-8", timeout: 12e4 }
|
|
1077
|
+
);
|
|
1078
|
+
const xmlStart = result.indexOf("<");
|
|
1079
|
+
const xmlEnd = result.lastIndexOf(">");
|
|
1080
|
+
if (xmlStart === -1 || xmlEnd === -1) {
|
|
1081
|
+
throw new Error("MCP did not return valid XML metadata");
|
|
1082
|
+
}
|
|
1083
|
+
const xml = result.slice(xmlStart, xmlEnd + 1);
|
|
1084
|
+
return parseMcpMetadataXml(xml, fileKey, fileName);
|
|
1085
|
+
}
|
|
1086
|
+
|
|
1087
|
+
// src/core/design-data-parser.ts
|
|
1088
|
+
function parseDesignData(data, fileKey, fileName) {
|
|
1089
|
+
const trimmed = data.trim();
|
|
1090
|
+
if (trimmed.startsWith("<")) {
|
|
1091
|
+
return parseMcpMetadataXml(trimmed, fileKey, fileName);
|
|
1092
|
+
}
|
|
1093
|
+
const parsed = JSON.parse(trimmed);
|
|
1094
|
+
if ("fileKey" in parsed && "document" in parsed) {
|
|
1095
|
+
return parsed;
|
|
1096
|
+
}
|
|
1097
|
+
if ("document" in parsed && "name" in parsed) {
|
|
1098
|
+
return transformFigmaResponse(fileKey, parsed);
|
|
1099
|
+
}
|
|
1100
|
+
throw new Error(
|
|
1101
|
+
"Unrecognized designData format. Expected XML from Figma MCP get_metadata, AnalysisFile JSON, or Figma REST API JSON."
|
|
1102
|
+
);
|
|
1103
|
+
}
|
|
1104
|
+
|
|
1105
|
+
// src/core/scoring.ts
|
|
1106
|
+
var SEVERITY_DENSITY_WEIGHT = {
|
|
1107
|
+
blocking: 3,
|
|
1108
|
+
risk: 2,
|
|
1109
|
+
"missing-info": 1,
|
|
1110
|
+
suggestion: 0.5
|
|
1111
|
+
};
|
|
1112
|
+
var TOTAL_RULES_PER_CATEGORY = {
|
|
1113
|
+
layout: 11,
|
|
1114
|
+
token: 7,
|
|
1115
|
+
component: 6,
|
|
1116
|
+
naming: 5,
|
|
1117
|
+
"ai-readability": 5,
|
|
1118
|
+
"handoff-risk": 5
|
|
1119
|
+
};
|
|
1120
|
+
var CATEGORY_WEIGHT = {
|
|
1121
|
+
layout: 1,
|
|
1122
|
+
token: 1,
|
|
1123
|
+
component: 1,
|
|
1124
|
+
naming: 1,
|
|
1125
|
+
"ai-readability": 1,
|
|
1126
|
+
"handoff-risk": 1
|
|
1127
|
+
};
|
|
1128
|
+
var DENSITY_WEIGHT = 0.7;
|
|
1129
|
+
var DIVERSITY_WEIGHT = 0.3;
|
|
1130
|
+
var SCORE_FLOOR = 5;
|
|
1131
|
+
function calculateGrade(percentage) {
|
|
1132
|
+
if (percentage >= 95) return "S";
|
|
1133
|
+
if (percentage >= 90) return "A+";
|
|
1134
|
+
if (percentage >= 85) return "A";
|
|
1135
|
+
if (percentage >= 80) return "B+";
|
|
1136
|
+
if (percentage >= 75) return "B";
|
|
1137
|
+
if (percentage >= 70) return "C+";
|
|
1138
|
+
if (percentage >= 65) return "C";
|
|
1139
|
+
if (percentage >= 50) return "D";
|
|
1140
|
+
return "F";
|
|
1141
|
+
}
|
|
1142
|
+
function clamp(value, min, max) {
|
|
1143
|
+
return Math.max(min, Math.min(max, value));
|
|
1144
|
+
}
|
|
1145
|
+
function calculateScores(result) {
|
|
1146
|
+
const categoryScores = initializeCategoryScores();
|
|
1147
|
+
const nodeCount = result.nodeCount;
|
|
1148
|
+
const uniqueRulesPerCategory = /* @__PURE__ */ new Map();
|
|
1149
|
+
for (const category of CATEGORIES) {
|
|
1150
|
+
uniqueRulesPerCategory.set(category, /* @__PURE__ */ new Set());
|
|
1151
|
+
}
|
|
1152
|
+
for (const issue of result.issues) {
|
|
1153
|
+
const category = issue.rule.definition.category;
|
|
1154
|
+
const severity = issue.config.severity;
|
|
1155
|
+
const ruleId = issue.rule.definition.id;
|
|
1156
|
+
categoryScores[category].issueCount++;
|
|
1157
|
+
categoryScores[category].bySeverity[severity]++;
|
|
1158
|
+
categoryScores[category].weightedIssueCount += SEVERITY_DENSITY_WEIGHT[severity];
|
|
1159
|
+
uniqueRulesPerCategory.get(category).add(ruleId);
|
|
1160
|
+
}
|
|
1161
|
+
for (const category of CATEGORIES) {
|
|
1162
|
+
const catScore = categoryScores[category];
|
|
1163
|
+
const uniqueRules = uniqueRulesPerCategory.get(category);
|
|
1164
|
+
const totalRules = TOTAL_RULES_PER_CATEGORY[category];
|
|
1165
|
+
catScore.uniqueRuleCount = uniqueRules.size;
|
|
1166
|
+
let densityScore = 100;
|
|
1167
|
+
if (nodeCount > 0 && catScore.issueCount > 0) {
|
|
1168
|
+
const density = catScore.weightedIssueCount / nodeCount;
|
|
1169
|
+
densityScore = clamp(Math.round(100 - density * 100), 0, 100);
|
|
1170
|
+
}
|
|
1171
|
+
catScore.densityScore = densityScore;
|
|
1172
|
+
let diversityScore = 100;
|
|
1173
|
+
if (catScore.issueCount > 0) {
|
|
1174
|
+
const diversityRatio = uniqueRules.size / totalRules;
|
|
1175
|
+
diversityScore = clamp(Math.round((1 - diversityRatio) * 100), 0, 100);
|
|
1176
|
+
}
|
|
1177
|
+
catScore.diversityScore = diversityScore;
|
|
1178
|
+
const combinedScore = densityScore * DENSITY_WEIGHT + diversityScore * DIVERSITY_WEIGHT;
|
|
1179
|
+
catScore.percentage = catScore.issueCount > 0 ? clamp(Math.round(combinedScore), SCORE_FLOOR, 100) : 100;
|
|
1180
|
+
catScore.score = catScore.percentage;
|
|
1181
|
+
catScore.maxScore = 100;
|
|
1182
|
+
}
|
|
1183
|
+
let totalWeight = 0;
|
|
1184
|
+
let weightedSum = 0;
|
|
1185
|
+
for (const category of CATEGORIES) {
|
|
1186
|
+
const weight = CATEGORY_WEIGHT[category];
|
|
1187
|
+
weightedSum += categoryScores[category].percentage * weight;
|
|
1188
|
+
totalWeight += weight;
|
|
1189
|
+
}
|
|
1190
|
+
const overallPercentage = totalWeight > 0 ? Math.round(weightedSum / totalWeight) : 100;
|
|
1191
|
+
const summary = {
|
|
1192
|
+
totalIssues: result.issues.length,
|
|
1193
|
+
blocking: 0,
|
|
1194
|
+
risk: 0,
|
|
1195
|
+
missingInfo: 0,
|
|
1196
|
+
suggestion: 0,
|
|
1197
|
+
nodeCount
|
|
1198
|
+
};
|
|
1199
|
+
for (const issue of result.issues) {
|
|
1200
|
+
switch (issue.config.severity) {
|
|
1201
|
+
case "blocking":
|
|
1202
|
+
summary.blocking++;
|
|
1203
|
+
break;
|
|
1204
|
+
case "risk":
|
|
1205
|
+
summary.risk++;
|
|
1206
|
+
break;
|
|
1207
|
+
case "missing-info":
|
|
1208
|
+
summary.missingInfo++;
|
|
1209
|
+
break;
|
|
1210
|
+
case "suggestion":
|
|
1211
|
+
summary.suggestion++;
|
|
1212
|
+
break;
|
|
1213
|
+
}
|
|
1214
|
+
}
|
|
1215
|
+
return {
|
|
1216
|
+
overall: {
|
|
1217
|
+
score: overallPercentage,
|
|
1218
|
+
maxScore: 100,
|
|
1219
|
+
percentage: overallPercentage,
|
|
1220
|
+
grade: calculateGrade(overallPercentage)
|
|
1221
|
+
},
|
|
1222
|
+
byCategory: categoryScores,
|
|
1223
|
+
summary
|
|
1224
|
+
};
|
|
1225
|
+
}
|
|
1226
|
+
function initializeCategoryScores() {
|
|
1227
|
+
const scores = {};
|
|
1228
|
+
for (const category of CATEGORIES) {
|
|
1229
|
+
scores[category] = {
|
|
1230
|
+
category,
|
|
1231
|
+
score: 100,
|
|
1232
|
+
maxScore: 100,
|
|
1233
|
+
percentage: 100,
|
|
1234
|
+
issueCount: 0,
|
|
1235
|
+
uniqueRuleCount: 0,
|
|
1236
|
+
weightedIssueCount: 0,
|
|
1237
|
+
densityScore: 100,
|
|
1238
|
+
diversityScore: 100,
|
|
1239
|
+
bySeverity: {
|
|
1240
|
+
blocking: 0,
|
|
1241
|
+
risk: 0,
|
|
1242
|
+
"missing-info": 0,
|
|
1243
|
+
suggestion: 0
|
|
1244
|
+
}
|
|
1245
|
+
};
|
|
1246
|
+
}
|
|
1247
|
+
return scores;
|
|
1248
|
+
}
|
|
1249
|
+
function formatScoreSummary(report) {
|
|
1250
|
+
const lines = [];
|
|
1251
|
+
lines.push(`Overall: ${report.overall.grade} (${report.overall.percentage}%)`);
|
|
1252
|
+
lines.push("");
|
|
1253
|
+
lines.push("By Category:");
|
|
1254
|
+
for (const category of CATEGORIES) {
|
|
1255
|
+
const cat = report.byCategory[category];
|
|
1256
|
+
lines.push(` ${category}: ${cat.percentage}% (${cat.issueCount} issues, ${cat.uniqueRuleCount} rules)`);
|
|
1257
|
+
}
|
|
1258
|
+
lines.push("");
|
|
1259
|
+
lines.push("Issues:");
|
|
1260
|
+
lines.push(` Blocking: ${report.summary.blocking}`);
|
|
1261
|
+
lines.push(` Risk: ${report.summary.risk}`);
|
|
1262
|
+
lines.push(` Missing Info: ${report.summary.missingInfo}`);
|
|
1263
|
+
lines.push(` Suggestion: ${report.summary.suggestion}`);
|
|
1264
|
+
lines.push(` Total: ${report.summary.totalIssues}`);
|
|
1265
|
+
return lines.join("\n");
|
|
1266
|
+
}
|
|
1267
|
+
|
|
1268
|
+
// src/report-html/index.ts
|
|
1269
|
+
var GAUGE_R = 54;
|
|
1270
|
+
var GAUGE_C = Math.round(2 * Math.PI * GAUGE_R);
|
|
1271
|
+
var CATEGORY_DESCRIPTIONS = {
|
|
1272
|
+
layout: "Auto Layout, responsive constraints, nesting depth, absolute positioning",
|
|
1273
|
+
token: "Design token binding for colors, fonts, shadows, spacing grid",
|
|
1274
|
+
component: "Component reuse, detached instances, variant coverage",
|
|
1275
|
+
naming: "Semantic layer names, naming conventions, default names",
|
|
1276
|
+
"ai-readability": "Structure clarity for AI code generation, z-index, empty frames",
|
|
1277
|
+
"handoff-risk": "Hardcoded values, text truncation, image placeholders, dev status"
|
|
1278
|
+
};
|
|
1279
|
+
var SEVERITY_ORDER = ["blocking", "risk", "missing-info", "suggestion"];
|
|
1280
|
+
function gaugeColor(pct) {
|
|
1281
|
+
if (pct >= 75) return "#22c55e";
|
|
1282
|
+
if (pct >= 50) return "#f59e0b";
|
|
1283
|
+
return "#ef4444";
|
|
1284
|
+
}
|
|
1285
|
+
function severityBadge(sev) {
|
|
1286
|
+
const map = {
|
|
1287
|
+
blocking: "bg-red-500/10 text-red-600 border-red-500/20",
|
|
1288
|
+
risk: "bg-amber-500/10 text-amber-600 border-amber-500/20",
|
|
1289
|
+
"missing-info": "bg-zinc-500/10 text-zinc-600 border-zinc-500/20",
|
|
1290
|
+
suggestion: "bg-green-500/10 text-green-600 border-green-500/20"
|
|
1291
|
+
};
|
|
1292
|
+
return map[sev];
|
|
1293
|
+
}
|
|
1294
|
+
function scoreBadgeStyle(pct) {
|
|
1295
|
+
if (pct >= 75) return "bg-green-500/10 text-green-700 border-green-500/20";
|
|
1296
|
+
if (pct >= 50) return "bg-amber-500/10 text-amber-700 border-amber-500/20";
|
|
1297
|
+
return "bg-red-500/10 text-red-700 border-red-500/20";
|
|
1298
|
+
}
|
|
1299
|
+
function severityDot(sev) {
|
|
1300
|
+
const map = {
|
|
1301
|
+
blocking: "bg-red-500",
|
|
1302
|
+
risk: "bg-amber-500",
|
|
1303
|
+
"missing-info": "bg-zinc-400",
|
|
1304
|
+
suggestion: "bg-green-500"
|
|
1305
|
+
};
|
|
1306
|
+
return map[sev];
|
|
1307
|
+
}
|
|
1308
|
+
function generateHtmlReport(file, result, scores, options) {
|
|
1309
|
+
const screenshotMap = new Map(
|
|
1310
|
+
(options?.nodeScreenshots ?? []).map((ns) => [ns.nodeId, ns])
|
|
1311
|
+
);
|
|
1312
|
+
const figmaToken = options?.figmaToken;
|
|
1313
|
+
const quickWins = getQuickWins(result.issues, 5);
|
|
1314
|
+
const issuesByCategory = groupIssuesByCategory(result.issues);
|
|
1315
|
+
return `<!DOCTYPE html>
|
|
1316
|
+
<html lang="en" class="antialiased">
|
|
1317
|
+
<head>
|
|
1318
|
+
<meta charset="UTF-8">
|
|
1319
|
+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
1320
|
+
<title>CanICode Report \u2014 ${esc(file.name)}</title>
|
|
1321
|
+
<script src="https://cdn.tailwindcss.com"></script>
|
|
1322
|
+
<link rel="preconnect" href="https://fonts.googleapis.com">
|
|
1323
|
+
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
|
1324
|
+
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
|
|
1325
|
+
<script>
|
|
1326
|
+
tailwind.config = {
|
|
1327
|
+
theme: {
|
|
1328
|
+
extend: {
|
|
1329
|
+
fontFamily: { sans: ['Inter', 'ui-sans-serif', 'system-ui', '-apple-system', 'sans-serif'] },
|
|
1330
|
+
colors: {
|
|
1331
|
+
border: 'hsl(240 5.9% 90%)',
|
|
1332
|
+
ring: 'hsl(240 5.9% 10%)',
|
|
1333
|
+
background: 'hsl(0 0% 100%)',
|
|
1334
|
+
foreground: 'hsl(240 10% 3.9%)',
|
|
1335
|
+
muted: { DEFAULT: 'hsl(240 4.8% 95.9%)', foreground: 'hsl(240 3.8% 46.1%)' },
|
|
1336
|
+
card: { DEFAULT: 'hsl(0 0% 100%)', foreground: 'hsl(240 10% 3.9%)' },
|
|
1337
|
+
},
|
|
1338
|
+
borderRadius: { lg: '0.5rem', md: 'calc(0.5rem - 2px)', sm: 'calc(0.5rem - 4px)' },
|
|
1339
|
+
}
|
|
1340
|
+
}
|
|
1341
|
+
}
|
|
1342
|
+
</script>
|
|
1343
|
+
<style>
|
|
1344
|
+
details summary::-webkit-details-marker { display: none; }
|
|
1345
|
+
details summary::marker { content: ""; }
|
|
1346
|
+
details summary { list-style: none; }
|
|
1347
|
+
.gauge-fill { transition: stroke-dashoffset 0.8s cubic-bezier(0.4,0,0.2,1); }
|
|
1348
|
+
@media print {
|
|
1349
|
+
.no-print { display: none !important; }
|
|
1350
|
+
.topbar-print { position: static !important; background: white !important; color: hsl(240 10% 3.9%) !important; }
|
|
1351
|
+
}
|
|
1352
|
+
</style>
|
|
1353
|
+
</head>
|
|
1354
|
+
<body class="bg-muted font-sans text-foreground min-h-screen">
|
|
1355
|
+
|
|
1356
|
+
<!-- Top Bar -->
|
|
1357
|
+
<header class="topbar-print sticky top-0 z-50 bg-zinc-950 text-white border-b border-zinc-800">
|
|
1358
|
+
<div class="max-w-[960px] mx-auto px-6 py-3 flex items-center gap-4">
|
|
1359
|
+
<span class="font-semibold text-sm tracking-tight">CanICode</span>
|
|
1360
|
+
<span class="text-zinc-400 text-sm truncate">${esc(file.name)}</span>
|
|
1361
|
+
<span class="ml-auto text-zinc-500 text-xs no-print">${(/* @__PURE__ */ new Date()).toLocaleDateString()}</span>
|
|
1362
|
+
</div>
|
|
1363
|
+
</header>
|
|
1364
|
+
|
|
1365
|
+
<main class="max-w-[960px] mx-auto px-6 pb-16">
|
|
1366
|
+
|
|
1367
|
+
<!-- Overall Score -->
|
|
1368
|
+
<section class="flex flex-col items-center pt-12 pb-6">
|
|
1369
|
+
${renderGaugeSvg(scores.overall.percentage, 200, 10, scores.overall.grade)}
|
|
1370
|
+
<div class="mt-3 text-center">
|
|
1371
|
+
<span class="text-lg font-semibold">${scores.overall.percentage}</span>
|
|
1372
|
+
<span class="text-muted-foreground text-sm ml-1">/ 100</span>
|
|
1373
|
+
</div>
|
|
1374
|
+
<p class="text-muted-foreground text-sm mt-1">Overall Score</p>
|
|
1375
|
+
</section>
|
|
1376
|
+
|
|
1377
|
+
<!-- Category Gauges -->
|
|
1378
|
+
<section class="bg-card border border-border rounded-lg shadow-sm p-6 mb-6">
|
|
1379
|
+
<div class="grid grid-cols-3 sm:grid-cols-6 gap-4">
|
|
1380
|
+
${CATEGORIES.map((cat) => {
|
|
1381
|
+
const cs = scores.byCategory[cat];
|
|
1382
|
+
const desc = CATEGORY_DESCRIPTIONS[cat];
|
|
1383
|
+
return ` <div class="flex flex-col items-center group relative">
|
|
1384
|
+
${renderGaugeSvg(cs.percentage, 100, 7)}
|
|
1385
|
+
<span class="text-xs font-medium mt-2.5 text-center leading-tight">${CATEGORY_LABELS[cat]}</span>
|
|
1386
|
+
<span class="text-[11px] text-muted-foreground">${cs.issueCount} issues</span>
|
|
1387
|
+
<div class="absolute bottom-full mb-2 left-1/2 -translate-x-1/2 hidden group-hover:block bg-zinc-900 text-white text-xs px-3 py-2 rounded-md whitespace-nowrap z-10 shadow-lg pointer-events-none">
|
|
1388
|
+
${esc(desc)}
|
|
1389
|
+
<div class="absolute top-full left-1/2 -translate-x-1/2 border-4 border-transparent border-t-zinc-900"></div>
|
|
1390
|
+
</div>
|
|
1391
|
+
</div>`;
|
|
1392
|
+
}).join("\n")}
|
|
1393
|
+
</div>
|
|
1394
|
+
</section>
|
|
1395
|
+
|
|
1396
|
+
<!-- Issue Summary -->
|
|
1397
|
+
<section class="bg-card border border-border rounded-lg shadow-sm p-4 mb-6">
|
|
1398
|
+
<div class="flex flex-wrap items-center justify-center gap-6">
|
|
1399
|
+
${renderSummaryDot("bg-red-500", scores.summary.blocking, "Blocking")}
|
|
1400
|
+
${renderSummaryDot("bg-amber-500", scores.summary.risk, "Risk")}
|
|
1401
|
+
${renderSummaryDot("bg-zinc-400", scores.summary.missingInfo, "Missing Info")}
|
|
1402
|
+
${renderSummaryDot("bg-green-500", scores.summary.suggestion, "Suggestion")}
|
|
1403
|
+
<div class="border-l border-border pl-6 flex items-center gap-2">
|
|
1404
|
+
<span class="text-xl font-bold tracking-tight">${scores.summary.totalIssues}</span>
|
|
1405
|
+
<span class="text-sm text-muted-foreground">Total</span>
|
|
1406
|
+
</div>
|
|
1407
|
+
</div>
|
|
1408
|
+
</section>
|
|
1409
|
+
|
|
1410
|
+
${quickWins.length > 0 ? renderOpportunities(quickWins, file.fileKey) : ""}
|
|
1411
|
+
|
|
1412
|
+
<!-- Categories -->
|
|
1413
|
+
<div class="space-y-3">
|
|
1414
|
+
${CATEGORIES.map((cat) => renderCategory(cat, scores, issuesByCategory.get(cat) ?? [], file.fileKey, screenshotMap, figmaToken)).join("\n")}
|
|
1415
|
+
</div>
|
|
1416
|
+
|
|
1417
|
+
<!-- Footer -->
|
|
1418
|
+
<footer class="mt-12 pt-6 border-t border-border text-center">
|
|
1419
|
+
<p class="text-sm text-muted-foreground">Generated by <span class="font-semibold text-foreground">CanICode</span></p>
|
|
1420
|
+
<p class="text-xs text-muted-foreground/60 mt-1">${(/* @__PURE__ */ new Date()).toLocaleString()} \xB7 ${result.nodeCount} nodes \xB7 Max depth ${result.maxDepth}</p>
|
|
1421
|
+
</footer>
|
|
1422
|
+
|
|
1423
|
+
</main>
|
|
1424
|
+
|
|
1425
|
+
${figmaToken ? ` <script>
|
|
1426
|
+
const FIGMA_TOKEN = '${figmaToken}';
|
|
1427
|
+
async function postComment(btn) {
|
|
1428
|
+
const fileKey = btn.dataset.fileKey;
|
|
1429
|
+
const nodeId = btn.dataset.nodeId.replace(/-/g, ':');
|
|
1430
|
+
const rule = btn.dataset.rule;
|
|
1431
|
+
const message = btn.dataset.message;
|
|
1432
|
+
const path = btn.dataset.path;
|
|
1433
|
+
const fix = btn.dataset.fix;
|
|
1434
|
+
const why = btn.dataset.why;
|
|
1435
|
+
const impact = btn.dataset.impact;
|
|
1436
|
+
|
|
1437
|
+
const commentBody = '[CanICode] ' + rule + '\\n\\nFix: ' + fix + '\\nWhy: ' + why + '\\nImpact: ' + impact + '\\n\\n' + message + '\\nNode: ' + path;
|
|
1438
|
+
|
|
1439
|
+
btn.disabled = true;
|
|
1440
|
+
btn.textContent = 'Sending...';
|
|
1441
|
+
|
|
1442
|
+
try {
|
|
1443
|
+
const res = await fetch('https://api.figma.com/v1/files/' + fileKey + '/comments', {
|
|
1444
|
+
method: 'POST',
|
|
1445
|
+
headers: { 'X-FIGMA-TOKEN': FIGMA_TOKEN, 'Content-Type': 'application/json' },
|
|
1446
|
+
body: JSON.stringify({ message: commentBody, client_meta: { node_id: nodeId } }),
|
|
1447
|
+
});
|
|
1448
|
+
if (!res.ok) throw new Error(await res.text());
|
|
1449
|
+
btn.textContent = 'Sent \\u2713';
|
|
1450
|
+
btn.classList.remove('hover:bg-muted');
|
|
1451
|
+
btn.classList.add('text-green-600', 'border-green-500/30');
|
|
1452
|
+
} catch (e) {
|
|
1453
|
+
btn.textContent = 'Failed \\u2717';
|
|
1454
|
+
btn.classList.remove('hover:bg-muted');
|
|
1455
|
+
btn.classList.add('text-red-600', 'border-red-500/30');
|
|
1456
|
+
btn.disabled = false;
|
|
1457
|
+
console.error('Failed to post Figma comment:', e);
|
|
1458
|
+
}
|
|
1459
|
+
}
|
|
1460
|
+
</script>` : ""}
|
|
1461
|
+
</body>
|
|
1462
|
+
</html>`;
|
|
1463
|
+
}
|
|
1464
|
+
function renderGaugeSvg(pct, size, strokeW, grade) {
|
|
1465
|
+
const offset = GAUGE_C * (1 - pct / 100);
|
|
1466
|
+
const color = gaugeColor(pct);
|
|
1467
|
+
if (grade) {
|
|
1468
|
+
return `<svg width="${size}" height="${size}" viewBox="0 0 120 120" class="block">
|
|
1469
|
+
<circle cx="60" cy="60" r="${GAUGE_R}" fill="none" stroke-width="${strokeW}" class="stroke-border" />
|
|
1470
|
+
<circle cx="60" cy="60" r="${GAUGE_R}" fill="none" stroke="${color}" stroke-width="${strokeW}" stroke-linecap="round" stroke-dasharray="${GAUGE_C}" stroke-dashoffset="${offset}" transform="rotate(-90 60 60)" class="gauge-fill" />
|
|
1471
|
+
<text x="60" y="60" text-anchor="middle" dominant-baseline="central" fill="currentColor" font-size="52" font-weight="700" class="font-sans">${esc(grade)}</text>
|
|
1472
|
+
</svg>`;
|
|
1473
|
+
}
|
|
1474
|
+
const fontSize = 32;
|
|
1475
|
+
return `<svg width="${size}" height="${size}" viewBox="0 0 120 120" class="block">
|
|
1476
|
+
<circle cx="60" cy="60" r="${GAUGE_R}" fill="none" stroke-width="${strokeW}" class="stroke-border" />
|
|
1477
|
+
<circle cx="60" cy="60" r="${GAUGE_R}" fill="none" stroke="${color}" stroke-width="${strokeW}" stroke-linecap="round" stroke-dasharray="${GAUGE_C}" stroke-dashoffset="${offset}" transform="rotate(-90 60 60)" class="gauge-fill" />
|
|
1478
|
+
<text x="60" y="62" text-anchor="middle" dominant-baseline="central" fill="currentColor" font-size="${fontSize}" font-weight="700" class="font-sans">${pct}</text>
|
|
1479
|
+
</svg>`;
|
|
1480
|
+
}
|
|
1481
|
+
function renderSummaryDot(dotClass, count, label) {
|
|
1482
|
+
return `<div class="flex items-center gap-2">
|
|
1483
|
+
<span class="w-2.5 h-2.5 rounded-full ${dotClass}"></span>
|
|
1484
|
+
<span class="text-lg font-bold tracking-tight">${count}</span>
|
|
1485
|
+
<span class="text-sm text-muted-foreground">${label}</span>
|
|
1486
|
+
</div>`;
|
|
1487
|
+
}
|
|
1488
|
+
function renderOpportunities(issues, fileKey) {
|
|
1489
|
+
const maxAbs = issues.reduce((m, i) => Math.max(m, Math.abs(i.calculatedScore)), 1);
|
|
1490
|
+
return `
|
|
1491
|
+
<!-- Opportunities -->
|
|
1492
|
+
<section class="bg-card border border-border rounded-lg shadow-sm mb-6 overflow-hidden">
|
|
1493
|
+
<div class="px-6 py-4 border-b border-border">
|
|
1494
|
+
<h2 class="text-sm font-semibold flex items-center gap-2">
|
|
1495
|
+
<span class="w-2 h-2 rounded-full bg-red-500"></span>
|
|
1496
|
+
Opportunities
|
|
1497
|
+
</h2>
|
|
1498
|
+
<p class="text-xs text-muted-foreground mt-1">Top blocking issues \u2014 fix these first for the biggest improvement.</p>
|
|
1499
|
+
</div>
|
|
1500
|
+
<div class="divide-y divide-border">
|
|
1501
|
+
${issues.map((issue) => {
|
|
1502
|
+
const def = issue.rule.definition;
|
|
1503
|
+
const link = buildFigmaDeepLink(fileKey, issue.violation.nodeId);
|
|
1504
|
+
const barW = Math.round(Math.abs(issue.calculatedScore) / maxAbs * 100);
|
|
1505
|
+
return ` <div class="px-6 py-3 flex items-center gap-4 hover:bg-muted/50 transition-colors">
|
|
1506
|
+
<div class="flex-1 min-w-0">
|
|
1507
|
+
<div class="text-sm font-medium truncate">${esc(def.name)}</div>
|
|
1508
|
+
<div class="text-xs text-muted-foreground truncate mt-0.5">${esc(issue.violation.message)}</div>
|
|
1509
|
+
</div>
|
|
1510
|
+
<div class="w-32 flex items-center gap-2 shrink-0">
|
|
1511
|
+
<div class="flex-1 h-1.5 bg-muted rounded-full overflow-hidden">
|
|
1512
|
+
<div class="h-full bg-red-500 rounded-full" style="width:${barW}%"></div>
|
|
1513
|
+
</div>
|
|
1514
|
+
<span class="text-xs font-medium text-red-600 w-12 text-right">${issue.calculatedScore}</span>
|
|
1515
|
+
</div>
|
|
1516
|
+
<a href="${link}" target="_blank" rel="noopener" class="text-xs text-muted-foreground hover:text-foreground shrink-0 no-print">Figma \u2192</a>
|
|
1517
|
+
</div>`;
|
|
1518
|
+
}).join("\n")}
|
|
1519
|
+
</div>
|
|
1520
|
+
</section>`;
|
|
1521
|
+
}
|
|
1522
|
+
function renderCategory(cat, scores, issues, fileKey, screenshotMap, figmaToken) {
|
|
1523
|
+
const cs = scores.byCategory[cat];
|
|
1524
|
+
const hasProblems = issues.some((i) => i.config.severity === "blocking" || i.config.severity === "risk");
|
|
1525
|
+
const bySeverity = /* @__PURE__ */ new Map();
|
|
1526
|
+
for (const sev of SEVERITY_ORDER) bySeverity.set(sev, []);
|
|
1527
|
+
for (const issue of issues) bySeverity.get(issue.config.severity)?.push(issue);
|
|
1528
|
+
return `
|
|
1529
|
+
<details class="bg-card border border-border rounded-lg shadow-sm overflow-hidden group"${hasProblems ? " open" : ""}>
|
|
1530
|
+
<summary class="px-5 py-3.5 flex items-center gap-3 cursor-pointer hover:bg-muted/50 transition-colors select-none">
|
|
1531
|
+
<span class="inline-flex items-center justify-center w-10 h-6 rounded-md text-xs font-bold border ${scoreBadgeStyle(cs.percentage)}">${cs.percentage}</span>
|
|
1532
|
+
<div class="flex-1 min-w-0">
|
|
1533
|
+
<div class="text-sm font-semibold">${CATEGORY_LABELS[cat]}</div>
|
|
1534
|
+
<div class="text-xs text-muted-foreground">${esc(CATEGORY_DESCRIPTIONS[cat])}</div>
|
|
1535
|
+
</div>
|
|
1536
|
+
<span class="text-xs text-muted-foreground">${cs.issueCount} issues</span>
|
|
1537
|
+
<svg class="w-4 h-4 text-muted-foreground transition-transform group-open:rotate-180 shrink-0 no-print" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path d="M19 9l-7 7-7-7"/></svg>
|
|
1538
|
+
</summary>
|
|
1539
|
+
<div class="border-t border-border">
|
|
1540
|
+
${issues.length === 0 ? ' <div class="px-5 py-4 text-sm text-green-600 font-medium">No issues found</div>' : SEVERITY_ORDER.filter((sev) => (bySeverity.get(sev)?.length ?? 0) > 0).map((sev) => renderSeverityGroup(sev, bySeverity.get(sev) ?? [], fileKey, screenshotMap, figmaToken)).join("\n")}
|
|
1541
|
+
</div>
|
|
1542
|
+
</details>`;
|
|
1543
|
+
}
|
|
1544
|
+
function renderSeverityGroup(sev, issues, fileKey, screenshotMap, figmaToken) {
|
|
1545
|
+
return ` <div class="px-5 py-3">
|
|
1546
|
+
<div class="flex items-center gap-2 mb-2">
|
|
1547
|
+
<span class="w-2 h-2 rounded-full ${severityDot(sev)}"></span>
|
|
1548
|
+
<span class="text-xs font-semibold uppercase tracking-wider">${SEVERITY_LABELS[sev]}</span>
|
|
1549
|
+
<span class="text-xs text-muted-foreground ml-auto">${issues.length}</span>
|
|
1550
|
+
</div>
|
|
1551
|
+
<div class="space-y-1">
|
|
1552
|
+
${issues.map((issue) => renderIssueRow(issue, fileKey, screenshotMap, figmaToken)).join("\n")}
|
|
1553
|
+
</div>
|
|
1554
|
+
</div>`;
|
|
1555
|
+
}
|
|
1556
|
+
function renderIssueRow(issue, fileKey, screenshotMap, figmaToken) {
|
|
1557
|
+
const sev = issue.config.severity;
|
|
1558
|
+
const def = issue.rule.definition;
|
|
1559
|
+
const link = buildFigmaDeepLink(fileKey, issue.violation.nodeId);
|
|
1560
|
+
const screenshot = screenshotMap.get(issue.violation.nodeId);
|
|
1561
|
+
const screenshotHtml = screenshot ? `<div class="mt-3"><a href="${link}" target="_blank" rel="noopener"><img src="data:image/png;base64,${screenshot.screenshotBase64}" alt="${esc(screenshot.nodePath)}" class="max-w-[240px] border border-border rounded-md"></a></div>` : "";
|
|
1562
|
+
return ` <details class="border border-border rounded-md overflow-hidden">
|
|
1563
|
+
<summary class="flex items-center gap-2.5 px-3 py-2 text-sm cursor-pointer hover:bg-muted/50 transition-colors">
|
|
1564
|
+
<span class="w-1.5 h-1.5 rounded-full ${severityDot(sev)} shrink-0"></span>
|
|
1565
|
+
<span class="font-medium shrink-0">${esc(def.name)}</span>
|
|
1566
|
+
<span class="text-muted-foreground truncate text-xs flex-1">${esc(issue.violation.message)}</span>
|
|
1567
|
+
<span class="inline-flex items-center px-1.5 py-0.5 text-[10px] font-medium rounded border ${severityBadge(sev)} shrink-0">${issue.calculatedScore}</span>
|
|
1568
|
+
</summary>
|
|
1569
|
+
<div class="px-3 py-3 bg-muted/30 border-t border-border text-sm space-y-2">
|
|
1570
|
+
<div class="font-mono text-xs text-muted-foreground break-all">${esc(issue.violation.nodePath)}</div>
|
|
1571
|
+
<div class="text-muted-foreground leading-relaxed space-y-1">
|
|
1572
|
+
<p><span class="font-medium text-foreground">Why:</span> ${esc(def.why)}</p>
|
|
1573
|
+
<p><span class="font-medium text-foreground">Impact:</span> ${esc(def.impact)}</p>
|
|
1574
|
+
<p><span class="font-medium text-foreground">Fix:</span> ${esc(def.fix)}</p>
|
|
1575
|
+
</div>${screenshotHtml}
|
|
1576
|
+
<div class="flex items-center gap-2 mt-1 no-print">
|
|
1577
|
+
<a href="${link}" target="_blank" rel="noopener" class="inline-flex items-center gap-1 px-2.5 py-1 text-xs font-medium border border-border rounded-md hover:bg-muted transition-colors">Open in Figma <span>\u2192</span></a>${figmaToken ? `
|
|
1578
|
+
<button onclick="postComment(this)" data-file-key="${esc(fileKey)}" data-node-id="${esc(issue.violation.nodeId)}" data-rule="${esc(def.name)}" data-message="${esc(issue.violation.message)}" data-path="${esc(issue.violation.nodePath)}" data-fix="${esc(def.fix)}" data-why="${esc(def.why)}" data-impact="${esc(def.impact)}" class="inline-flex items-center gap-1 px-2.5 py-1 text-xs font-medium border border-border rounded-md hover:bg-muted transition-colors cursor-pointer">Comment on Figma</button>` : ""}
|
|
1579
|
+
</div>
|
|
1580
|
+
</div>
|
|
1581
|
+
</details>`;
|
|
1582
|
+
}
|
|
1583
|
+
function getQuickWins(issues, limit) {
|
|
1584
|
+
return issues.filter((issue) => issue.config.severity === "blocking").sort((a, b) => a.calculatedScore - b.calculatedScore).slice(0, limit);
|
|
1585
|
+
}
|
|
1586
|
+
function groupIssuesByCategory(issues) {
|
|
1587
|
+
const grouped = /* @__PURE__ */ new Map();
|
|
1588
|
+
for (const category of CATEGORIES) grouped.set(category, []);
|
|
1589
|
+
for (const issue of issues) grouped.get(issue.rule.definition.category).push(issue);
|
|
1590
|
+
return grouped;
|
|
1591
|
+
}
|
|
1592
|
+
function esc(text) {
|
|
1593
|
+
return text.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
|
1594
|
+
}
|
|
1595
|
+
var RuleOverrideSchema = z.object({
|
|
1596
|
+
score: z.number().int().max(0).optional(),
|
|
1597
|
+
severity: SeveritySchema.optional(),
|
|
1598
|
+
enabled: z.boolean().optional()
|
|
1599
|
+
});
|
|
1600
|
+
var ConfigFileSchema = z.object({
|
|
1601
|
+
excludeNodeTypes: z.array(z.string()).optional(),
|
|
1602
|
+
excludeNodeNames: z.array(z.string()).optional(),
|
|
1603
|
+
gridBase: z.number().int().positive().optional(),
|
|
1604
|
+
colorTolerance: z.number().int().positive().optional(),
|
|
1605
|
+
rules: z.record(z.string(), RuleOverrideSchema).optional()
|
|
1606
|
+
});
|
|
1607
|
+
async function loadConfigFile(filePath) {
|
|
1608
|
+
const absPath = resolve(filePath);
|
|
1609
|
+
const raw = await readFile(absPath, "utf-8");
|
|
1610
|
+
const parsed = JSON.parse(raw);
|
|
1611
|
+
return ConfigFileSchema.parse(parsed);
|
|
1612
|
+
}
|
|
1613
|
+
function mergeConfigs(base, overrides) {
|
|
1614
|
+
const merged = { ...base };
|
|
1615
|
+
if (overrides.gridBase !== void 0) {
|
|
1616
|
+
for (const [id, config2] of Object.entries(merged)) {
|
|
1617
|
+
if (config2.options && "gridBase" in config2.options) {
|
|
1618
|
+
merged[id] = {
|
|
1619
|
+
...config2,
|
|
1620
|
+
options: { ...config2.options, gridBase: overrides.gridBase }
|
|
1621
|
+
};
|
|
1622
|
+
}
|
|
1623
|
+
}
|
|
1624
|
+
}
|
|
1625
|
+
if (overrides.colorTolerance !== void 0) {
|
|
1626
|
+
for (const [id, config2] of Object.entries(merged)) {
|
|
1627
|
+
if (config2.options && "tolerance" in config2.options) {
|
|
1628
|
+
merged[id] = {
|
|
1629
|
+
...config2,
|
|
1630
|
+
options: { ...config2.options, tolerance: overrides.colorTolerance }
|
|
1631
|
+
};
|
|
1632
|
+
}
|
|
1633
|
+
}
|
|
1634
|
+
}
|
|
1635
|
+
if (overrides.rules) {
|
|
1636
|
+
for (const [ruleId, override] of Object.entries(overrides.rules)) {
|
|
1637
|
+
const existing = merged[ruleId];
|
|
1638
|
+
if (existing) {
|
|
1639
|
+
merged[ruleId] = {
|
|
1640
|
+
...existing,
|
|
1641
|
+
...override.score !== void 0 && { score: override.score },
|
|
1642
|
+
...override.severity !== void 0 && { severity: override.severity },
|
|
1643
|
+
...override.enabled !== void 0 && { enabled: override.enabled }
|
|
1644
|
+
};
|
|
1645
|
+
}
|
|
1646
|
+
}
|
|
1647
|
+
}
|
|
1648
|
+
return merged;
|
|
1649
|
+
}
|
|
1650
|
+
var CustomRuleSchema = z.object({
|
|
1651
|
+
id: z.string(),
|
|
1652
|
+
category: CategorySchema,
|
|
1653
|
+
severity: SeveritySchema,
|
|
1654
|
+
score: z.number().int().max(0),
|
|
1655
|
+
prompt: z.string(),
|
|
1656
|
+
why: z.string(),
|
|
1657
|
+
impact: z.string(),
|
|
1658
|
+
fix: z.string()
|
|
1659
|
+
});
|
|
1660
|
+
var CustomRulesFileSchema = z.array(CustomRuleSchema);
|
|
1661
|
+
|
|
1662
|
+
// src/rules/custom/custom-rule-loader.ts
|
|
1663
|
+
async function loadCustomRules(filePath) {
|
|
1664
|
+
const absPath = resolve(filePath);
|
|
1665
|
+
const raw = await readFile(absPath, "utf-8");
|
|
1666
|
+
const parsed = JSON.parse(raw);
|
|
1667
|
+
const customRules = CustomRulesFileSchema.parse(parsed);
|
|
1668
|
+
const rules = [];
|
|
1669
|
+
const configs = {};
|
|
1670
|
+
for (const cr of customRules) {
|
|
1671
|
+
rules.push(toRule(cr));
|
|
1672
|
+
configs[cr.id] = {
|
|
1673
|
+
severity: cr.severity,
|
|
1674
|
+
score: cr.score,
|
|
1675
|
+
enabled: true
|
|
1676
|
+
};
|
|
1677
|
+
}
|
|
1678
|
+
return { rules, configs };
|
|
1679
|
+
}
|
|
1680
|
+
function toRule(cr) {
|
|
1681
|
+
return {
|
|
1682
|
+
definition: {
|
|
1683
|
+
id: cr.id,
|
|
1684
|
+
name: cr.id.replace(/-/g, " ").replace(/\b\w/g, (c) => c.toUpperCase()),
|
|
1685
|
+
category: cr.category,
|
|
1686
|
+
why: cr.why,
|
|
1687
|
+
impact: cr.impact,
|
|
1688
|
+
fix: cr.fix
|
|
1689
|
+
},
|
|
1690
|
+
check: createPromptBasedCheck()
|
|
1691
|
+
};
|
|
1692
|
+
}
|
|
1693
|
+
function createPromptBasedCheck(_cr) {
|
|
1694
|
+
return (node, _context) => {
|
|
1695
|
+
if (node.type === "DOCUMENT" || node.type === "CANVAS") return null;
|
|
1696
|
+
return null;
|
|
1697
|
+
};
|
|
1698
|
+
}
|
|
1699
|
+
|
|
1700
|
+
// src/rules/layout/index.ts
|
|
1701
|
+
function isContainerNode(node) {
|
|
1702
|
+
return node.type === "FRAME" || node.type === "GROUP" || node.type === "COMPONENT";
|
|
1703
|
+
}
|
|
1704
|
+
function hasAutoLayout(node) {
|
|
1705
|
+
return node.layoutMode !== void 0 && node.layoutMode !== "NONE";
|
|
1706
|
+
}
|
|
1707
|
+
function hasTextContent(node) {
|
|
1708
|
+
return node.type === "TEXT" || (node.children?.some((c) => c.type === "TEXT") ?? false);
|
|
1709
|
+
}
|
|
1710
|
+
var noAutoLayoutDef = {
|
|
1711
|
+
id: "no-auto-layout",
|
|
1712
|
+
name: "No Auto Layout",
|
|
1713
|
+
category: "layout",
|
|
1714
|
+
why: "Frames without Auto Layout require manual positioning for every element",
|
|
1715
|
+
impact: "Layout breaks on content changes, harder to maintain and scale",
|
|
1716
|
+
fix: "Apply Auto Layout to the frame with appropriate direction and spacing"
|
|
1717
|
+
};
|
|
1718
|
+
var noAutoLayoutCheck = (node, context) => {
|
|
1719
|
+
if (node.type !== "FRAME") return null;
|
|
1720
|
+
if (hasAutoLayout(node)) return null;
|
|
1721
|
+
if (!node.children || node.children.length === 0) return null;
|
|
1722
|
+
return {
|
|
1723
|
+
ruleId: noAutoLayoutDef.id,
|
|
1724
|
+
nodeId: node.id,
|
|
1725
|
+
nodePath: context.path.join(" > "),
|
|
1726
|
+
message: `Frame "${node.name}" has no Auto Layout`
|
|
1727
|
+
};
|
|
1728
|
+
};
|
|
1729
|
+
defineRule({
|
|
1730
|
+
definition: noAutoLayoutDef,
|
|
1731
|
+
check: noAutoLayoutCheck
|
|
1732
|
+
});
|
|
1733
|
+
var absolutePositionInAutoLayoutDef = {
|
|
1734
|
+
id: "absolute-position-in-auto-layout",
|
|
1735
|
+
name: "Absolute Position in Auto Layout",
|
|
1736
|
+
category: "layout",
|
|
1737
|
+
why: "Absolute positioning inside Auto Layout breaks the automatic flow",
|
|
1738
|
+
impact: "Element will not respond to sibling changes, may overlap unexpectedly",
|
|
1739
|
+
fix: "Remove absolute positioning or use proper Auto Layout alignment"
|
|
1740
|
+
};
|
|
1741
|
+
var INTENTIONAL_ABSOLUTE_PATTERNS = /^(badge|close|dismiss|overlay|float|fab|dot|indicator|corner|decoration|tag|status|notification|x|icon[-_ ]?(close|dismiss|x)|btn[-_ ]?(close|dismiss))/i;
|
|
1742
|
+
function isSmallRelativeToParent(node, parent) {
|
|
1743
|
+
const nodeBB = node.absoluteBoundingBox;
|
|
1744
|
+
const parentBB = parent.absoluteBoundingBox;
|
|
1745
|
+
if (!nodeBB || !parentBB) return false;
|
|
1746
|
+
if (parentBB.width === 0 || parentBB.height === 0) return false;
|
|
1747
|
+
const widthRatio = nodeBB.width / parentBB.width;
|
|
1748
|
+
const heightRatio = nodeBB.height / parentBB.height;
|
|
1749
|
+
return widthRatio < 0.25 && heightRatio < 0.25;
|
|
1750
|
+
}
|
|
1751
|
+
var absolutePositionInAutoLayoutCheck = (node, context) => {
|
|
1752
|
+
if (!context.parent) return null;
|
|
1753
|
+
if (!hasAutoLayout(context.parent)) return null;
|
|
1754
|
+
if (node.layoutPositioning !== "ABSOLUTE") return null;
|
|
1755
|
+
if (INTENTIONAL_ABSOLUTE_PATTERNS.test(node.name)) return null;
|
|
1756
|
+
if (isSmallRelativeToParent(node, context.parent)) return null;
|
|
1757
|
+
if (context.parent.type === "COMPONENT") return null;
|
|
1758
|
+
return {
|
|
1759
|
+
ruleId: absolutePositionInAutoLayoutDef.id,
|
|
1760
|
+
nodeId: node.id,
|
|
1761
|
+
nodePath: context.path.join(" > "),
|
|
1762
|
+
message: `"${node.name}" uses absolute positioning inside Auto Layout parent "${context.parent.name}". If intentional (badge, overlay, close button), rename to badge-*, overlay-*, close-* to suppress this warning.`
|
|
1763
|
+
};
|
|
1764
|
+
};
|
|
1765
|
+
defineRule({
|
|
1766
|
+
definition: absolutePositionInAutoLayoutDef,
|
|
1767
|
+
check: absolutePositionInAutoLayoutCheck
|
|
1768
|
+
});
|
|
1769
|
+
var fixedWidthInResponsiveContextDef = {
|
|
1770
|
+
id: "fixed-width-in-responsive-context",
|
|
1771
|
+
name: "Fixed Width in Responsive Context",
|
|
1772
|
+
category: "layout",
|
|
1773
|
+
why: "Fixed width inside Auto Layout prevents responsive behavior",
|
|
1774
|
+
impact: "Content will not adapt to container size changes",
|
|
1775
|
+
fix: "Use 'Fill' or 'Hug' instead of fixed width"
|
|
1776
|
+
};
|
|
1777
|
+
var fixedWidthInResponsiveContextCheck = (node, context) => {
|
|
1778
|
+
if (!context.parent) return null;
|
|
1779
|
+
if (!hasAutoLayout(context.parent)) return null;
|
|
1780
|
+
if (!isContainerNode(node)) return null;
|
|
1781
|
+
if (node.layoutAlign === "STRETCH") return null;
|
|
1782
|
+
const bbox = node.absoluteBoundingBox;
|
|
1783
|
+
if (!bbox) return null;
|
|
1784
|
+
if (node.layoutAlign !== "INHERIT") return null;
|
|
1785
|
+
return {
|
|
1786
|
+
ruleId: fixedWidthInResponsiveContextDef.id,
|
|
1787
|
+
nodeId: node.id,
|
|
1788
|
+
nodePath: context.path.join(" > "),
|
|
1789
|
+
message: `"${node.name}" has fixed width inside Auto Layout`
|
|
1790
|
+
};
|
|
1791
|
+
};
|
|
1792
|
+
defineRule({
|
|
1793
|
+
definition: fixedWidthInResponsiveContextDef,
|
|
1794
|
+
check: fixedWidthInResponsiveContextCheck
|
|
1795
|
+
});
|
|
1796
|
+
var missingResponsiveBehaviorDef = {
|
|
1797
|
+
id: "missing-responsive-behavior",
|
|
1798
|
+
name: "Missing Responsive Behavior",
|
|
1799
|
+
category: "layout",
|
|
1800
|
+
why: "Elements without constraints won't adapt to different screen sizes",
|
|
1801
|
+
impact: "Layout will break or look wrong on different devices",
|
|
1802
|
+
fix: "Set appropriate constraints (left/right, top/bottom, scale, etc.)"
|
|
1803
|
+
};
|
|
1804
|
+
var missingResponsiveBehaviorCheck = (node, context) => {
|
|
1805
|
+
if (!isContainerNode(node)) return null;
|
|
1806
|
+
if (context.parent && hasAutoLayout(context.parent)) return null;
|
|
1807
|
+
if (context.depth < 2) return null;
|
|
1808
|
+
if (!hasAutoLayout(node) && !node.layoutAlign) {
|
|
1809
|
+
return {
|
|
1810
|
+
ruleId: missingResponsiveBehaviorDef.id,
|
|
1811
|
+
nodeId: node.id,
|
|
1812
|
+
nodePath: context.path.join(" > "),
|
|
1813
|
+
message: `"${node.name}" has no responsive behavior configured`
|
|
1814
|
+
};
|
|
1815
|
+
}
|
|
1816
|
+
return null;
|
|
1817
|
+
};
|
|
1818
|
+
defineRule({
|
|
1819
|
+
definition: missingResponsiveBehaviorDef,
|
|
1820
|
+
check: missingResponsiveBehaviorCheck
|
|
1821
|
+
});
|
|
1822
|
+
var groupUsageDef = {
|
|
1823
|
+
id: "group-usage",
|
|
1824
|
+
name: "Group Usage",
|
|
1825
|
+
category: "layout",
|
|
1826
|
+
why: "Groups don't support Auto Layout and have limited layout control",
|
|
1827
|
+
impact: "Harder to maintain consistent spacing and alignment",
|
|
1828
|
+
fix: "Convert Group to Frame and apply Auto Layout"
|
|
1829
|
+
};
|
|
1830
|
+
var groupUsageCheck = (node, context) => {
|
|
1831
|
+
if (node.type !== "GROUP") return null;
|
|
1832
|
+
return {
|
|
1833
|
+
ruleId: groupUsageDef.id,
|
|
1834
|
+
nodeId: node.id,
|
|
1835
|
+
nodePath: context.path.join(" > "),
|
|
1836
|
+
message: `"${node.name}" is a Group - consider converting to Frame with Auto Layout`
|
|
1837
|
+
};
|
|
1838
|
+
};
|
|
1839
|
+
defineRule({
|
|
1840
|
+
definition: groupUsageDef,
|
|
1841
|
+
check: groupUsageCheck
|
|
1842
|
+
});
|
|
1843
|
+
var fixedSizeInAutoLayoutDef = {
|
|
1844
|
+
id: "fixed-size-in-auto-layout",
|
|
1845
|
+
name: "Fixed Size in Auto Layout",
|
|
1846
|
+
category: "layout",
|
|
1847
|
+
why: "Fixed sizes inside Auto Layout limit flexibility",
|
|
1848
|
+
impact: "Element won't adapt to content or container changes",
|
|
1849
|
+
fix: "Consider using 'Hug' for content-driven sizing"
|
|
1850
|
+
};
|
|
1851
|
+
var fixedSizeInAutoLayoutCheck = (node, context) => {
|
|
1852
|
+
if (!context.parent) return null;
|
|
1853
|
+
if (!hasAutoLayout(context.parent)) return null;
|
|
1854
|
+
if (!isContainerNode(node)) return null;
|
|
1855
|
+
if (!node.absoluteBoundingBox) return null;
|
|
1856
|
+
const { width, height } = node.absoluteBoundingBox;
|
|
1857
|
+
if (width <= 48 && height <= 48) return null;
|
|
1858
|
+
return null;
|
|
1859
|
+
};
|
|
1860
|
+
defineRule({
|
|
1861
|
+
definition: fixedSizeInAutoLayoutDef,
|
|
1862
|
+
check: fixedSizeInAutoLayoutCheck
|
|
1863
|
+
});
|
|
1864
|
+
var missingMinWidthDef = {
|
|
1865
|
+
id: "missing-min-width",
|
|
1866
|
+
name: "Missing Min Width",
|
|
1867
|
+
category: "layout",
|
|
1868
|
+
why: "Without min-width, containers can collapse to unusable sizes",
|
|
1869
|
+
impact: "Text truncation or layout collapse on narrow screens",
|
|
1870
|
+
fix: "Set a minimum width constraint on the container"
|
|
1871
|
+
};
|
|
1872
|
+
var missingMinWidthCheck = (node, context) => {
|
|
1873
|
+
if (!isContainerNode(node) && !hasTextContent(node)) return null;
|
|
1874
|
+
if (node.absoluteBoundingBox) {
|
|
1875
|
+
const { width, height } = node.absoluteBoundingBox;
|
|
1876
|
+
if (width <= 48 && height <= 24) return null;
|
|
1877
|
+
}
|
|
1878
|
+
if (!context.parent || !hasAutoLayout(context.parent)) return null;
|
|
1879
|
+
return null;
|
|
1880
|
+
};
|
|
1881
|
+
defineRule({
|
|
1882
|
+
definition: missingMinWidthDef,
|
|
1883
|
+
check: missingMinWidthCheck
|
|
1884
|
+
});
|
|
1885
|
+
var missingMaxWidthDef = {
|
|
1886
|
+
id: "missing-max-width",
|
|
1887
|
+
name: "Missing Max Width",
|
|
1888
|
+
category: "layout",
|
|
1889
|
+
why: "Without max-width, content can stretch too wide on large screens",
|
|
1890
|
+
impact: "Poor readability and layout on wide screens",
|
|
1891
|
+
fix: "Set a maximum width constraint, especially for text containers"
|
|
1892
|
+
};
|
|
1893
|
+
var missingMaxWidthCheck = (node, _context) => {
|
|
1894
|
+
if (!isContainerNode(node) && !hasTextContent(node)) return null;
|
|
1895
|
+
if (node.absoluteBoundingBox) {
|
|
1896
|
+
const { width } = node.absoluteBoundingBox;
|
|
1897
|
+
if (width <= 200) return null;
|
|
1898
|
+
}
|
|
1899
|
+
return null;
|
|
1900
|
+
};
|
|
1901
|
+
defineRule({
|
|
1902
|
+
definition: missingMaxWidthDef,
|
|
1903
|
+
check: missingMaxWidthCheck
|
|
1904
|
+
});
|
|
1905
|
+
var deepNestingDef = {
|
|
1906
|
+
id: "deep-nesting",
|
|
1907
|
+
name: "Deep Nesting",
|
|
1908
|
+
category: "layout",
|
|
1909
|
+
why: "Deep nesting makes the structure hard to understand and maintain",
|
|
1910
|
+
impact: "Increases complexity, harder to debug layout issues",
|
|
1911
|
+
fix: "Flatten the structure by removing unnecessary wrapper frames"
|
|
1912
|
+
};
|
|
1913
|
+
var deepNestingCheck = (node, context, options) => {
|
|
1914
|
+
const maxDepth = options?.["maxDepth"] ?? getRuleOption("deep-nesting", "maxDepth", 5);
|
|
1915
|
+
if (context.depth < maxDepth) return null;
|
|
1916
|
+
if (!isContainerNode(node)) return null;
|
|
1917
|
+
return {
|
|
1918
|
+
ruleId: deepNestingDef.id,
|
|
1919
|
+
nodeId: node.id,
|
|
1920
|
+
nodePath: context.path.join(" > "),
|
|
1921
|
+
message: `"${node.name}" is nested ${context.depth} levels deep (max: ${maxDepth})`
|
|
1922
|
+
};
|
|
1923
|
+
};
|
|
1924
|
+
defineRule({
|
|
1925
|
+
definition: deepNestingDef,
|
|
1926
|
+
check: deepNestingCheck
|
|
1927
|
+
});
|
|
1928
|
+
var overflowHiddenAbuseDef = {
|
|
1929
|
+
id: "overflow-hidden-abuse",
|
|
1930
|
+
name: "Overflow Hidden Abuse",
|
|
1931
|
+
category: "layout",
|
|
1932
|
+
why: "Using clip content to hide layout problems masks underlying issues",
|
|
1933
|
+
impact: "Content may be unintentionally cut off, problems harder to diagnose",
|
|
1934
|
+
fix: "Fix the underlying layout issue instead of hiding overflow"
|
|
1935
|
+
};
|
|
1936
|
+
var overflowHiddenAbuseCheck = (_node, _context) => {
|
|
1937
|
+
return null;
|
|
1938
|
+
};
|
|
1939
|
+
defineRule({
|
|
1940
|
+
definition: overflowHiddenAbuseDef,
|
|
1941
|
+
check: overflowHiddenAbuseCheck
|
|
1942
|
+
});
|
|
1943
|
+
var inconsistentSiblingLayoutDirectionDef = {
|
|
1944
|
+
id: "inconsistent-sibling-layout-direction",
|
|
1945
|
+
name: "Inconsistent Sibling Layout Direction",
|
|
1946
|
+
category: "layout",
|
|
1947
|
+
why: "Sibling containers with mixed layout directions without clear reason create confusion",
|
|
1948
|
+
impact: "Harder to understand and maintain the design structure",
|
|
1949
|
+
fix: "Use consistent layout direction for similar sibling elements"
|
|
1950
|
+
};
|
|
1951
|
+
var inconsistentSiblingLayoutDirectionCheck = (node, context) => {
|
|
1952
|
+
if (!isContainerNode(node)) return null;
|
|
1953
|
+
if (!context.siblings || context.siblings.length < 2) return null;
|
|
1954
|
+
const siblingContainers = context.siblings.filter(
|
|
1955
|
+
(s) => isContainerNode(s) && s.id !== node.id
|
|
1956
|
+
);
|
|
1957
|
+
if (siblingContainers.length === 0) return null;
|
|
1958
|
+
const myDirection = node.layoutMode;
|
|
1959
|
+
if (!myDirection || myDirection === "NONE") return null;
|
|
1960
|
+
const siblingDirections = siblingContainers.map((s) => s.layoutMode).filter((d) => d && d !== "NONE");
|
|
1961
|
+
if (siblingDirections.length === 0) return null;
|
|
1962
|
+
const allSameSiblingDirection = siblingDirections.every(
|
|
1963
|
+
(d) => d === siblingDirections[0]
|
|
1964
|
+
);
|
|
1965
|
+
if (allSameSiblingDirection && siblingDirections[0] !== myDirection) {
|
|
1966
|
+
if (context.parent?.layoutMode === "HORIZONTAL" && myDirection === "VERTICAL") {
|
|
1967
|
+
return null;
|
|
1968
|
+
}
|
|
1969
|
+
return {
|
|
1970
|
+
ruleId: inconsistentSiblingLayoutDirectionDef.id,
|
|
1971
|
+
nodeId: node.id,
|
|
1972
|
+
nodePath: context.path.join(" > "),
|
|
1973
|
+
message: `"${node.name}" has ${myDirection} layout while siblings use ${siblingDirections[0]}`
|
|
1974
|
+
};
|
|
1975
|
+
}
|
|
1976
|
+
return null;
|
|
1977
|
+
};
|
|
1978
|
+
defineRule({
|
|
1979
|
+
definition: inconsistentSiblingLayoutDirectionDef,
|
|
1980
|
+
check: inconsistentSiblingLayoutDirectionCheck
|
|
1981
|
+
});
|
|
1982
|
+
|
|
1983
|
+
// src/rules/token/index.ts
|
|
1984
|
+
function hasStyleReference(node, styleType) {
|
|
1985
|
+
return node.styles !== void 0 && styleType in node.styles;
|
|
1986
|
+
}
|
|
1987
|
+
function hasBoundVariable(node, key) {
|
|
1988
|
+
return node.boundVariables !== void 0 && key in node.boundVariables;
|
|
1989
|
+
}
|
|
1990
|
+
function isOnGrid(value, gridBase) {
|
|
1991
|
+
return value % gridBase === 0;
|
|
1992
|
+
}
|
|
1993
|
+
var rawColorDef = {
|
|
1994
|
+
id: "raw-color",
|
|
1995
|
+
name: "Raw Color",
|
|
1996
|
+
category: "token",
|
|
1997
|
+
why: "Raw hex colors are not connected to the design system",
|
|
1998
|
+
impact: "Color changes require manual updates across the entire design",
|
|
1999
|
+
fix: "Use a color style or variable instead of raw hex values"
|
|
2000
|
+
};
|
|
2001
|
+
var rawColorCheck = (node, context) => {
|
|
2002
|
+
if (!node.fills || !Array.isArray(node.fills)) return null;
|
|
2003
|
+
if (node.fills.length === 0) return null;
|
|
2004
|
+
if (hasStyleReference(node, "fill")) return null;
|
|
2005
|
+
if (hasBoundVariable(node, "fills")) return null;
|
|
2006
|
+
for (const fill of node.fills) {
|
|
2007
|
+
const fillObj = fill;
|
|
2008
|
+
if (fillObj["type"] === "SOLID" && fillObj["color"]) {
|
|
2009
|
+
return {
|
|
2010
|
+
ruleId: rawColorDef.id,
|
|
2011
|
+
nodeId: node.id,
|
|
2012
|
+
nodePath: context.path.join(" > "),
|
|
2013
|
+
message: `"${node.name}" uses raw color without style or variable`
|
|
2014
|
+
};
|
|
2015
|
+
}
|
|
2016
|
+
}
|
|
2017
|
+
return null;
|
|
2018
|
+
};
|
|
2019
|
+
defineRule({
|
|
2020
|
+
definition: rawColorDef,
|
|
2021
|
+
check: rawColorCheck
|
|
2022
|
+
});
|
|
2023
|
+
var rawFontDef = {
|
|
2024
|
+
id: "raw-font",
|
|
2025
|
+
name: "Raw Font",
|
|
2026
|
+
category: "token",
|
|
2027
|
+
why: "Text without text styles is disconnected from the type system",
|
|
2028
|
+
impact: "Typography changes require manual updates across the design",
|
|
2029
|
+
fix: "Apply a text style to maintain consistency"
|
|
2030
|
+
};
|
|
2031
|
+
var rawFontCheck = (node, context) => {
|
|
2032
|
+
if (node.type !== "TEXT") return null;
|
|
2033
|
+
if (hasStyleReference(node, "text")) return null;
|
|
2034
|
+
if (hasBoundVariable(node, "fontFamily") || hasBoundVariable(node, "fontSize")) {
|
|
2035
|
+
return null;
|
|
2036
|
+
}
|
|
2037
|
+
return {
|
|
2038
|
+
ruleId: rawFontDef.id,
|
|
2039
|
+
nodeId: node.id,
|
|
2040
|
+
nodePath: context.path.join(" > "),
|
|
2041
|
+
message: `"${node.name}" has no text style applied`
|
|
2042
|
+
};
|
|
2043
|
+
};
|
|
2044
|
+
defineRule({
|
|
2045
|
+
definition: rawFontDef,
|
|
2046
|
+
check: rawFontCheck
|
|
2047
|
+
});
|
|
2048
|
+
var inconsistentSpacingDef = {
|
|
2049
|
+
id: "inconsistent-spacing",
|
|
2050
|
+
name: "Inconsistent Spacing",
|
|
2051
|
+
category: "token",
|
|
2052
|
+
why: "Spacing values outside the grid system break visual consistency",
|
|
2053
|
+
impact: "Inconsistent visual rhythm and harder to maintain",
|
|
2054
|
+
fix: "Use spacing values from the design system grid (e.g., 8pt increments)"
|
|
2055
|
+
};
|
|
2056
|
+
var inconsistentSpacingCheck = (node, context, options) => {
|
|
2057
|
+
const gridBase = options?.["gridBase"] ?? getRuleOption("inconsistent-spacing", "gridBase", 8);
|
|
2058
|
+
const paddings = [
|
|
2059
|
+
node.paddingLeft,
|
|
2060
|
+
node.paddingRight,
|
|
2061
|
+
node.paddingTop,
|
|
2062
|
+
node.paddingBottom
|
|
2063
|
+
].filter((p) => p !== void 0 && p > 0);
|
|
2064
|
+
for (const padding of paddings) {
|
|
2065
|
+
if (!isOnGrid(padding, gridBase)) {
|
|
2066
|
+
return {
|
|
2067
|
+
ruleId: inconsistentSpacingDef.id,
|
|
2068
|
+
nodeId: node.id,
|
|
2069
|
+
nodePath: context.path.join(" > "),
|
|
2070
|
+
message: `"${node.name}" has padding ${padding}px not on ${gridBase}pt grid`
|
|
2071
|
+
};
|
|
2072
|
+
}
|
|
2073
|
+
}
|
|
2074
|
+
if (node.itemSpacing !== void 0 && node.itemSpacing > 0) {
|
|
2075
|
+
if (!isOnGrid(node.itemSpacing, gridBase)) {
|
|
2076
|
+
return {
|
|
2077
|
+
ruleId: inconsistentSpacingDef.id,
|
|
2078
|
+
nodeId: node.id,
|
|
2079
|
+
nodePath: context.path.join(" > "),
|
|
2080
|
+
message: `"${node.name}" has item spacing ${node.itemSpacing}px not on ${gridBase}pt grid`
|
|
2081
|
+
};
|
|
2082
|
+
}
|
|
2083
|
+
}
|
|
2084
|
+
return null;
|
|
2085
|
+
};
|
|
2086
|
+
defineRule({
|
|
2087
|
+
definition: inconsistentSpacingDef,
|
|
2088
|
+
check: inconsistentSpacingCheck
|
|
2089
|
+
});
|
|
2090
|
+
var magicNumberSpacingDef = {
|
|
2091
|
+
id: "magic-number-spacing",
|
|
2092
|
+
name: "Magic Number Spacing",
|
|
2093
|
+
category: "token",
|
|
2094
|
+
why: "Arbitrary spacing values make the system harder to understand",
|
|
2095
|
+
impact: "Unpredictable spacing, harder to create consistent layouts",
|
|
2096
|
+
fix: "Round spacing to the nearest grid value or use spacing tokens"
|
|
2097
|
+
};
|
|
2098
|
+
var magicNumberSpacingCheck = (node, context, options) => {
|
|
2099
|
+
const gridBase = options?.["gridBase"] ?? getRuleOption("magic-number-spacing", "gridBase", 8);
|
|
2100
|
+
const allSpacings = [
|
|
2101
|
+
node.paddingLeft,
|
|
2102
|
+
node.paddingRight,
|
|
2103
|
+
node.paddingTop,
|
|
2104
|
+
node.paddingBottom,
|
|
2105
|
+
node.itemSpacing
|
|
2106
|
+
].filter((s) => s !== void 0 && s > 0);
|
|
2107
|
+
for (const spacing of allSpacings) {
|
|
2108
|
+
const commonValues = [1, 2, 4];
|
|
2109
|
+
if (!isOnGrid(spacing, gridBase) && !commonValues.includes(spacing)) {
|
|
2110
|
+
if (spacing % 2 !== 0 && spacing > 4) {
|
|
2111
|
+
return {
|
|
2112
|
+
ruleId: magicNumberSpacingDef.id,
|
|
2113
|
+
nodeId: node.id,
|
|
2114
|
+
nodePath: context.path.join(" > "),
|
|
2115
|
+
message: `"${node.name}" uses magic number spacing: ${spacing}px`
|
|
2116
|
+
};
|
|
2117
|
+
}
|
|
2118
|
+
}
|
|
2119
|
+
}
|
|
2120
|
+
return null;
|
|
2121
|
+
};
|
|
2122
|
+
defineRule({
|
|
2123
|
+
definition: magicNumberSpacingDef,
|
|
2124
|
+
check: magicNumberSpacingCheck
|
|
2125
|
+
});
|
|
2126
|
+
var rawShadowDef = {
|
|
2127
|
+
id: "raw-shadow",
|
|
2128
|
+
name: "Raw Shadow",
|
|
2129
|
+
category: "token",
|
|
2130
|
+
why: "Shadow effects without styles are disconnected from the design system",
|
|
2131
|
+
impact: "Shadow changes require manual updates across the design",
|
|
2132
|
+
fix: "Create and apply an effect style for shadows"
|
|
2133
|
+
};
|
|
2134
|
+
var rawShadowCheck = (node, context) => {
|
|
2135
|
+
if (!node.effects || !Array.isArray(node.effects)) return null;
|
|
2136
|
+
if (node.effects.length === 0) return null;
|
|
2137
|
+
if (hasStyleReference(node, "effect")) return null;
|
|
2138
|
+
for (const effect of node.effects) {
|
|
2139
|
+
const effectObj = effect;
|
|
2140
|
+
if (effectObj["type"] === "DROP_SHADOW" || effectObj["type"] === "INNER_SHADOW") {
|
|
2141
|
+
return {
|
|
2142
|
+
ruleId: rawShadowDef.id,
|
|
2143
|
+
nodeId: node.id,
|
|
2144
|
+
nodePath: context.path.join(" > "),
|
|
2145
|
+
message: `"${node.name}" has shadow effect without effect style`
|
|
2146
|
+
};
|
|
2147
|
+
}
|
|
2148
|
+
}
|
|
2149
|
+
return null;
|
|
2150
|
+
};
|
|
2151
|
+
defineRule({
|
|
2152
|
+
definition: rawShadowDef,
|
|
2153
|
+
check: rawShadowCheck
|
|
2154
|
+
});
|
|
2155
|
+
var rawOpacityDef = {
|
|
2156
|
+
id: "raw-opacity",
|
|
2157
|
+
name: "Raw Opacity",
|
|
2158
|
+
category: "token",
|
|
2159
|
+
why: "Hardcoded opacity values are not connected to design tokens",
|
|
2160
|
+
impact: "Opacity changes require manual updates",
|
|
2161
|
+
fix: "Use opacity variables or consider if opacity is truly needed"
|
|
2162
|
+
};
|
|
2163
|
+
var rawOpacityCheck = (node, _context) => {
|
|
2164
|
+
if (hasBoundVariable(node, "opacity")) return null;
|
|
2165
|
+
return null;
|
|
2166
|
+
};
|
|
2167
|
+
defineRule({
|
|
2168
|
+
definition: rawOpacityDef,
|
|
2169
|
+
check: rawOpacityCheck
|
|
2170
|
+
});
|
|
2171
|
+
var multipleFillColorsDef = {
|
|
2172
|
+
id: "multiple-fill-colors",
|
|
2173
|
+
name: "Multiple Fill Colors",
|
|
2174
|
+
category: "token",
|
|
2175
|
+
why: "Similar but slightly different colors indicate inconsistent token usage",
|
|
2176
|
+
impact: "Visual inconsistency and harder to maintain brand colors",
|
|
2177
|
+
fix: "Consolidate to a single color token or style"
|
|
2178
|
+
};
|
|
2179
|
+
var multipleFillColorsCheck = (_node, _context, _options) => {
|
|
2180
|
+
return null;
|
|
2181
|
+
};
|
|
2182
|
+
defineRule({
|
|
2183
|
+
definition: multipleFillColorsDef,
|
|
2184
|
+
check: multipleFillColorsCheck
|
|
2185
|
+
});
|
|
2186
|
+
|
|
2187
|
+
// src/rules/component/index.ts
|
|
2188
|
+
function isComponentInstance(node) {
|
|
2189
|
+
return node.type === "INSTANCE";
|
|
2190
|
+
}
|
|
2191
|
+
function isComponent(node) {
|
|
2192
|
+
return node.type === "COMPONENT" || node.type === "COMPONENT_SET";
|
|
2193
|
+
}
|
|
2194
|
+
function collectFrameNames(node, names = /* @__PURE__ */ new Map()) {
|
|
2195
|
+
if (node.type === "FRAME" && node.name) {
|
|
2196
|
+
const existing = names.get(node.name) ?? [];
|
|
2197
|
+
existing.push(node.id);
|
|
2198
|
+
names.set(node.name, existing);
|
|
2199
|
+
}
|
|
2200
|
+
if (node.children) {
|
|
2201
|
+
for (const child of node.children) {
|
|
2202
|
+
collectFrameNames(child, names);
|
|
2203
|
+
}
|
|
2204
|
+
}
|
|
2205
|
+
return names;
|
|
2206
|
+
}
|
|
2207
|
+
var missingComponentDef = {
|
|
2208
|
+
id: "missing-component",
|
|
2209
|
+
name: "Missing Component",
|
|
2210
|
+
category: "component",
|
|
2211
|
+
why: "Repeated identical structures should be componentized",
|
|
2212
|
+
impact: "Changes require manual updates in multiple places",
|
|
2213
|
+
fix: "Create a component from the repeated structure"
|
|
2214
|
+
};
|
|
2215
|
+
var missingComponentCheck = (node, context, options) => {
|
|
2216
|
+
if (node.type !== "FRAME") return null;
|
|
2217
|
+
const minRepetitions = options?.["minRepetitions"] ?? getRuleOption("missing-component", "minRepetitions", 3);
|
|
2218
|
+
const frameNames = collectFrameNames(context.file.document);
|
|
2219
|
+
const sameNameFrames = frameNames.get(node.name);
|
|
2220
|
+
if (sameNameFrames && sameNameFrames.length >= minRepetitions) {
|
|
2221
|
+
if (sameNameFrames[0] === node.id) {
|
|
2222
|
+
return {
|
|
2223
|
+
ruleId: missingComponentDef.id,
|
|
2224
|
+
nodeId: node.id,
|
|
2225
|
+
nodePath: context.path.join(" > "),
|
|
2226
|
+
message: `"${node.name}" appears ${sameNameFrames.length} times - consider making it a component`
|
|
2227
|
+
};
|
|
2228
|
+
}
|
|
2229
|
+
}
|
|
2230
|
+
return null;
|
|
2231
|
+
};
|
|
2232
|
+
defineRule({
|
|
2233
|
+
definition: missingComponentDef,
|
|
2234
|
+
check: missingComponentCheck
|
|
2235
|
+
});
|
|
2236
|
+
var detachedInstanceDef = {
|
|
2237
|
+
id: "detached-instance",
|
|
2238
|
+
name: "Detached Instance",
|
|
2239
|
+
category: "component",
|
|
2240
|
+
why: "Detached instances lose their connection to the source component",
|
|
2241
|
+
impact: "Updates to the component won't propagate to this instance",
|
|
2242
|
+
fix: "Reset the instance or create a new variant if customization is needed"
|
|
2243
|
+
};
|
|
2244
|
+
var detachedInstanceCheck = (node, context) => {
|
|
2245
|
+
if (node.type !== "FRAME") return null;
|
|
2246
|
+
const components = context.file.components;
|
|
2247
|
+
const nodeName = node.name.toLowerCase();
|
|
2248
|
+
for (const [, component] of Object.entries(components)) {
|
|
2249
|
+
if (nodeName.includes(component.name.toLowerCase())) {
|
|
2250
|
+
return {
|
|
2251
|
+
ruleId: detachedInstanceDef.id,
|
|
2252
|
+
nodeId: node.id,
|
|
2253
|
+
nodePath: context.path.join(" > "),
|
|
2254
|
+
message: `"${node.name}" may be a detached instance of component "${component.name}"`
|
|
2255
|
+
};
|
|
2256
|
+
}
|
|
2257
|
+
}
|
|
2258
|
+
return null;
|
|
2259
|
+
};
|
|
2260
|
+
defineRule({
|
|
2261
|
+
definition: detachedInstanceDef,
|
|
2262
|
+
check: detachedInstanceCheck
|
|
2263
|
+
});
|
|
2264
|
+
var nestedInstanceOverrideDef = {
|
|
2265
|
+
id: "nested-instance-override",
|
|
2266
|
+
name: "Nested Instance Override",
|
|
2267
|
+
category: "component",
|
|
2268
|
+
why: "Excessive overrides in instances make components harder to maintain",
|
|
2269
|
+
impact: "Component updates may not work as expected",
|
|
2270
|
+
fix: "Create a variant or new component for significantly different use cases"
|
|
2271
|
+
};
|
|
2272
|
+
var nestedInstanceOverrideCheck = (node, context) => {
|
|
2273
|
+
if (!isComponentInstance(node)) return null;
|
|
2274
|
+
if (!node.componentProperties) return null;
|
|
2275
|
+
const overrideCount = Object.keys(node.componentProperties).length;
|
|
2276
|
+
if (overrideCount > 5) {
|
|
2277
|
+
return {
|
|
2278
|
+
ruleId: nestedInstanceOverrideDef.id,
|
|
2279
|
+
nodeId: node.id,
|
|
2280
|
+
nodePath: context.path.join(" > "),
|
|
2281
|
+
message: `"${node.name}" has ${overrideCount} property overrides - consider creating a variant`
|
|
2282
|
+
};
|
|
2283
|
+
}
|
|
2284
|
+
return null;
|
|
2285
|
+
};
|
|
2286
|
+
defineRule({
|
|
2287
|
+
definition: nestedInstanceOverrideDef,
|
|
2288
|
+
check: nestedInstanceOverrideCheck
|
|
2289
|
+
});
|
|
2290
|
+
var variantNotUsedDef = {
|
|
2291
|
+
id: "variant-not-used",
|
|
2292
|
+
name: "Variant Not Used",
|
|
2293
|
+
category: "component",
|
|
2294
|
+
why: "Using instances but not leveraging variants defeats their purpose",
|
|
2295
|
+
impact: "Manual changes instead of using designed variants",
|
|
2296
|
+
fix: "Use the appropriate variant instead of overriding the default"
|
|
2297
|
+
};
|
|
2298
|
+
var variantNotUsedCheck = (_node, _context) => {
|
|
2299
|
+
return null;
|
|
2300
|
+
};
|
|
2301
|
+
defineRule({
|
|
2302
|
+
definition: variantNotUsedDef,
|
|
2303
|
+
check: variantNotUsedCheck
|
|
2304
|
+
});
|
|
2305
|
+
var componentPropertyUnusedDef = {
|
|
2306
|
+
id: "component-property-unused",
|
|
2307
|
+
name: "Component Property Unused",
|
|
2308
|
+
category: "component",
|
|
2309
|
+
why: "Component properties should be utilized to expose customization",
|
|
2310
|
+
impact: "Hardcoded values that should be configurable",
|
|
2311
|
+
fix: "Connect the value to a component property"
|
|
2312
|
+
};
|
|
2313
|
+
var componentPropertyUnusedCheck = (node, _context) => {
|
|
2314
|
+
if (!isComponent(node)) return null;
|
|
2315
|
+
if (!node.componentPropertyDefinitions) return null;
|
|
2316
|
+
const definedProps = Object.keys(node.componentPropertyDefinitions);
|
|
2317
|
+
if (definedProps.length === 0) return null;
|
|
2318
|
+
return null;
|
|
2319
|
+
};
|
|
2320
|
+
defineRule({
|
|
2321
|
+
definition: componentPropertyUnusedDef,
|
|
2322
|
+
check: componentPropertyUnusedCheck
|
|
2323
|
+
});
|
|
2324
|
+
var singleUseComponentDef = {
|
|
2325
|
+
id: "single-use-component",
|
|
2326
|
+
name: "Single Use Component",
|
|
2327
|
+
category: "component",
|
|
2328
|
+
why: "Components used only once add complexity without reuse benefit",
|
|
2329
|
+
impact: "Unnecessary abstraction increases maintenance overhead",
|
|
2330
|
+
fix: "Consider inlining if this component won't be reused"
|
|
2331
|
+
};
|
|
2332
|
+
var singleUseComponentCheck = (node, context) => {
|
|
2333
|
+
if (!isComponent(node)) return null;
|
|
2334
|
+
let instanceCount = 0;
|
|
2335
|
+
function countInstances(n) {
|
|
2336
|
+
if (n.type === "INSTANCE" && n.componentId === node.id) {
|
|
2337
|
+
instanceCount++;
|
|
2338
|
+
}
|
|
2339
|
+
if (n.children) {
|
|
2340
|
+
for (const child of n.children) {
|
|
2341
|
+
countInstances(child);
|
|
2342
|
+
}
|
|
2343
|
+
}
|
|
2344
|
+
}
|
|
2345
|
+
countInstances(context.file.document);
|
|
2346
|
+
if (instanceCount === 1) {
|
|
2347
|
+
return {
|
|
2348
|
+
ruleId: singleUseComponentDef.id,
|
|
2349
|
+
nodeId: node.id,
|
|
2350
|
+
nodePath: context.path.join(" > "),
|
|
2351
|
+
message: `Component "${node.name}" is only used once`
|
|
2352
|
+
};
|
|
2353
|
+
}
|
|
2354
|
+
return null;
|
|
2355
|
+
};
|
|
2356
|
+
defineRule({
|
|
2357
|
+
definition: singleUseComponentDef,
|
|
2358
|
+
check: singleUseComponentCheck
|
|
2359
|
+
});
|
|
2360
|
+
|
|
2361
|
+
// src/rules/naming/index.ts
|
|
2362
|
+
var DEFAULT_NAME_PATTERNS = [
|
|
2363
|
+
/^Frame\s*\d*$/i,
|
|
2364
|
+
/^Group\s*\d*$/i,
|
|
2365
|
+
/^Rectangle\s*\d*$/i,
|
|
2366
|
+
/^Ellipse\s*\d*$/i,
|
|
2367
|
+
/^Vector\s*\d*$/i,
|
|
2368
|
+
/^Line\s*\d*$/i,
|
|
2369
|
+
/^Text\s*\d*$/i,
|
|
2370
|
+
/^Image\s*\d*$/i,
|
|
2371
|
+
/^Component\s*\d*$/i,
|
|
2372
|
+
/^Instance\s*\d*$/i
|
|
2373
|
+
];
|
|
2374
|
+
var NON_SEMANTIC_NAMES = [
|
|
2375
|
+
"rectangle",
|
|
2376
|
+
"ellipse",
|
|
2377
|
+
"vector",
|
|
2378
|
+
"line",
|
|
2379
|
+
"polygon",
|
|
2380
|
+
"star",
|
|
2381
|
+
"path",
|
|
2382
|
+
"shape",
|
|
2383
|
+
"image",
|
|
2384
|
+
"fill",
|
|
2385
|
+
"stroke"
|
|
2386
|
+
];
|
|
2387
|
+
function isDefaultName(name) {
|
|
2388
|
+
return DEFAULT_NAME_PATTERNS.some((pattern) => pattern.test(name));
|
|
2389
|
+
}
|
|
2390
|
+
function isNonSemanticName(name) {
|
|
2391
|
+
const normalized = name.toLowerCase().trim();
|
|
2392
|
+
return NON_SEMANTIC_NAMES.includes(normalized);
|
|
2393
|
+
}
|
|
2394
|
+
function hasNumericSuffix(name) {
|
|
2395
|
+
return /\s+\d+$/.test(name);
|
|
2396
|
+
}
|
|
2397
|
+
function detectNamingConvention(name) {
|
|
2398
|
+
if (/^[a-z]+(-[a-z]+)*$/.test(name)) return "kebab-case";
|
|
2399
|
+
if (/^[a-z]+(_[a-z]+)*$/.test(name)) return "snake_case";
|
|
2400
|
+
if (/^[a-z]+([A-Z][a-z]*)*$/.test(name)) return "camelCase";
|
|
2401
|
+
if (/^[A-Z][a-z]+([A-Z][a-z]*)*$/.test(name)) return "PascalCase";
|
|
2402
|
+
if (/^[A-Z]+(_[A-Z]+)*$/.test(name)) return "SCREAMING_SNAKE_CASE";
|
|
2403
|
+
if (/\s/.test(name)) return "Title Case";
|
|
2404
|
+
return null;
|
|
2405
|
+
}
|
|
2406
|
+
var defaultNameDef = {
|
|
2407
|
+
id: "default-name",
|
|
2408
|
+
name: "Default Name",
|
|
2409
|
+
category: "naming",
|
|
2410
|
+
why: "Default names like 'Frame 123' provide no context about the element's purpose",
|
|
2411
|
+
impact: "Designers and developers cannot understand the structure",
|
|
2412
|
+
fix: "Rename with a descriptive, semantic name (e.g., 'Header', 'ProductCard')"
|
|
2413
|
+
};
|
|
2414
|
+
var defaultNameCheck = (node, context) => {
|
|
2415
|
+
if (!node.name) return null;
|
|
2416
|
+
if (!isDefaultName(node.name)) return null;
|
|
2417
|
+
return {
|
|
2418
|
+
ruleId: defaultNameDef.id,
|
|
2419
|
+
nodeId: node.id,
|
|
2420
|
+
nodePath: context.path.join(" > "),
|
|
2421
|
+
message: `"${node.name}" is a default name - provide a meaningful name`
|
|
2422
|
+
};
|
|
2423
|
+
};
|
|
2424
|
+
defineRule({
|
|
2425
|
+
definition: defaultNameDef,
|
|
2426
|
+
check: defaultNameCheck
|
|
2427
|
+
});
|
|
2428
|
+
var nonSemanticNameDef = {
|
|
2429
|
+
id: "non-semantic-name",
|
|
2430
|
+
name: "Non-Semantic Name",
|
|
2431
|
+
category: "naming",
|
|
2432
|
+
why: "Names like 'Rectangle' describe shape, not purpose",
|
|
2433
|
+
impact: "Structure is hard to understand without context",
|
|
2434
|
+
fix: "Use names that describe what the element represents (e.g., 'Divider', 'Avatar')"
|
|
2435
|
+
};
|
|
2436
|
+
var nonSemanticNameCheck = (node, context) => {
|
|
2437
|
+
if (!node.name) return null;
|
|
2438
|
+
if (!isNonSemanticName(node.name)) return null;
|
|
2439
|
+
if (!node.children || node.children.length === 0) {
|
|
2440
|
+
const shapeTypes = ["RECTANGLE", "ELLIPSE", "VECTOR", "LINE", "STAR", "REGULAR_POLYGON"];
|
|
2441
|
+
if (shapeTypes.includes(node.type)) return null;
|
|
2442
|
+
}
|
|
2443
|
+
return {
|
|
2444
|
+
ruleId: nonSemanticNameDef.id,
|
|
2445
|
+
nodeId: node.id,
|
|
2446
|
+
nodePath: context.path.join(" > "),
|
|
2447
|
+
message: `"${node.name}" is a non-semantic name - describe its purpose`
|
|
2448
|
+
};
|
|
2449
|
+
};
|
|
2450
|
+
defineRule({
|
|
2451
|
+
definition: nonSemanticNameDef,
|
|
2452
|
+
check: nonSemanticNameCheck
|
|
2453
|
+
});
|
|
2454
|
+
var inconsistentNamingConventionDef = {
|
|
2455
|
+
id: "inconsistent-naming-convention",
|
|
2456
|
+
name: "Inconsistent Naming Convention",
|
|
2457
|
+
category: "naming",
|
|
2458
|
+
why: "Mixed naming conventions at the same level create confusion",
|
|
2459
|
+
impact: "Harder to navigate and maintain the design",
|
|
2460
|
+
fix: "Use a consistent naming convention for sibling elements"
|
|
2461
|
+
};
|
|
2462
|
+
var inconsistentNamingConventionCheck = (node, context) => {
|
|
2463
|
+
if (!context.siblings || context.siblings.length < 2) return null;
|
|
2464
|
+
const conventions = /* @__PURE__ */ new Map();
|
|
2465
|
+
for (const sibling of context.siblings) {
|
|
2466
|
+
if (!sibling.name) continue;
|
|
2467
|
+
const convention = detectNamingConvention(sibling.name);
|
|
2468
|
+
if (convention) {
|
|
2469
|
+
conventions.set(convention, (conventions.get(convention) ?? 0) + 1);
|
|
2470
|
+
}
|
|
2471
|
+
}
|
|
2472
|
+
if (conventions.size < 2) return null;
|
|
2473
|
+
let dominantConvention = "";
|
|
2474
|
+
let maxCount = 0;
|
|
2475
|
+
for (const [convention, count] of conventions) {
|
|
2476
|
+
if (count > maxCount) {
|
|
2477
|
+
maxCount = count;
|
|
2478
|
+
dominantConvention = convention;
|
|
2479
|
+
}
|
|
2480
|
+
}
|
|
2481
|
+
const nodeConvention = detectNamingConvention(node.name);
|
|
2482
|
+
if (nodeConvention && nodeConvention !== dominantConvention && maxCount >= 2) {
|
|
2483
|
+
return {
|
|
2484
|
+
ruleId: inconsistentNamingConventionDef.id,
|
|
2485
|
+
nodeId: node.id,
|
|
2486
|
+
nodePath: context.path.join(" > "),
|
|
2487
|
+
message: `"${node.name}" uses ${nodeConvention} while siblings use ${dominantConvention}`
|
|
2488
|
+
};
|
|
2489
|
+
}
|
|
2490
|
+
return null;
|
|
2491
|
+
};
|
|
2492
|
+
defineRule({
|
|
2493
|
+
definition: inconsistentNamingConventionDef,
|
|
2494
|
+
check: inconsistentNamingConventionCheck
|
|
2495
|
+
});
|
|
2496
|
+
var numericSuffixNameDef = {
|
|
2497
|
+
id: "numeric-suffix-name",
|
|
2498
|
+
name: "Numeric Suffix Name",
|
|
2499
|
+
category: "naming",
|
|
2500
|
+
why: "Names with numeric suffixes often indicate copy-paste duplication",
|
|
2501
|
+
impact: "Suggests the element might need componentization",
|
|
2502
|
+
fix: "Remove the suffix or create a component if duplicated"
|
|
2503
|
+
};
|
|
2504
|
+
var numericSuffixNameCheck = (node, context) => {
|
|
2505
|
+
if (!node.name) return null;
|
|
2506
|
+
if (isDefaultName(node.name)) return null;
|
|
2507
|
+
if (!hasNumericSuffix(node.name)) return null;
|
|
2508
|
+
return {
|
|
2509
|
+
ruleId: numericSuffixNameDef.id,
|
|
2510
|
+
nodeId: node.id,
|
|
2511
|
+
nodePath: context.path.join(" > "),
|
|
2512
|
+
message: `"${node.name}" has a numeric suffix - consider renaming`
|
|
2513
|
+
};
|
|
2514
|
+
};
|
|
2515
|
+
defineRule({
|
|
2516
|
+
definition: numericSuffixNameDef,
|
|
2517
|
+
check: numericSuffixNameCheck
|
|
2518
|
+
});
|
|
2519
|
+
var tooLongNameDef = {
|
|
2520
|
+
id: "too-long-name",
|
|
2521
|
+
name: "Too Long Name",
|
|
2522
|
+
category: "naming",
|
|
2523
|
+
why: "Very long names are hard to read and use in code",
|
|
2524
|
+
impact: "Clutters the layer panel and makes selectors unwieldy",
|
|
2525
|
+
fix: "Shorten the name while keeping it descriptive"
|
|
2526
|
+
};
|
|
2527
|
+
var tooLongNameCheck = (node, context, options) => {
|
|
2528
|
+
if (!node.name) return null;
|
|
2529
|
+
const maxLength = options?.["maxLength"] ?? getRuleOption("too-long-name", "maxLength", 50);
|
|
2530
|
+
if (node.name.length <= maxLength) return null;
|
|
2531
|
+
return {
|
|
2532
|
+
ruleId: tooLongNameDef.id,
|
|
2533
|
+
nodeId: node.id,
|
|
2534
|
+
nodePath: context.path.join(" > "),
|
|
2535
|
+
message: `"${node.name.substring(0, 30)}..." is ${node.name.length} chars (max: ${maxLength})`
|
|
2536
|
+
};
|
|
2537
|
+
};
|
|
2538
|
+
defineRule({
|
|
2539
|
+
definition: tooLongNameDef,
|
|
2540
|
+
check: tooLongNameCheck
|
|
2541
|
+
});
|
|
2542
|
+
|
|
2543
|
+
// src/rules/ai-readability/index.ts
|
|
2544
|
+
function hasAutoLayout2(node) {
|
|
2545
|
+
return node.layoutMode !== void 0 && node.layoutMode !== "NONE";
|
|
2546
|
+
}
|
|
2547
|
+
function isContainerNode2(node) {
|
|
2548
|
+
return node.type === "FRAME" || node.type === "GROUP" || node.type === "COMPONENT";
|
|
2549
|
+
}
|
|
2550
|
+
function hasOverlappingBounds(a, b) {
|
|
2551
|
+
const boxA = a.absoluteBoundingBox;
|
|
2552
|
+
const boxB = b.absoluteBoundingBox;
|
|
2553
|
+
if (!boxA || !boxB) return false;
|
|
2554
|
+
return !(boxA.x + boxA.width <= boxB.x || boxB.x + boxB.width <= boxA.x || boxA.y + boxA.height <= boxB.y || boxB.y + boxB.height <= boxA.y);
|
|
2555
|
+
}
|
|
2556
|
+
var ambiguousStructureDef = {
|
|
2557
|
+
id: "ambiguous-structure",
|
|
2558
|
+
name: "Ambiguous Structure",
|
|
2559
|
+
category: "ai-readability",
|
|
2560
|
+
why: "Overlapping nodes without Auto Layout create ambiguous visual hierarchy",
|
|
2561
|
+
impact: "AI cannot reliably determine the reading order or structure",
|
|
2562
|
+
fix: "Use Auto Layout to create clear, explicit structure"
|
|
2563
|
+
};
|
|
2564
|
+
var ambiguousStructureCheck = (node, context) => {
|
|
2565
|
+
if (!isContainerNode2(node)) return null;
|
|
2566
|
+
if (hasAutoLayout2(node)) return null;
|
|
2567
|
+
if (!node.children || node.children.length < 2) return null;
|
|
2568
|
+
for (let i = 0; i < node.children.length; i++) {
|
|
2569
|
+
for (let j = i + 1; j < node.children.length; j++) {
|
|
2570
|
+
const childA = node.children[i];
|
|
2571
|
+
const childB = node.children[j];
|
|
2572
|
+
if (childA && childB && hasOverlappingBounds(childA, childB)) {
|
|
2573
|
+
if (childA.visible !== false && childB.visible !== false) {
|
|
2574
|
+
return {
|
|
2575
|
+
ruleId: ambiguousStructureDef.id,
|
|
2576
|
+
nodeId: node.id,
|
|
2577
|
+
nodePath: context.path.join(" > "),
|
|
2578
|
+
message: `"${node.name}" has overlapping children without Auto Layout`
|
|
2579
|
+
};
|
|
2580
|
+
}
|
|
2581
|
+
}
|
|
2582
|
+
}
|
|
2583
|
+
}
|
|
2584
|
+
return null;
|
|
2585
|
+
};
|
|
2586
|
+
defineRule({
|
|
2587
|
+
definition: ambiguousStructureDef,
|
|
2588
|
+
check: ambiguousStructureCheck
|
|
2589
|
+
});
|
|
2590
|
+
var zIndexDependentLayoutDef = {
|
|
2591
|
+
id: "z-index-dependent-layout",
|
|
2592
|
+
name: "Z-Index Dependent Layout",
|
|
2593
|
+
category: "ai-readability",
|
|
2594
|
+
why: "Using overlapping layers to create visual layout is hard to interpret",
|
|
2595
|
+
impact: "Code generation may misinterpret the intended layout",
|
|
2596
|
+
fix: "Restructure using Auto Layout to express the visual relationship explicitly"
|
|
2597
|
+
};
|
|
2598
|
+
var zIndexDependentLayoutCheck = (node, context) => {
|
|
2599
|
+
if (!isContainerNode2(node)) return null;
|
|
2600
|
+
if (!node.children || node.children.length < 2) return null;
|
|
2601
|
+
let significantOverlapCount = 0;
|
|
2602
|
+
for (let i = 0; i < node.children.length; i++) {
|
|
2603
|
+
for (let j = i + 1; j < node.children.length; j++) {
|
|
2604
|
+
const childA = node.children[i];
|
|
2605
|
+
const childB = node.children[j];
|
|
2606
|
+
if (!childA || !childB) continue;
|
|
2607
|
+
if (childA.visible === false || childB.visible === false) continue;
|
|
2608
|
+
const boxA = childA.absoluteBoundingBox;
|
|
2609
|
+
const boxB = childB.absoluteBoundingBox;
|
|
2610
|
+
if (!boxA || !boxB) continue;
|
|
2611
|
+
if (hasOverlappingBounds(childA, childB)) {
|
|
2612
|
+
const overlapX = Math.min(boxA.x + boxA.width, boxB.x + boxB.width) - Math.max(boxA.x, boxB.x);
|
|
2613
|
+
const overlapY = Math.min(boxA.y + boxA.height, boxB.y + boxB.height) - Math.max(boxA.y, boxB.y);
|
|
2614
|
+
if (overlapX > 0 && overlapY > 0) {
|
|
2615
|
+
const overlapArea = overlapX * overlapY;
|
|
2616
|
+
const smallerArea = Math.min(
|
|
2617
|
+
boxA.width * boxA.height,
|
|
2618
|
+
boxB.width * boxB.height
|
|
2619
|
+
);
|
|
2620
|
+
if (overlapArea > smallerArea * 0.2) {
|
|
2621
|
+
significantOverlapCount++;
|
|
2622
|
+
}
|
|
2623
|
+
}
|
|
2624
|
+
}
|
|
2625
|
+
}
|
|
2626
|
+
}
|
|
2627
|
+
if (significantOverlapCount > 0) {
|
|
2628
|
+
return {
|
|
2629
|
+
ruleId: zIndexDependentLayoutDef.id,
|
|
2630
|
+
nodeId: node.id,
|
|
2631
|
+
nodePath: context.path.join(" > "),
|
|
2632
|
+
message: `"${node.name}" uses layer stacking for layout (${significantOverlapCount} overlaps)`
|
|
2633
|
+
};
|
|
2634
|
+
}
|
|
2635
|
+
return null;
|
|
2636
|
+
};
|
|
2637
|
+
defineRule({
|
|
2638
|
+
definition: zIndexDependentLayoutDef,
|
|
2639
|
+
check: zIndexDependentLayoutCheck
|
|
2640
|
+
});
|
|
2641
|
+
var missingLayoutHintDef = {
|
|
2642
|
+
id: "missing-layout-hint",
|
|
2643
|
+
name: "Missing Layout Hint",
|
|
2644
|
+
category: "ai-readability",
|
|
2645
|
+
why: "Complex nesting without Auto Layout makes structure unpredictable",
|
|
2646
|
+
impact: "AI may generate incorrect code due to ambiguous relationships",
|
|
2647
|
+
fix: "Add Auto Layout or simplify the nesting structure"
|
|
2648
|
+
};
|
|
2649
|
+
var missingLayoutHintCheck = (node, context) => {
|
|
2650
|
+
if (!isContainerNode2(node)) return null;
|
|
2651
|
+
if (hasAutoLayout2(node)) return null;
|
|
2652
|
+
if (!node.children || node.children.length === 0) return null;
|
|
2653
|
+
const nestedContainers = node.children.filter((c) => isContainerNode2(c));
|
|
2654
|
+
if (nestedContainers.length >= 2) {
|
|
2655
|
+
const withoutLayout = nestedContainers.filter((c) => !hasAutoLayout2(c));
|
|
2656
|
+
if (withoutLayout.length >= 2) {
|
|
2657
|
+
return {
|
|
2658
|
+
ruleId: missingLayoutHintDef.id,
|
|
2659
|
+
nodeId: node.id,
|
|
2660
|
+
nodePath: context.path.join(" > "),
|
|
2661
|
+
message: `"${node.name}" has ${withoutLayout.length} nested containers without layout hints`
|
|
2662
|
+
};
|
|
2663
|
+
}
|
|
2664
|
+
}
|
|
2665
|
+
return null;
|
|
2666
|
+
};
|
|
2667
|
+
defineRule({
|
|
2668
|
+
definition: missingLayoutHintDef,
|
|
2669
|
+
check: missingLayoutHintCheck
|
|
2670
|
+
});
|
|
2671
|
+
var invisibleLayerDef = {
|
|
2672
|
+
id: "invisible-layer",
|
|
2673
|
+
name: "Invisible Layer",
|
|
2674
|
+
category: "ai-readability",
|
|
2675
|
+
why: "Hidden layers add noise and may confuse analysis tools",
|
|
2676
|
+
impact: "Exported code may include unnecessary elements",
|
|
2677
|
+
fix: "Delete hidden layers or move them to a separate 'archive' page"
|
|
2678
|
+
};
|
|
2679
|
+
var invisibleLayerCheck = (node, context) => {
|
|
2680
|
+
if (node.visible !== false) return null;
|
|
2681
|
+
if (context.parent?.visible === false) return null;
|
|
2682
|
+
return {
|
|
2683
|
+
ruleId: invisibleLayerDef.id,
|
|
2684
|
+
nodeId: node.id,
|
|
2685
|
+
nodePath: context.path.join(" > "),
|
|
2686
|
+
message: `"${node.name}" is hidden - consider removing if not needed`
|
|
2687
|
+
};
|
|
2688
|
+
};
|
|
2689
|
+
defineRule({
|
|
2690
|
+
definition: invisibleLayerDef,
|
|
2691
|
+
check: invisibleLayerCheck
|
|
2692
|
+
});
|
|
2693
|
+
var emptyFrameDef = {
|
|
2694
|
+
id: "empty-frame",
|
|
2695
|
+
name: "Empty Frame",
|
|
2696
|
+
category: "ai-readability",
|
|
2697
|
+
why: "Empty frames add noise and may indicate incomplete design",
|
|
2698
|
+
impact: "Generates unnecessary wrapper elements in code",
|
|
2699
|
+
fix: "Remove the frame or add content"
|
|
2700
|
+
};
|
|
2701
|
+
var emptyFrameCheck = (node, context) => {
|
|
2702
|
+
if (node.type !== "FRAME") return null;
|
|
2703
|
+
if (node.children && node.children.length > 0) return null;
|
|
2704
|
+
if (node.absoluteBoundingBox) {
|
|
2705
|
+
const { width, height } = node.absoluteBoundingBox;
|
|
2706
|
+
if (width <= 48 && height <= 48) return null;
|
|
2707
|
+
}
|
|
2708
|
+
return {
|
|
2709
|
+
ruleId: emptyFrameDef.id,
|
|
2710
|
+
nodeId: node.id,
|
|
2711
|
+
nodePath: context.path.join(" > "),
|
|
2712
|
+
message: `"${node.name}" is an empty frame`
|
|
2713
|
+
};
|
|
2714
|
+
};
|
|
2715
|
+
defineRule({
|
|
2716
|
+
definition: emptyFrameDef,
|
|
2717
|
+
check: emptyFrameCheck
|
|
2718
|
+
});
|
|
2719
|
+
|
|
2720
|
+
// src/rules/handoff-risk/index.ts
|
|
2721
|
+
function hasAutoLayout3(node) {
|
|
2722
|
+
return node.layoutMode !== void 0 && node.layoutMode !== "NONE";
|
|
2723
|
+
}
|
|
2724
|
+
function isContainerNode3(node) {
|
|
2725
|
+
return node.type === "FRAME" || node.type === "GROUP" || node.type === "COMPONENT";
|
|
2726
|
+
}
|
|
2727
|
+
function isTextNode(node) {
|
|
2728
|
+
return node.type === "TEXT";
|
|
2729
|
+
}
|
|
2730
|
+
function isImageNode(node) {
|
|
2731
|
+
if (node.type === "RECTANGLE" && node.fills) {
|
|
2732
|
+
for (const fill of node.fills) {
|
|
2733
|
+
const fillObj = fill;
|
|
2734
|
+
if (fillObj["type"] === "IMAGE") return true;
|
|
2735
|
+
}
|
|
2736
|
+
}
|
|
2737
|
+
return false;
|
|
2738
|
+
}
|
|
2739
|
+
var hardcodeRiskDef = {
|
|
2740
|
+
id: "hardcode-risk",
|
|
2741
|
+
name: "Hardcode Risk",
|
|
2742
|
+
category: "handoff-risk",
|
|
2743
|
+
why: "Absolute positioning with fixed values creates inflexible layouts",
|
|
2744
|
+
impact: "Layout will break when content changes or on different screens",
|
|
2745
|
+
fix: "Use Auto Layout with relative positioning"
|
|
2746
|
+
};
|
|
2747
|
+
var hardcodeRiskCheck = (node, context) => {
|
|
2748
|
+
if (!isContainerNode3(node)) return null;
|
|
2749
|
+
if (node.layoutPositioning !== "ABSOLUTE") return null;
|
|
2750
|
+
if (context.parent && hasAutoLayout3(context.parent)) {
|
|
2751
|
+
return {
|
|
2752
|
+
ruleId: hardcodeRiskDef.id,
|
|
2753
|
+
nodeId: node.id,
|
|
2754
|
+
nodePath: context.path.join(" > "),
|
|
2755
|
+
message: `"${node.name}" uses absolute positioning with fixed values`
|
|
2756
|
+
};
|
|
2757
|
+
}
|
|
2758
|
+
return null;
|
|
2759
|
+
};
|
|
2760
|
+
defineRule({
|
|
2761
|
+
definition: hardcodeRiskDef,
|
|
2762
|
+
check: hardcodeRiskCheck
|
|
2763
|
+
});
|
|
2764
|
+
var textTruncationUnhandledDef = {
|
|
2765
|
+
id: "text-truncation-unhandled",
|
|
2766
|
+
name: "Text Truncation Unhandled",
|
|
2767
|
+
category: "handoff-risk",
|
|
2768
|
+
why: "Text nodes without truncation handling may overflow",
|
|
2769
|
+
impact: "Long text will break the layout",
|
|
2770
|
+
fix: "Set text truncation (ellipsis) or ensure container can grow"
|
|
2771
|
+
};
|
|
2772
|
+
var textTruncationUnhandledCheck = (node, context) => {
|
|
2773
|
+
if (!isTextNode(node)) return null;
|
|
2774
|
+
if (!context.parent) return null;
|
|
2775
|
+
if (!hasAutoLayout3(context.parent)) return null;
|
|
2776
|
+
if (node.absoluteBoundingBox) {
|
|
2777
|
+
const { width } = node.absoluteBoundingBox;
|
|
2778
|
+
if (node.characters && node.characters.length > 50 && width < 300) {
|
|
2779
|
+
return {
|
|
2780
|
+
ruleId: textTruncationUnhandledDef.id,
|
|
2781
|
+
nodeId: node.id,
|
|
2782
|
+
nodePath: context.path.join(" > "),
|
|
2783
|
+
message: `"${node.name}" may need text truncation handling`
|
|
2784
|
+
};
|
|
2785
|
+
}
|
|
2786
|
+
}
|
|
2787
|
+
return null;
|
|
2788
|
+
};
|
|
2789
|
+
defineRule({
|
|
2790
|
+
definition: textTruncationUnhandledDef,
|
|
2791
|
+
check: textTruncationUnhandledCheck
|
|
2792
|
+
});
|
|
2793
|
+
var imageNoPlaceholderDef = {
|
|
2794
|
+
id: "image-no-placeholder",
|
|
2795
|
+
name: "Image No Placeholder",
|
|
2796
|
+
category: "handoff-risk",
|
|
2797
|
+
why: "Images without placeholder state may cause layout shifts",
|
|
2798
|
+
impact: "Poor user experience during image loading",
|
|
2799
|
+
fix: "Define a placeholder state or background color"
|
|
2800
|
+
};
|
|
2801
|
+
var imageNoPlaceholderCheck = (node, context) => {
|
|
2802
|
+
if (!isImageNode(node)) return null;
|
|
2803
|
+
if (node.fills && Array.isArray(node.fills) && node.fills.length === 1) {
|
|
2804
|
+
const fill = node.fills[0];
|
|
2805
|
+
if (fill["type"] === "IMAGE") {
|
|
2806
|
+
return {
|
|
2807
|
+
ruleId: imageNoPlaceholderDef.id,
|
|
2808
|
+
nodeId: node.id,
|
|
2809
|
+
nodePath: context.path.join(" > "),
|
|
2810
|
+
message: `"${node.name}" image has no placeholder fill`
|
|
2811
|
+
};
|
|
2812
|
+
}
|
|
2813
|
+
}
|
|
2814
|
+
return null;
|
|
2815
|
+
};
|
|
2816
|
+
defineRule({
|
|
2817
|
+
definition: imageNoPlaceholderDef,
|
|
2818
|
+
check: imageNoPlaceholderCheck
|
|
2819
|
+
});
|
|
2820
|
+
var prototypeLinkInDesignDef = {
|
|
2821
|
+
id: "prototype-link-in-design",
|
|
2822
|
+
name: "Prototype Link in Design",
|
|
2823
|
+
category: "handoff-risk",
|
|
2824
|
+
why: "Prototype connections may affect how the design is interpreted",
|
|
2825
|
+
impact: "Developers may misunderstand which elements should be interactive",
|
|
2826
|
+
fix: "Document interactions separately or use clear naming"
|
|
2827
|
+
};
|
|
2828
|
+
var prototypeLinkInDesignCheck = (_node, _context) => {
|
|
2829
|
+
return null;
|
|
2830
|
+
};
|
|
2831
|
+
defineRule({
|
|
2832
|
+
definition: prototypeLinkInDesignDef,
|
|
2833
|
+
check: prototypeLinkInDesignCheck
|
|
2834
|
+
});
|
|
2835
|
+
var noDevStatusDef = {
|
|
2836
|
+
id: "no-dev-status",
|
|
2837
|
+
name: "No Dev Status",
|
|
2838
|
+
category: "handoff-risk",
|
|
2839
|
+
why: "Without dev status, developers cannot know if a design is ready",
|
|
2840
|
+
impact: "May implement designs that are still in progress",
|
|
2841
|
+
fix: "Mark frames as 'Ready for Dev' or 'Completed' when appropriate"
|
|
2842
|
+
};
|
|
2843
|
+
var noDevStatusCheck = (node, context) => {
|
|
2844
|
+
if (node.type !== "FRAME") return null;
|
|
2845
|
+
if (context.depth > 1) return null;
|
|
2846
|
+
if (node.devStatus) return null;
|
|
2847
|
+
return {
|
|
2848
|
+
ruleId: noDevStatusDef.id,
|
|
2849
|
+
nodeId: node.id,
|
|
2850
|
+
nodePath: context.path.join(" > "),
|
|
2851
|
+
message: `"${node.name}" has no dev status set`
|
|
2852
|
+
};
|
|
2853
|
+
};
|
|
2854
|
+
defineRule({
|
|
2855
|
+
definition: noDevStatusDef,
|
|
2856
|
+
check: noDevStatusCheck
|
|
2857
|
+
});
|
|
2858
|
+
|
|
2859
|
+
// src/mcp/server.ts
|
|
2860
|
+
config();
|
|
2861
|
+
var require2 = createRequire(import.meta.url);
|
|
2862
|
+
var pkg = require2("../../package.json");
|
|
2863
|
+
var server = new McpServer({
|
|
2864
|
+
name: "canicode",
|
|
2865
|
+
version: pkg.version
|
|
2866
|
+
});
|
|
2867
|
+
server.tool(
|
|
2868
|
+
"analyze",
|
|
2869
|
+
`Analyze a Figma design for development-friendliness and AI-friendliness.
|
|
2870
|
+
|
|
2871
|
+
Two ways to provide design data:
|
|
2872
|
+
1. designData \u2014 Pass Figma node data directly (from Figma MCP get_metadata). Recommended when using Figma MCP.
|
|
2873
|
+
2. input \u2014 Figma URL (fetches via REST API, requires FIGMA_TOKEN).
|
|
2874
|
+
|
|
2875
|
+
Typical flow with Figma MCP:
|
|
2876
|
+
Step 1: Call Figma MCP get_metadata to get the node tree
|
|
2877
|
+
Step 2: Pass the result as designData to this tool`,
|
|
2878
|
+
{
|
|
2879
|
+
designData: z.string().optional().describe("Figma node data from Figma MCP get_metadata (XML or JSON). Pass this instead of input when using Figma MCP."),
|
|
2880
|
+
input: z.string().optional().describe("Figma URL. Used when designData is not provided. Requires FIGMA_TOKEN."),
|
|
2881
|
+
fileKey: z.string().optional().describe("Figma file key (used with designData to generate deep links)"),
|
|
2882
|
+
fileName: z.string().optional().describe("Figma file name (used with designData for display)"),
|
|
2883
|
+
token: z.string().optional().describe("Figma API token (falls back to FIGMA_TOKEN env var)"),
|
|
2884
|
+
preset: z.enum(["relaxed", "dev-friendly", "ai-ready", "strict"]).optional().describe("Analysis preset"),
|
|
2885
|
+
targetNodeId: z.string().optional().describe("Scope analysis to a specific node ID"),
|
|
2886
|
+
configPath: z.string().optional().describe("Path to config JSON file for rule overrides"),
|
|
2887
|
+
customRulesPath: z.string().optional().describe("Path to custom rules JSON file")
|
|
2888
|
+
},
|
|
2889
|
+
async ({ designData, input, fileKey, fileName, token, preset, targetNodeId, configPath, customRulesPath }) => {
|
|
2890
|
+
try {
|
|
2891
|
+
let file;
|
|
2892
|
+
let nodeId;
|
|
2893
|
+
if (designData) {
|
|
2894
|
+
file = parseDesignData(designData, fileKey ?? "unknown", fileName);
|
|
2895
|
+
} else if (input) {
|
|
2896
|
+
const loaded = await loadFile(input, token, "api");
|
|
2897
|
+
file = loaded.file;
|
|
2898
|
+
nodeId = loaded.nodeId;
|
|
2899
|
+
} else {
|
|
2900
|
+
throw new Error("Provide either designData (from Figma MCP) or input (Figma URL).");
|
|
2901
|
+
}
|
|
2902
|
+
const effectiveNodeId = targetNodeId ?? nodeId;
|
|
2903
|
+
let configs = preset ? { ...getConfigsWithPreset(preset) } : { ...RULE_CONFIGS };
|
|
2904
|
+
if (configPath) {
|
|
2905
|
+
const configFile = await loadConfigFile(configPath);
|
|
2906
|
+
configs = mergeConfigs(configs, configFile);
|
|
2907
|
+
}
|
|
2908
|
+
if (customRulesPath) {
|
|
2909
|
+
const { rules, configs: customConfigs } = await loadCustomRules(customRulesPath);
|
|
2910
|
+
for (const rule of rules) {
|
|
2911
|
+
ruleRegistry.register(rule);
|
|
2912
|
+
}
|
|
2913
|
+
configs = { ...configs, ...customConfigs };
|
|
2914
|
+
}
|
|
2915
|
+
const result = analyzeFile(file, {
|
|
2916
|
+
configs,
|
|
2917
|
+
...effectiveNodeId ? { targetNodeId: effectiveNodeId } : {}
|
|
2918
|
+
});
|
|
2919
|
+
const scores = calculateScores(result);
|
|
2920
|
+
const summary = formatScoreSummary(scores);
|
|
2921
|
+
const figmaToken = token ?? process.env["FIGMA_TOKEN"];
|
|
2922
|
+
const html = generateHtmlReport(file, result, scores, { figmaToken });
|
|
2923
|
+
const now = /* @__PURE__ */ new Date();
|
|
2924
|
+
const ts = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, "0")}-${String(now.getDate()).padStart(2, "0")}-${String(now.getHours()).padStart(2, "0")}-${String(now.getMinutes()).padStart(2, "0")}`;
|
|
2925
|
+
ensureReportsDir();
|
|
2926
|
+
const reportPath = `${getReportsDir()}/report-${ts}-${file.fileKey}.html`;
|
|
2927
|
+
await new Promise((resolve4, reject) => {
|
|
2928
|
+
writeFile(reportPath, html, "utf-8", (err) => {
|
|
2929
|
+
if (err) reject(err);
|
|
2930
|
+
else resolve4();
|
|
2931
|
+
});
|
|
2932
|
+
});
|
|
2933
|
+
const openCmd = process.platform === "darwin" ? "open" : process.platform === "win32" ? "start" : "xdg-open";
|
|
2934
|
+
exec(`${openCmd} "${reportPath}"`);
|
|
2935
|
+
const issuesByRule = {};
|
|
2936
|
+
for (const issue of result.issues) {
|
|
2937
|
+
const id = issue.violation.ruleId;
|
|
2938
|
+
issuesByRule[id] = (issuesByRule[id] ?? 0) + 1;
|
|
2939
|
+
}
|
|
2940
|
+
return {
|
|
2941
|
+
content: [
|
|
2942
|
+
{
|
|
2943
|
+
type: "text",
|
|
2944
|
+
text: JSON.stringify(
|
|
2945
|
+
{
|
|
2946
|
+
fileName: file.name,
|
|
2947
|
+
nodeCount: result.nodeCount,
|
|
2948
|
+
maxDepth: result.maxDepth,
|
|
2949
|
+
issueCount: result.issues.length,
|
|
2950
|
+
scores: {
|
|
2951
|
+
overall: scores.overall,
|
|
2952
|
+
categories: scores.byCategory
|
|
2953
|
+
},
|
|
2954
|
+
issuesByRule,
|
|
2955
|
+
summary
|
|
2956
|
+
},
|
|
2957
|
+
null,
|
|
2958
|
+
2
|
|
2959
|
+
)
|
|
2960
|
+
}
|
|
2961
|
+
]
|
|
2962
|
+
};
|
|
2963
|
+
} catch (error) {
|
|
2964
|
+
return {
|
|
2965
|
+
content: [
|
|
2966
|
+
{
|
|
2967
|
+
type: "text",
|
|
2968
|
+
text: `Error: ${error instanceof Error ? error.message : String(error)}`
|
|
2969
|
+
}
|
|
2970
|
+
],
|
|
2971
|
+
isError: true
|
|
2972
|
+
};
|
|
2973
|
+
}
|
|
2974
|
+
}
|
|
2975
|
+
);
|
|
2976
|
+
server.tool(
|
|
2977
|
+
"list-rules",
|
|
2978
|
+
"List all available analysis rules with their current configuration",
|
|
2979
|
+
{},
|
|
2980
|
+
async () => {
|
|
2981
|
+
const rules = ruleRegistry.getAll().map((rule) => {
|
|
2982
|
+
const config2 = RULE_CONFIGS[rule.definition.id];
|
|
2983
|
+
return {
|
|
2984
|
+
id: rule.definition.id,
|
|
2985
|
+
name: rule.definition.name,
|
|
2986
|
+
category: rule.definition.category,
|
|
2987
|
+
severity: config2?.severity,
|
|
2988
|
+
score: config2?.score,
|
|
2989
|
+
enabled: config2?.enabled,
|
|
2990
|
+
why: rule.definition.why
|
|
2991
|
+
};
|
|
2992
|
+
});
|
|
2993
|
+
return {
|
|
2994
|
+
content: [
|
|
2995
|
+
{
|
|
2996
|
+
type: "text",
|
|
2997
|
+
text: JSON.stringify(rules, null, 2)
|
|
2998
|
+
}
|
|
2999
|
+
]
|
|
3000
|
+
};
|
|
3001
|
+
}
|
|
3002
|
+
);
|
|
3003
|
+
async function main() {
|
|
3004
|
+
const transport = new StdioServerTransport();
|
|
3005
|
+
await server.connect(transport);
|
|
3006
|
+
}
|
|
3007
|
+
main().catch(console.error);
|
|
3008
|
+
//# sourceMappingURL=server.js.map
|
|
3009
|
+
//# sourceMappingURL=server.js.map
|