codesign-mcp-next 0.3.3 → 0.3.5

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/CHANGELOG.md CHANGED
@@ -1,5 +1,29 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.3.5 - 2026-11-26
4
+
5
+ ### Added
6
+
7
+ - Added `visual_diff`, a pixel-level visual regression tool. Provide `pageUrl` (a local http dev server) or `screenshotPath`, plus the artboard selector. It downloads the artboard preview, aligns both images to the artboard viewport, and returns a 0..1 similarity score, verdict, diff pixels, difference hotspots, and a diff image path. Aspect-ratio drift beyond tolerance is reported as `VISUAL_DIFF_ALIGNMENT` rather than a misleading score. The score is a regression signal, not a pass/fail gate.
8
+ - Added `acquireHeadlessIsolated()` to the browser manager so local dev-server screenshots use a dedicated page and never disturb the shared CoDesign page.
9
+ - Added `VISUAL_DIFF_IMAGE_INVALID`, `VISUAL_DIFF_ALIGNMENT`, and `VISUAL_DIFF_PAGE_INVALID` error codes; `pageUrl` is restricted to local loopback hosts.
10
+
11
+ ### Changed
12
+
13
+ - Updated the design-to-code prompt, workflow resource, README, and skill to include optional `visual_diff` as the L3 visual-regression layer.
14
+
15
+ ## 0.3.4 - 2026-11-26
16
+
17
+ ### Added
18
+
19
+ - Added `verify_rendering`, a read-only tool that re-fetches the official spec, rebuilds `platformSpec`, and statically checks generated code for size, slice scale, color, typography, radius, and hierarchy. Slice usages are located via `data-slice-id="<layerObjectId>"` attributes or `/* slice:<layerObjectId> */` comments. It reports per-file/line issues and a `reviewRequired` list for areas that cannot be statically resolved, and returns `ok: false` when a hard check fails.
20
+ - Added `designSize` to `download_slice` results when `targetPlatform` is supplied: the converted layout width/height a slice must be displayed at, so 2x assets are shown at design size rather than pixel size.
21
+ - Added `CODE_FILE_INVALID` for missing, oversized, or out-of-workspace code files passed to `verify_rendering`.
22
+
23
+ ### Changed
24
+
25
+ - Updated the design-to-code prompt, workflow resource, and skill to mark slice anchors and run `verify_rendering` before finishing.
26
+
3
27
  ## 0.3.3 - 2026-11-26
4
28
 
5
29
  ### Added
package/README.md CHANGED
@@ -118,14 +118,16 @@ CODESIGN_LOG_LEVEL=info
118
118
  - `list_artboards`: Resolve a CoDesign sharing URL into designs and artboards.
119
119
  - `get_artboard_spec`: Fetch official CoDesign `meta_url` specs with layers, text, colors, CSS, groups, and slice metadata. Every response includes a `spec.hierarchy` tree built from `parent_id` and `layerIndex`; each node carries `rect` (artboard-absolute), `relativeRect` (relative to the artboard), and `relativeToParent` (relative to its direct parent) so a full-page layout can be mapped to DOM without rebuilding the tree yourself. With `layerObjectId`, `selectionScope` can be `layer`, `subtree`, or `region`; selected responses also include flat layers/groups, selection bounds, and relative coordinates. Optional `targetPlatform` accepts natural-language platform names such as `web`, `Android`, `安卓`, `iOS`, `微信小程序`, or `mini program` and returns platform-adjusted metadata. Optional `targetUnit`, `customScale`, `customWidth`, and `remBasePx` mirror CoDesign's platform settings.
120
120
  - `get_artboard_image`: Fetch preview or cover images for visual comparison.
121
- - `download_slice`: Download designer-exported slice assets from the official slice manifest.
121
+ - `download_slice`: Download designer-exported slice assets from the official slice manifest. Passing the same `targetPlatform`/unit/width options used for `get_artboard_spec` also returns `slice.designSize` — the converted layout width/height the slice must be displayed at. A 2x asset must be shown at `designSize`, never at its pixel size.
122
+ - `verify_rendering`: Re-fetch the official spec (ignoring any LLM-supplied measurements), rebuild `platformSpec`, and statically check generated code against the design. Mark each slice usage with a `data-slice-id="<layerObjectId>"` attribute or a `/* slice:<layerObjectId> */` comment, pass the code files plus the same platform options, and it reports per-file/line issues across size, scale, color, typography, radius, and hierarchy, plus a `reviewRequired` list for areas that cannot be statically resolved. Returns `ok: false` when any hard check fails. Read-only.
123
+ - `visual_diff`: Pixel-level visual regression. Provide either `pageUrl` (a running local http dev server on localhost/127.0.0.1, screenshotted at the artboard viewport) or `screenshotPath` (an existing screenshot), plus the same artboard selector. It downloads the artboard preview, aligns both images to the artboard's CSS dimensions, and returns a 0..1 similarity `score`, a `verdict` (high/medium/low), `diffPixels`, difference `hotspots`, and a `diffImagePath` under `.codesign-mcp/artifacts/`. Alignment failure is reported as an error rather than a misleading score. The score is a regression signal for comparing runs, not a pass/fail gate — font rasterization can lower it. Read-only; only writes the diff image.
122
124
  - `debug_collect_network`: Collect a redacted network summary for diagnosis.
123
125
 
124
126
  ## Caching and tool output
125
127
 
126
128
  Sharing details, meta JSON, and slice manifests are cached in memory for 60 seconds (`CODESIGN_CACHE_TTL_MS`, in milliseconds). Concurrent calls for the same resource share a single request. Set the variable to `0` to disable caching. The cache is process-local and is never written to disk.
127
129
 
128
- Successful tool results keep the complete payload in `structuredContent`. `content[0].text` contains only a short summary, so the same JSON is not counted twice in the model context. For `get_artboard_spec`, the text summary additionally includes a two-level `hierarchy` skeleton, artboard dimensions, layer/group/slice counts, and any integrity warnings, so clients that ignore `structuredContent` still receive the structural cues needed for design-to-code. If your MCP client does not read `structuredContent`, pass `includeFullText: true` to any data tool (`list_artboards`, `get_artboard_spec`, `get_artboard_image`, `download_slice`) to receive the full JSON as text instead. `debug_collect_network` keeps full records in the text channel because those records are the diagnostic output itself.
130
+ Successful tool results keep the complete payload in `structuredContent`. `content[0].text` contains only a short summary, so the same JSON is not counted twice in the model context. For `get_artboard_spec`, the text summary additionally includes a two-level `hierarchy` skeleton, artboard dimensions, layer/group/slice counts, and any integrity warnings, so clients that ignore `structuredContent` still receive the structural cues needed for design-to-code. If your MCP client does not read `structuredContent`, pass `includeFullText: true` to any data tool (`list_artboards`, `get_artboard_spec`, `get_artboard_image`, `download_slice`, `verify_rendering`, `visual_diff`) to receive the full JSON as text instead. `debug_collect_network` keeps full records in the text channel because those records are the diagnostic output itself.
129
131
 
130
132
  All headless tools reuse one browser page, so the sharing page is opened only once per session instead of once per tool call. The headed login window uses an exclusive page and mode switches wait for in-flight calls to finish.
131
133
 
@@ -147,7 +149,7 @@ Remote metadata and artifact downloads are restricted to `https://codesign.qq.co
147
149
 
148
150
  ## Prompts
149
151
 
150
- - `implement_codesign_page`: Generate a structured design-to-code prompt for a full page or copied CoDesign selection. It guides an Agent to call `list_artboards`, `get_artboard_spec`, and `download_slice` in the intended order.
152
+ - `implement_codesign_page`: Generate a structured design-to-code prompt for a full page or copied CoDesign selection. It guides an Agent to call `list_artboards`, `get_artboard_spec`, `download_slice`, `verify_rendering`, and optionally `visual_diff` in the intended order.
151
153
 
152
154
  ## Resources
153
155
 
@@ -156,10 +158,10 @@ Remote metadata and artifact downloads are restricted to `https://codesign.qq.co
156
158
  For design-to-code work, prefer this flow:
157
159
 
158
160
  ```text
159
- list_artboards -> get_artboard_spec -> download_slice
161
+ list_artboards -> get_artboard_spec -> download_slice -> (write code) -> verify_rendering -> visual_diff (optional)
160
162
  ```
161
163
 
162
- Preview screenshots are for visual comparison, not for production slicing.
164
+ `verify_rendering` re-fetches the spec itself, so its expected values never depend on numbers copied into the prompt. Check its `issues` and `reviewRequired`, fix the code, and re-run until `ok: true`. `visual_diff` is an optional extra signal: start your local dev server, pass its `pageUrl`, and compare the `score` across iterations; a drop means a change hurt visual fidelity. Preview screenshots are for visual comparison, not for production slicing.
163
165
 
164
166
  ## CoDesign AI Selection Userscript
165
167
 
@@ -345,14 +347,16 @@ CODESIGN_LOG_LEVEL=info
345
347
  - `list_artboards`:把 CoDesign 分享链接解析为设计稿和画板列表。
346
348
  - `get_artboard_spec`:读取官方 CoDesign `meta_url` 标注数据,包括图层、文字、颜色、CSS、分组和切图元数据。所有结果都包含按 `parent_id` 与 `layerIndex` 构建的 `spec.hierarchy` 层级树;每个节点带 `rect`(相对画板绝对坐标)、`relativeRect`(相对画板)和 `relativeToParent`(相对直接父节点),整页还原可直接映射为 DOM,无需自行拼树。传入 `layerObjectId` 后,`selectionScope` 可设为 `layer`、`subtree` 或 `region`;选区结果还包含扁平图层/分组、选区边界和相对坐标。可选的 `targetPlatform` 支持 `web`、`Android`、`安卓`、`iOS`、`微信小程序`、`mini program` 等自然语言平台名称,并返回平台转换后的标注信息。`targetUnit`、`customScale`、`customWidth`、`remBasePx` 对应 CoDesign 的平台设置。
347
349
  - `get_artboard_image`:获取预览图或封面图,主要用于视觉对比。
348
- - `download_slice`:从官方切图清单下载设计师导出的切图资源。
350
+ - `download_slice`:从官方切图清单下载设计师导出的切图资源。传入与 `get_artboard_spec` 相同的 `targetPlatform`/单位/宽度参数时,会同时返回 `slice.designSize`,即该切图在代码中应显示的换算后布局宽高;2x 图必须按 `designSize` 显示,而不是按图片像素尺寸显示。
351
+ - `verify_rendering`:重新拉取官方 spec(不信任任何由模型转录的尺寸),重建 `platformSpec`,然后静态校验生成代码与设计稿是否一致。在每处切图使用点用 `data-slice-id="<图层objectId>"` 属性或 `/* slice:<图层objectId> */` 注释标注,传入代码文件与相同的平台参数,即可按文件/行号返回尺寸、倍率、颜色、字号、圆角、层级六个维度的 issue,并给出 `reviewRequired`(无法静态判定的区域清单)。任一硬性检查失败时返回 `ok: false`。只读,不修改文件。
352
+ - `visual_diff`:像素级视觉回归。提供 `pageUrl`(本机 localhost/127.0.0.1 上运行的本地 dev server,按画板 viewport 截图)或 `screenshotPath`(已有截图),加上相同的画板选择器。工具下载画板预览图,把两张图对齐到画板 CSS 尺寸后,返回 0..1 的相似度 `score`、`verdict`(high/medium/low)、`diffPixels`、差异 `hotspots` 以及 `.codesign-mcp/artifacts/` 下的 `diffImagePath`。对齐失败会直接报错,而不是给出一个误导性的分数。分数是比较多次运行的回归信号,不是通过/失败硬判定——字体渲染会拉低分数。只读,仅写入差异图。
349
353
  - `debug_collect_network`:收集脱敏后的网络摘要,用于诊断。
350
354
 
351
355
  ## 缓存与工具输出
352
356
 
353
357
  分享详情、标注 JSON 和切图清单会在内存中缓存 60 秒(`CODESIGN_CACHE_TTL_MS`,单位毫秒),相同资源的并发调用会合并为一次请求。设为 `0` 可关闭缓存。缓存只存在于当前进程,不会写入磁盘。
354
358
 
355
- 工具成功结果把完整数据放在 `structuredContent` 中,`content[0].text` 只返回简短摘要,避免同一份 JSON 在模型上下文里被计算两次。`get_artboard_spec` 的文本摘要还会带出两层 `hierarchy` 骨架、画板尺寸、图层/分组/切图数量以及完整性告警,因此不读取 `structuredContent` 的客户端也能拿到还原所需的结构信息。如果你的 MCP 客户端不读取 `structuredContent`,可以对任意数据工具(`list_artboards`、`get_artboard_spec`、`get_artboard_image`、`download_slice`)传 `includeFullText: true`,改为接收完整 JSON 文本。`debug_collect_network` 的诊断记录本身就是输出内容,因此仍在文本通道中保留完整记录。
359
+ 工具成功结果把完整数据放在 `structuredContent` 中,`content[0].text` 只返回简短摘要,避免同一份 JSON 在模型上下文里被计算两次。`get_artboard_spec` 的文本摘要还会带出两层 `hierarchy` 骨架、画板尺寸、图层/分组/切图数量以及完整性告警,因此不读取 `structuredContent` 的客户端也能拿到还原所需的结构信息。如果你的 MCP 客户端不读取 `structuredContent`,可以对任意数据工具(`list_artboards`、`get_artboard_spec`、`get_artboard_image`、`download_slice`、`verify_rendering`、`visual_diff`)传 `includeFullText: true`,改为接收完整 JSON 文本。`debug_collect_network` 的诊断记录本身就是输出内容,因此仍在文本通道中保留完整记录。
356
360
 
357
361
  所有 headless 工具复用同一个浏览器页面,分享页在每个会话中只打开一次,而不是每次工具调用都打开。登录用的 headed 窗口使用独占页面,模式切换会等待正在进行的调用结束。
358
362
 
@@ -374,7 +378,7 @@ CODESIGN_LOG_LEVEL=info
374
378
 
375
379
  ## 提示词
376
380
 
377
- - `implement_codesign_page`:为完整页面或复制的 CoDesign 选区生成结构化设计还原提示词,引导 Agent 按预期顺序调用 `list_artboards`、`get_artboard_spec` 和 `download_slice`。
381
+ - `implement_codesign_page`:为完整页面或复制的 CoDesign 选区生成结构化设计还原提示词,引导 Agent 按预期顺序调用 `list_artboards`、`get_artboard_spec`、`download_slice`、`verify_rendering`,并可选用 `visual_diff`。
378
382
 
379
383
  ## 资源
380
384
 
@@ -383,10 +387,10 @@ CODESIGN_LOG_LEVEL=info
383
387
  设计还原建议优先使用:
384
388
 
385
389
  ```text
386
- list_artboards -> get_artboard_spec -> download_slice
390
+ list_artboards -> get_artboard_spec -> download_slice -> (写代码) -> verify_rendering -> visual_diff(可选)
387
391
  ```
388
392
 
389
- 预览截图只适合做视觉对比,不应作为生产切图来源。
393
+ `verify_rendering` 会自行重新拉取 spec,因此期望值不依赖写入提示词的数字。检查其 `issues` 与 `reviewRequired`,修复代码后重跑,直到 `ok: true`。`visual_diff` 是可选的额外信号:启动本地 dev server,传入其 `pageUrl`,比较多次运行的 `score`;分数下降说明某次改动损害了视觉还原度。预览截图只适合做视觉对比,不应作为生产切图来源。
390
394
 
391
395
  ## CoDesign AI 选区油猴脚本
392
396
 
@@ -185,6 +185,9 @@ export function createBrowserManager(launcher = defaultLauncher) {
185
185
  acquireHeadless() {
186
186
  return acquireCall('headless', true);
187
187
  },
188
+ acquireHeadlessIsolated() {
189
+ return acquireCall('headless', false);
190
+ },
188
191
  acquireHeaded() {
189
192
  return acquireCall('headed', false);
190
193
  },
@@ -22,6 +22,10 @@ export const ERROR_CODES = [
22
22
  'ARTIFACT_SIZE_MISMATCH',
23
23
  'ARTIFACT_MAGIC_MISMATCH',
24
24
  'ARTIFACT_PATH_INVALID',
25
+ 'CODE_FILE_INVALID',
26
+ 'VISUAL_DIFF_IMAGE_INVALID',
27
+ 'VISUAL_DIFF_ALIGNMENT',
28
+ 'VISUAL_DIFF_PAGE_INVALID',
25
29
  ];
26
30
  export class CodesignError extends Error {
27
31
  code;
@@ -0,0 +1,495 @@
1
+ // 还原度静态校验的纯函数部分:锚点解析、代码声明提取、六维度比对、盲区枚举。
2
+ // 不依赖浏览器/网络,便于单测。期望值一律由调用方传入(MCP 工具层重新拉 spec 重建)。
3
+ export const VERIFY_CHECKS = ['size', 'scale', 'color', 'typography', 'radius', 'hierarchy'];
4
+ const WINDOW_LINES = 16;
5
+ const ATTR_RE = /data-slice-id\s*=\s*["'`]([^"'`]+)["'`]/gi;
6
+ const COMMENT_RE = /\/\*\s*slice\s*[::]\s*([^*]+?)\s*\*\//gi;
7
+ const NUM = '(-?\\d+(?:\\.\\d+)?)';
8
+ const UNIT = '(px|rem|rpx|dp|pt|%)?';
9
+ function cssProp(prop) {
10
+ return new RegExp(`(?:^|[;{\\s])${prop}\\s*:\\s*${NUM}\\s*${UNIT}`, 'gi');
11
+ }
12
+ function htmlAttr(prop) {
13
+ return new RegExp(`${prop}\\s*=\\s*["']${NUM}${UNIT}["']`, 'gi');
14
+ }
15
+ const BG_SIZE_RE = new RegExp(`background-size\\s*:\\s*${NUM}\\s*${UNIT}[\\s,]+${NUM}\\s*${UNIT}`, 'gi');
16
+ const URL_RE = /(?:url\(\s*["']?|src\s*=\s*["'])([^"')>\s]+)/gi;
17
+ const COLOR_RE = /#[0-9a-fA-F]{3,8}\b|rgba?\([^)]+\)/g;
18
+ function extractAnchors(files) {
19
+ const anchors = [];
20
+ for (const file of files) {
21
+ const lines = file.text.split(/\r?\n/);
22
+ for (let i = 0; i < lines.length; i += 1) {
23
+ const line = lines[i];
24
+ for (const [pattern, kind] of [
25
+ [ATTR_RE, 'attribute'],
26
+ [COMMENT_RE, 'comment'],
27
+ ]) {
28
+ pattern.lastIndex = 0;
29
+ let match;
30
+ while ((match = pattern.exec(line)) !== null) {
31
+ const objectId = match[1].trim();
32
+ if (!objectId)
33
+ continue;
34
+ const end = Math.min(lines.length, i + WINDOW_LINES);
35
+ anchors.push({
36
+ objectId,
37
+ kind,
38
+ file: file.path,
39
+ line: i + 1,
40
+ block: lines.slice(i, end).join('\n'),
41
+ });
42
+ }
43
+ }
44
+ }
45
+ }
46
+ return anchors;
47
+ }
48
+ function firstValue(block, prop) {
49
+ const css = cssProp(prop);
50
+ const match = css.exec(block);
51
+ if (match)
52
+ return { value: Number(match[1]), unit: (match[2] ?? '').toLowerCase() };
53
+ const attr = htmlAttr(prop);
54
+ const attrMatch = attr.exec(block);
55
+ if (attrMatch)
56
+ return { value: Number(attrMatch[1]), unit: (attrMatch[2] ?? '').toLowerCase() };
57
+ return undefined;
58
+ }
59
+ function extractDeclarations(block) {
60
+ const declarations = {
61
+ width: firstValue(block, 'width'),
62
+ height: firstValue(block, 'height'),
63
+ fontSize: firstValue(block, 'font-size'),
64
+ lineHeight: firstValue(block, 'line-height'),
65
+ radius: firstValue(block, 'border-radius'),
66
+ colors: [],
67
+ assetRefs: [],
68
+ };
69
+ BG_SIZE_RE.lastIndex = 0;
70
+ const bg = BG_SIZE_RE.exec(block);
71
+ if (bg) {
72
+ declarations.backgroundSize = [
73
+ { value: Number(bg[1]), unit: (bg[2] ?? '').toLowerCase() },
74
+ { value: Number(bg[3]), unit: (bg[4] ?? '').toLowerCase() },
75
+ ];
76
+ }
77
+ let match;
78
+ COLOR_RE.lastIndex = 0;
79
+ while ((match = COLOR_RE.exec(block)) !== null)
80
+ declarations.colors.push(normalizeColor(match[0]));
81
+ URL_RE.lastIndex = 0;
82
+ while ((match = URL_RE.exec(block)) !== null)
83
+ declarations.assetRefs.push(match[1]);
84
+ return declarations;
85
+ }
86
+ function normalizeColor(raw) {
87
+ const value = raw.trim().toLowerCase();
88
+ if (value.startsWith('#')) {
89
+ const hex = value.slice(1);
90
+ if (hex.length === 3)
91
+ return `#${hex.split('').map((c) => c + c).join('')}`;
92
+ return `#${hex}`;
93
+ }
94
+ const numbers = value.match(/\d+(?:\.\d+)?/g) ?? [];
95
+ return `rgba(${numbers.slice(0, 4).join(',')})`;
96
+ }
97
+ // 统一以 px 为基准:rem 用 remBasePx 换算,px 原值,
98
+ // rpx/dp/pt 只在与目标平台同单位时按数值直接比较(跨单位无法静态换算)。
99
+ function toPixels(value, platform) {
100
+ const unit = value.unit || platform.unit;
101
+ if (unit === 'rem')
102
+ return value.value * remBase(platform);
103
+ if (unit === 'px')
104
+ return value.value;
105
+ if (unit === platform.unit)
106
+ return value.value;
107
+ return undefined;
108
+ }
109
+ function remBase(platform) {
110
+ const base = platform.conversion.remBasePx;
111
+ return typeof base === 'number' && base > 0 ? base : 16;
112
+ }
113
+ function expectedPixels(value, platform) {
114
+ return platform.unit === 'rem' ? value * remBase(platform) : value;
115
+ }
116
+ function compareSize(expected, platform, actual) {
117
+ if (!actual || actual.unit === '%')
118
+ return { status: 'unverifiable' };
119
+ const actualPx = toPixels(actual, platform);
120
+ const expectedPx = expectedPixels(expected, platform);
121
+ if (actualPx == null || !Number.isFinite(expectedPx) || expectedPx <= 0)
122
+ return { status: 'unverifiable' };
123
+ const ratio = actualPx / expectedPx;
124
+ if (Math.abs(ratio - 1) <= 0.02 || Math.abs(actualPx - expectedPx) <= 1) {
125
+ return { status: 'pass', actualPx };
126
+ }
127
+ if (Math.abs(ratio - 2) <= 0.02)
128
+ return { status: 'double', actualPx };
129
+ return { status: 'mismatch', actualPx };
130
+ }
131
+ function detectScaleRefs(refs) {
132
+ const scales = new Set();
133
+ for (const ref of refs) {
134
+ const match = ref.match(/@(\d)x|[-_](\d)x\.|scale[=_-]?(\d)/i);
135
+ if (!match)
136
+ continue;
137
+ const value = Number(match[1] ?? match[2] ?? match[3]);
138
+ if ([1, 2, 3, 4].includes(value))
139
+ scales.add(value);
140
+ }
141
+ return [...scales];
142
+ }
143
+ function expectedColors(layer) {
144
+ const found = [];
145
+ const visit = (value, depth) => {
146
+ if (depth > 4 || found.length > 8)
147
+ return;
148
+ if (typeof value === 'string') {
149
+ let match;
150
+ COLOR_RE.lastIndex = 0;
151
+ while ((match = COLOR_RE.exec(value)) !== null)
152
+ found.push(normalizeColor(match[0]));
153
+ return;
154
+ }
155
+ if (Array.isArray(value)) {
156
+ for (const item of value)
157
+ visit(item, depth + 1);
158
+ return;
159
+ }
160
+ if (value && typeof value === 'object') {
161
+ for (const [key, item] of Object.entries(value)) {
162
+ if (/color|fill|stroke|background/i.test(key))
163
+ visit(item, depth + 1);
164
+ }
165
+ }
166
+ };
167
+ if (layer.fills)
168
+ visit(layer.fills, 0);
169
+ if (layer.color)
170
+ visit(layer.color, 0);
171
+ return [...new Set(found)];
172
+ }
173
+ function reviewReasons(layer) {
174
+ const reasons = [];
175
+ const extra = layer;
176
+ if (Array.isArray(extra.masks) && extra.masks.length > 0)
177
+ reasons.push('mask');
178
+ if (Array.isArray(layer.effects) && layer.effects.length > 0)
179
+ reasons.push('effect');
180
+ if (Array.isArray(layer.shadows) && layer.shadows.length > 0)
181
+ reasons.push('shadow');
182
+ const css = Array.isArray(layer.css) ? layer.css.join(' ') : (layer.css ?? '');
183
+ if (/gradient|mask|filter|backdrop-filter|blur|mix-blend/i.test(css))
184
+ reasons.push('css-complex');
185
+ if (layer.type === 'text' && !layer.content)
186
+ reasons.push('text-content-missing');
187
+ return reasons;
188
+ }
189
+ function collectOrder(nodes, output = []) {
190
+ for (const node of nodes) {
191
+ if (!node || typeof node !== 'object')
192
+ continue;
193
+ const record = node;
194
+ const id = record.object_id ?? record.objectId ?? record.id;
195
+ if (typeof id === 'string' && id && !output.includes(id))
196
+ output.push(id);
197
+ for (const key of ['children', 'layers', 'groups']) {
198
+ const child = record[key];
199
+ if (Array.isArray(child))
200
+ collectOrder(child, output);
201
+ }
202
+ }
203
+ return output;
204
+ }
205
+ function scaleFromManifest(manifest, objectId) {
206
+ const item = manifest.find((entry) => entry.object_id === objectId);
207
+ if (!item)
208
+ return [];
209
+ return [...new Set(item.exportables.map((e) => e.scale).filter((s) => typeof s === 'number'))];
210
+ }
211
+ export function verifyRendering(input) {
212
+ const checks = new Set(input.checks ?? VERIFY_CHECKS);
213
+ const expectedScale = input.scale ?? 2;
214
+ const anchors = extractAnchors(input.files);
215
+ const allLayers = [...input.layers, ...input.groups];
216
+ const layerByObjectId = new Map(allLayers.map((layer) => [layer.object_id, layer]));
217
+ const platformByObjectId = new Map([...input.platformSpec.layers, ...input.platformSpec.groups].map((layer) => [layer.objectId, layer]));
218
+ const issues = [];
219
+ const seen = new Set();
220
+ let pass = 0;
221
+ const addIssue = (issue) => {
222
+ issues.push(issue);
223
+ };
224
+ for (const anchor of anchors) {
225
+ const layer = layerByObjectId.get(anchor.objectId);
226
+ if (!layer) {
227
+ addIssue({
228
+ code: 'ANCHOR_UNRESOLVED',
229
+ dimension: 'parse',
230
+ severity: 'warning',
231
+ layerObjectId: anchor.objectId,
232
+ file: anchor.file,
233
+ line: anchor.line,
234
+ message: `anchor ${anchor.objectId} does not match any spec layer`,
235
+ });
236
+ continue;
237
+ }
238
+ seen.add(anchor.objectId);
239
+ const declarations = extractDeclarations(anchor.block);
240
+ const platformLayer = platformByObjectId.get(anchor.objectId);
241
+ if (checks.has('size') && platformLayer) {
242
+ for (const [axis, actual] of [
243
+ ['width', declarations.width],
244
+ ['height', declarations.height],
245
+ ]) {
246
+ const result = compareSize(platformLayer.rect[axis], input.platformSpec, actual);
247
+ const expectedText = `${platformLayer.rect[axis]}${platformLayer.rect.unit}`;
248
+ const actualText = actual ? `${actual.value}${actual.unit || input.platformSpec.unit}` : null;
249
+ if (result.status === 'pass') {
250
+ pass += 1;
251
+ }
252
+ else if (result.status === 'double') {
253
+ addIssue({
254
+ code: 'DOUBLE_SCALE',
255
+ dimension: 'size',
256
+ severity: 'error',
257
+ layerObjectId: anchor.objectId,
258
+ file: anchor.file,
259
+ line: anchor.line,
260
+ expected: expectedText,
261
+ actual: actualText,
262
+ message: `${axis} is about 2x the design size (2x asset must be displayed at design size)`,
263
+ });
264
+ }
265
+ else if (result.status === 'mismatch') {
266
+ addIssue({
267
+ code: 'SIZE_MISMATCH',
268
+ dimension: 'size',
269
+ severity: 'error',
270
+ layerObjectId: anchor.objectId,
271
+ file: anchor.file,
272
+ line: anchor.line,
273
+ expected: expectedText,
274
+ actual: actualText,
275
+ message: `${axis} does not match the design size`,
276
+ });
277
+ }
278
+ else {
279
+ addIssue({
280
+ code: 'UNVERIFIABLE',
281
+ dimension: 'size',
282
+ severity: 'warning',
283
+ layerObjectId: anchor.objectId,
284
+ file: anchor.file,
285
+ line: anchor.line,
286
+ expected: expectedText,
287
+ actual: actualText,
288
+ message: `${axis} cannot be statically resolved (external class, percentage, or dynamic style)`,
289
+ });
290
+ }
291
+ }
292
+ if (declarations.backgroundSize) {
293
+ const [bgWidth, bgHeight] = declarations.backgroundSize;
294
+ for (const [axis, actual] of [
295
+ ['width', bgWidth],
296
+ ['height', bgHeight],
297
+ ]) {
298
+ const result = compareSize(platformLayer.rect[axis], input.platformSpec, actual);
299
+ if (result.status === 'pass')
300
+ pass += 1;
301
+ else if (result.status !== 'unverifiable') {
302
+ addIssue({
303
+ code: result.status === 'double' ? 'DOUBLE_SCALE' : 'SIZE_MISMATCH',
304
+ dimension: 'size',
305
+ severity: 'error',
306
+ layerObjectId: anchor.objectId,
307
+ file: anchor.file,
308
+ line: anchor.line,
309
+ expected: `${platformLayer.rect[axis]}${platformLayer.rect.unit}`,
310
+ actual: `${actual.value}${actual.unit || input.platformSpec.unit}`,
311
+ message: `background-size ${axis} does not match the design size`,
312
+ });
313
+ }
314
+ }
315
+ }
316
+ }
317
+ if (checks.has('scale')) {
318
+ const assetScales = detectScaleRefs(declarations.assetRefs);
319
+ const wrong = assetScales.filter((scale) => scale !== expectedScale);
320
+ if (wrong.length > 0) {
321
+ addIssue({
322
+ code: 'WRONG_SCALE_ASSET',
323
+ dimension: 'scale',
324
+ severity: 'error',
325
+ layerObjectId: anchor.objectId,
326
+ file: anchor.file,
327
+ line: anchor.line,
328
+ expected: `${expectedScale}x`,
329
+ actual: wrong.map((s) => `${s}x`).join(','),
330
+ message: `code references a non-${expectedScale}x slice asset`,
331
+ });
332
+ }
333
+ else if (assetScales.includes(expectedScale)) {
334
+ pass += 1;
335
+ }
336
+ const available = scaleFromManifest(input.manifest, anchor.objectId);
337
+ if (available.length > 0 && !available.includes(expectedScale)) {
338
+ addIssue({
339
+ code: 'SCALE_UNAVAILABLE',
340
+ dimension: 'scale',
341
+ severity: 'error',
342
+ layerObjectId: anchor.objectId,
343
+ file: anchor.file,
344
+ line: anchor.line,
345
+ expected: `${expectedScale}x`,
346
+ actual: available.map((s) => `${s}x`).join(','),
347
+ message: `design manifest has no ${expectedScale}x export for this layer`,
348
+ });
349
+ }
350
+ }
351
+ if (checks.has('typography')) {
352
+ if (layer.fontSize != null && declarations.fontSize) {
353
+ const expectedFont = expectedPixels(layer.fontSize * input.platformSpec.scale, input.platformSpec);
354
+ const result = compareSize(expectedFont, input.platformSpec, declarations.fontSize);
355
+ if (result.status === 'pass')
356
+ pass += 1;
357
+ else if (result.status !== 'unverifiable') {
358
+ addIssue({
359
+ code: 'FONT_SIZE_MISMATCH',
360
+ dimension: 'typography',
361
+ severity: 'warning',
362
+ layerObjectId: anchor.objectId,
363
+ file: anchor.file,
364
+ line: anchor.line,
365
+ expected: `${expectedFont}${input.platformSpec.unit}`,
366
+ actual: `${declarations.fontSize.value}${declarations.fontSize.unit || input.platformSpec.unit}`,
367
+ message: 'font-size does not match the design annotation',
368
+ });
369
+ }
370
+ }
371
+ if (layer.lineHeight != null && declarations.lineHeight) {
372
+ const expectedLine = expectedPixels(layer.lineHeight * input.platformSpec.scale, input.platformSpec);
373
+ const result = compareSize(expectedLine, input.platformSpec, declarations.lineHeight);
374
+ if (result.status === 'pass')
375
+ pass += 1;
376
+ else if (result.status !== 'unverifiable') {
377
+ addIssue({
378
+ code: 'LINE_HEIGHT_MISMATCH',
379
+ dimension: 'typography',
380
+ severity: 'warning',
381
+ layerObjectId: anchor.objectId,
382
+ file: anchor.file,
383
+ line: anchor.line,
384
+ expected: `${expectedLine}${input.platformSpec.unit}`,
385
+ actual: `${declarations.lineHeight.value}${declarations.lineHeight.unit || input.platformSpec.unit}`,
386
+ message: 'line-height does not match the design annotation',
387
+ });
388
+ }
389
+ }
390
+ }
391
+ if (checks.has('radius')) {
392
+ const radius = Array.isArray(layer.radius) ? layer.radius[0] : layer.radius;
393
+ if (typeof radius === 'number' && declarations.radius) {
394
+ const expectedRadius = expectedPixels(radius * input.platformSpec.scale, input.platformSpec);
395
+ const result = compareSize(expectedRadius, input.platformSpec, declarations.radius);
396
+ if (result.status === 'pass')
397
+ pass += 1;
398
+ else if (result.status !== 'unverifiable') {
399
+ addIssue({
400
+ code: 'RADIUS_MISMATCH',
401
+ dimension: 'radius',
402
+ severity: 'warning',
403
+ layerObjectId: anchor.objectId,
404
+ file: anchor.file,
405
+ line: anchor.line,
406
+ expected: `${expectedRadius}${input.platformSpec.unit}`,
407
+ actual: `${declarations.radius.value}${declarations.radius.unit || input.platformSpec.unit}`,
408
+ message: 'border-radius does not match the design annotation',
409
+ });
410
+ }
411
+ }
412
+ }
413
+ if (checks.has('color') && declarations.colors.length > 0) {
414
+ const expected = expectedColors(layer);
415
+ if (expected.length > 0 && !expected.some((color) => declarations.colors.includes(color))) {
416
+ addIssue({
417
+ code: 'COLOR_MISMATCH',
418
+ dimension: 'color',
419
+ severity: 'warning',
420
+ layerObjectId: anchor.objectId,
421
+ file: anchor.file,
422
+ line: anchor.line,
423
+ expected: expected.slice(0, 3).join(','),
424
+ actual: declarations.colors.slice(0, 3).join(','),
425
+ message: 'no code color matches the design fills (CSS variables may need mapping)',
426
+ });
427
+ }
428
+ else if (expected.length > 0) {
429
+ pass += 1;
430
+ }
431
+ }
432
+ }
433
+ if (checks.has('hierarchy')) {
434
+ const expectedOrder = collectOrder(input.hierarchy).filter((id) => seen.has(id));
435
+ const actualOrder = anchors.map((anchor) => anchor.objectId).filter((id, index, list) => seen.has(id) && list.indexOf(id) === index);
436
+ for (let i = 0; i < Math.min(expectedOrder.length, actualOrder.length); i += 1) {
437
+ if (expectedOrder[i] === actualOrder[i])
438
+ pass += 1;
439
+ else {
440
+ const first = anchors.find((anchor) => anchor.objectId === actualOrder[i]);
441
+ addIssue({
442
+ code: 'HIERARCHY_ORDER',
443
+ dimension: 'hierarchy',
444
+ severity: 'warning',
445
+ layerObjectId: actualOrder[i],
446
+ file: first?.file ?? '',
447
+ line: first?.line ?? 0,
448
+ expected: expectedOrder[i],
449
+ actual: actualOrder[i],
450
+ message: 'anchor order differs from the design hierarchy',
451
+ });
452
+ break;
453
+ }
454
+ }
455
+ }
456
+ const unusedSlices = input.manifest
457
+ .filter((item) => item.exportables.some((e) => e.scale === expectedScale))
458
+ .map((item) => item.object_id)
459
+ .filter((id) => !seen.has(id));
460
+ for (const objectId of unusedSlices) {
461
+ addIssue({
462
+ code: 'SLICE_UNUSED',
463
+ dimension: 'asset',
464
+ severity: 'error',
465
+ layerObjectId: objectId,
466
+ file: '',
467
+ line: 0,
468
+ message: `design has a ${expectedScale}x slice but no code anchor uses it`,
469
+ });
470
+ }
471
+ const reviewRequired = [];
472
+ for (const layer of allLayers) {
473
+ const reasons = reviewReasons(layer);
474
+ if (reasons.length === 0)
475
+ continue;
476
+ const anchor = anchors.find((item) => item.objectId === layer.object_id);
477
+ reviewRequired.push({
478
+ layerObjectId: layer.object_id,
479
+ name: layer.name,
480
+ reasons,
481
+ file: anchor?.file,
482
+ line: anchor?.line,
483
+ });
484
+ }
485
+ const fail = issues.filter((issue) => issue.severity === 'error').length;
486
+ const warn = issues.filter((issue) => issue.severity === 'warning').length;
487
+ return {
488
+ ok: fail === 0,
489
+ summary: { pass, fail, warn },
490
+ issues,
491
+ reviewRequired,
492
+ anchors: anchors.length,
493
+ checkedSlices: input.manifest.filter((item) => item.exportables.some((e) => e.scale === expectedScale)).length,
494
+ };
495
+ }