dsh-desktop-kit 2.24.1 → 2.31.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. package/CHANGELOG.md +85 -10
  2. package/README.en.md +102 -0
  3. package/README.md +223 -256
  4. package/client.js +1 -1
  5. package/docs/ARCHITECTURE.md +9 -6
  6. package/docs/COMPATIBILITY.md +2 -1
  7. package/docs/LAPTOP-INSTALL.md +9 -5
  8. package/docs/MEASURED.md +25 -0
  9. package/docs/PROPOSAL-2.25-quality-pipeline.md +435 -0
  10. package/docs/PROPOSAL-NEXUM-FINDINGS.md +259 -0
  11. package/docs/TEST-2.30.0.md +83 -0
  12. package/docs/TEST-2.31.0.md +61 -0
  13. package/docs/UPGRADING.md +3 -1
  14. package/docs/images/capability-map-2.30.png +0 -0
  15. package/docs/images/hero-2.30.png +0 -0
  16. package/docs/images/hero-2.31.png +0 -0
  17. package/docs/images/quality-pipeline-2.30.png +0 -0
  18. package/docs/measured.json +30 -0
  19. package/docs/preview/capability-map-2.30.html +106 -0
  20. package/docs/preview/hero-2.30.html +133 -0
  21. package/docs/preview/hero-2.31.html +133 -0
  22. package/docs/preview/quality-pipeline-2.30.html +142 -0
  23. package/docs/preview/readme-visuals.css +111 -0
  24. package/doctor.ps1 +161 -142
  25. package/index.js +82 -5
  26. package/install.ps1 +178 -99
  27. package/lib/kit-diagnostics.js +780 -0
  28. package/package.json +15 -5
  29. package/plugins/dsh-agent-extensions/lib/routing.js +4 -0
  30. package/plugins/dsh-agent-extensions/lib/scaffold.js +152 -27
  31. package/plugins/dsh-agent-extensions/lib/settings.js +19 -0
  32. package/plugins/dsh-agent-extensions/lib/swarm.js +6 -2
  33. package/plugins/dsh-browser-qa/index.js +202 -9
  34. package/plugins/dsh-browser-qa/lib/design-more.js +688 -0
  35. package/plugins/dsh-browser-qa/lib/extras.js +1313 -0
  36. package/plugins/dsh-browser-qa/lib/pages.js +4 -3
  37. package/plugins/dsh-browser-qa/lib/png.js +190 -0
  38. package/plugins/dsh-browser-qa/lib/ui-gate.js +171 -31
  39. package/plugins/dsh-i18n/README.md +36 -0
  40. package/plugins/dsh-i18n/cordis.patch.yml +3 -0
  41. package/plugins/dsh-i18n/index.js +294 -0
  42. package/plugins/dsh-i18n/lib/lang.js +179 -0
  43. package/plugins/dsh-i18n/package.json +29 -0
  44. package/plugins/dsh-integrations/lib/job-sandbox.ps1 +1 -1
  45. package/plugins/dsh-profile-transfer/bootstrap/install-on-clean-machine.ps1 +1 -1
  46. package/plugins/dsh-quality-pipeline/README.md +53 -0
  47. package/plugins/dsh-quality-pipeline/cordis.patch.yml +3 -0
  48. package/plugins/dsh-quality-pipeline/index.js +647 -0
  49. package/plugins/dsh-quality-pipeline/lib/acceptance.js +132 -0
  50. package/plugins/dsh-quality-pipeline/lib/autostart.js +159 -0
  51. package/plugins/dsh-quality-pipeline/lib/design.js +123 -0
  52. package/plugins/dsh-quality-pipeline/lib/machine.js +312 -0
  53. package/plugins/dsh-quality-pipeline/lib/prework.js +215 -0
  54. package/plugins/dsh-quality-pipeline/lib/release.js +53 -0
  55. package/plugins/dsh-quality-pipeline/lib/schema.js +256 -0
  56. package/plugins/dsh-quality-pipeline/lib/store.js +114 -0
  57. package/plugins/dsh-quality-pipeline/lib/text.js +109 -0
  58. package/plugins/dsh-quality-pipeline/package.json +33 -0
  59. package/plugins/dsh-remote-ops/README.md +38 -0
  60. package/plugins/dsh-remote-ops/cordis.patch.yml +3 -0
  61. package/plugins/dsh-remote-ops/index.js +268 -0
  62. package/plugins/dsh-remote-ops/lib/hosts.js +118 -0
  63. package/plugins/dsh-remote-ops/lib/ssh.js +96 -0
  64. package/plugins/dsh-remote-ops/lib/state.js +66 -0
  65. package/plugins/dsh-remote-ops/package.json +31 -0
  66. package/plugins/dsh-skill-autopilot/index.js +204 -15
  67. package/skills/a11y-audit/SKILL.md +67 -0
  68. package/skills/cms-ops/SKILL.md +74 -0
  69. package/skills/design-system/SKILL.md +100 -0
  70. package/skills/legal-ru-web/SKILL.md +68 -0
  71. package/skills/manifest.json +38 -18
  72. package/skills/release-pipeline/SKILL.md +67 -0
  73. package/skills/ui-batch/SKILL.md +60 -0
  74. package/skills/web-build/SKILL.md +106 -0
  75. package/skills/web-build/recipes/form.md +16 -0
  76. package/skills/web-build/recipes/payment.md +16 -0
  77. package/skills/web-build/recipes/review.md +16 -0
  78. package/skills-baseline.json +201 -5
  79. package/uninstall.ps1 +1 -1
  80. package/skills/ui-design-system/references/accessibility-and-responsive.md +0 -50
  81. package/skills/ui-design-system/references/tokens-and-components.md +0 -67
  82. package/skills/ui-design-system/references/visual-qa.md +0 -44
  83. package/skills/visual-qa/references/commands.md +0 -32
  84. /package/skills/{ui-craft/SKILL.md → design-system/references/ui-craft.md} +0 -0
  85. /package/skills/{ui-design-system/SKILL.md → design-system/references/ui-design-system.md} +0 -0
  86. /package/skills/{visual-qa/SKILL.md → ui-batch/references/visual-qa.md} +0 -0
@@ -0,0 +1,688 @@
1
+ /**
2
+ * Design depth: palette contrast, cross-page consistency, content junk,
3
+ * interactive states, owner rules and the assembled design report.
4
+ *
5
+ * Every check is a browser question, not a taste opinion: it returns numbers
6
+ * and elements, so the model can fix the right thing without a screenshot
7
+ * argument.
8
+ */
9
+ import fs from "node:fs";
10
+ import path from "node:path";
11
+
12
+ import { withSession } from "./pages.js";
13
+ import { normalizeTarget, normalizeViewport, resolveOutDir, slugForTarget } from "./qa.js";
14
+
15
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
16
+
17
+ const COLOR = /^(?:#(?:[0-9a-f]{3,8})|rgba?\([^)]+\)|hsla?\([^)]+\)|transparent)$/iu;
18
+
19
+ function parseColor(value) {
20
+ const text = String(value ?? "").trim();
21
+ if (text === "transparent") return [0, 0, 0, 0];
22
+ const hex = text.match(/^#([0-9a-f]{3,8})$/iu);
23
+ if (hex) {
24
+ let raw = hex[1];
25
+ if (raw.length === 3) raw = [...raw].map((char) => char + char).join("");
26
+ if (raw.length === 6) raw += "ff";
27
+ if (raw.length !== 8) return null;
28
+ return [0, 2, 4, 6].map((at) => Number.parseInt(raw.slice(at, at + 2), 16));
29
+ }
30
+ const rgb = text.match(/^rgba?\(([^)]+)\)$/iu);
31
+ if (rgb) {
32
+ const parts = rgb[1].split(/[,\s/]+/u).filter(Boolean).map(Number);
33
+ if (parts.length < 3 || parts.some((item) => Number.isNaN(item))) return null;
34
+ return [parts[0], parts[1], parts[2], parts.length > 3 ? parts[3] : 1];
35
+ }
36
+ return null;
37
+ }
38
+
39
+ function luminance(rgb) {
40
+ const channel = (value) => {
41
+ const v = value / 255;
42
+ return v <= 0.03928 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4;
43
+ };
44
+ return 0.2126 * channel(rgb[0]) + 0.7152 * channel(rgb[1]) + 0.0722 * channel(rgb[2]);
45
+ }
46
+
47
+ function ratio(a, b) {
48
+ const left = luminance(a);
49
+ const right = luminance(b);
50
+ return (Math.max(left, right) + 0.05) / (Math.min(left, right) + 0.05);
51
+ }
52
+
53
+ /** Deuteranopia simulation: a coarse but honest red/green check. */
54
+ function simulateDeuteranopia([r, g, b]) {
55
+ return [
56
+ Math.round(0.625 * r + 0.375 * g),
57
+ Math.round(0.7 * r + 0.3 * g),
58
+ Math.round(0.3 * g + 0.7 * b),
59
+ ];
60
+ }
61
+
62
+ /* ------------------------------------------------------------------ */
63
+ /* tokens: palette contrast matrix */
64
+ /* ------------------------------------------------------------------ */
65
+
66
+ function tokensProbe() {
67
+ const tokens = {};
68
+ const text = [];
69
+ for (const sheet of document.styleSheets) {
70
+ let rules;
71
+ try {
72
+ rules = sheet.cssRules;
73
+ } catch {
74
+ continue;
75
+ }
76
+ if (!rules) continue;
77
+ for (const rule of rules) {
78
+ if (!rule.cssText || !rule.cssText.includes("--")) {
79
+ if (rule.cssRules) {
80
+ for (const inner of rule.cssRules) if (inner.cssText) text.push(inner.cssText);
81
+ }
82
+ continue;
83
+ }
84
+ text.push(rule.cssText);
85
+ }
86
+ }
87
+ for (const block of text) {
88
+ for (const match of block.matchAll(/--([\w-]+)\s*:\s*([^;}]+)/gu)) {
89
+ const name = match[1];
90
+ const value = match[2].trim();
91
+ if (!/^#|^rgb|^hsl/u.test(value)) continue;
92
+ if (tokens[name] === undefined) tokens[name] = value;
93
+ }
94
+ }
95
+ const root = getComputedStyle(document.documentElement);
96
+ return {
97
+ tokens,
98
+ rootSample: {
99
+ color: root.color,
100
+ background: root.backgroundColor,
101
+ fontSize: root.fontSize,
102
+ fontFamily: root.fontFamily,
103
+ },
104
+ };
105
+ }
106
+
107
+ export const TOKENS_EXPRESSION = `(${tokensProbe.toString()})()`;
108
+
109
+ const ROLES = {
110
+ text: /(?:^|[-_])(?:text|ink|fg|foreground|body)(?:[-_]|$)/iu,
111
+ muted: /(?:muted|secondary|subtle|dim)/iu,
112
+ accent: /(?:accent|brand|primary|copper|cta)/iu,
113
+ bg: /(?:^|[-_])(?:bg|background|surface|paper|canvas|base)(?:[-_]|$)/iu,
114
+ border: /(?:border|divider|line|stroke)/iu,
115
+ link: /(?:link|anchor)/iu,
116
+ focus: /(?:focus|ring|outline)/iu,
117
+ status: /(?:danger|error|success|warn|ok|red|green)/iu,
118
+ };
119
+
120
+ function roleOf(name) {
121
+ for (const [role, pattern] of Object.entries(ROLES)) if (pattern.test(name)) return role;
122
+ return "";
123
+ }
124
+
125
+ export async function runTokens(options = {}) {
126
+ const target = normalizeTarget(options.target ?? options.url, { cwd: options.cwd ?? process.cwd() });
127
+ const viewport = normalizeViewport(options);
128
+ const stage = await withSession({ ...options, target: options.target ?? options.url }, async ({ session, page }) => {
129
+ await page.setViewport(viewport.width, viewport.height);
130
+ const navigation = await page.navigate(target.url, { timeoutMs: options.timeoutMs ?? 30_000, signal: options.signal });
131
+ const data = await page.evaluate(TOKENS_EXPRESSION, { timeoutMs: 10_000 });
132
+ return { data, finalUrl: navigation.finalUrl, chrome: session.chromeInfo() };
133
+ });
134
+ const raw = stage.data ?? { tokens: {}, rootSample: {} };
135
+ const entries = Object.entries(raw.tokens ?? {}).map(([name, value]) => ({ name, value, role: roleOf(name), rgb: parseColor(value) })).filter((item) => item.rgb);
136
+ const byRole = (role) => entries.filter((item) => item.role === role);
137
+ const pairs = [];
138
+ const failures = [];
139
+ const addPair = (fg, bg, kind) => {
140
+ if (!fg || !bg) return;
141
+ const value = Math.round(ratio(fg.rgb, bg.rgb) * 100) / 100;
142
+ const required = kind === "large" ? 3 : 4.5;
143
+ const row = { fg: fg.name, bg: bg.name, ratio: value, required, ok: value >= required, kind };
144
+ pairs.push(row);
145
+ if (!row.ok) failures.push(row);
146
+ };
147
+ for (const fg of byRole("text")) for (const bg of byRole("bg")) addPair(fg, bg, "normal");
148
+ for (const fg of byRole("muted")) for (const bg of byRole("bg")) addPair(fg, bg, "normal");
149
+ for (const fg of byRole("link")) for (const bg of byRole("bg")) addPair(fg, bg, "normal");
150
+ for (const fg of byRole("accent")) for (const bg of byRole("bg")) addPair(fg, bg, "large");
151
+ for (const fg of byRole("border")) for (const bg of byRole("bg")) addPair(fg, bg, "large");
152
+ for (const fg of byRole("focus")) for (const bg of byRole("bg")) addPair(fg, bg, "large");
153
+ const blind = [];
154
+ for (const fg of byRole("status")) for (const bg of byRole("status")) {
155
+ if (fg.name === bg.name) continue;
156
+ const a = simulateDeuteranopia(fg.rgb);
157
+ const b = simulateDeuteranopia(bg.rgb);
158
+ const distance = Math.round(Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b[2]));
159
+ if (distance < 60) blind.push({ a: fg.name, b: bg.name, distance, note: "цвета статусов неразличимы при дейтеранопии" });
160
+ }
161
+ const ok = failures.length === 0 && entries.length > 0;
162
+ const lines = [
163
+ `browser_qa tokens: ${stage.finalUrl} · токенов-цветов ${entries.length}`,
164
+ `пар проверено ${pairs.length} · ниже нормы ${failures.length}`,
165
+ ...failures.slice(0, 15).map((row) => ` FAIL ${row.fg} на ${row.bg}: ${row.ratio}:1 < ${row.required} (${row.kind})`),
166
+ ...blind.slice(0, 5).map((row) => ` warn ${row.a} ↔ ${row.b}: расстояние ${row.distance} (${row.note})`),
167
+ entries.length === 0 ? "Токены не найдены: нужны CSS-переменные --* с цветами в :root" : "",
168
+ ok ? "Итог: PASS — палитра проходит по контрасту" : "Итог: FAIL — есть пары ниже нормы (WCAG 2.2: 4.5:1 текст, 3:1 крупный и границы)",
169
+ ].filter(Boolean);
170
+ return {
171
+ ok,
172
+ action: "tokens",
173
+ target: { url: target.url, finalUrl: stage.finalUrl },
174
+ tokens: entries.length,
175
+ pairs,
176
+ failures,
177
+ blind,
178
+ text: lines.join("\n"),
179
+ };
180
+ }
181
+
182
+ /* ------------------------------------------------------------------ */
183
+ /* consistency across pages */
184
+ /* ------------------------------------------------------------------ */
185
+
186
+ function consistencyProbe() {
187
+ const pick = (selectors) => {
188
+ for (const selector of selectors) {
189
+ const el = document.querySelector(selector);
190
+ if (el) return el;
191
+ }
192
+ return null;
193
+ };
194
+ const container = pick(['[class*="wrap"]', '[class*="container"]', '[class*="shell"]', "main", "body"]);
195
+ const h1 = document.querySelector("h1");
196
+ const h2 = document.querySelector("h2");
197
+ const section = document.querySelector("section");
198
+ const styleOf = (el) => (el ? getComputedStyle(el) : null);
199
+ const px = (value) => Math.round(parseFloat(value) || 0);
200
+ const cStyle = styleOf(container);
201
+ const sStyle = styleOf(section);
202
+ return {
203
+ containerWidth: container ? Math.round(container.getBoundingClientRect().width) : 0,
204
+ maxWidth: cStyle ? cStyle.maxWidth : "",
205
+ h1: h1 ? px(styleOf(h1).fontSize) : 0,
206
+ h2: h2 ? px(styleOf(h2).fontSize) : 0,
207
+ sectionPaddingTop: sStyle ? px(sStyle.paddingTop) : 0,
208
+ sectionPaddingBottom: sStyle ? px(sStyle.paddingBottom) : 0,
209
+ radius: sStyle ? sStyle.borderTopLeftRadius : "",
210
+ viewport: window.innerWidth,
211
+ docWidth: document.documentElement.scrollWidth,
212
+ };
213
+ }
214
+
215
+ export const CONSISTENCY_EXPRESSION = `(${consistencyProbe.toString()})()`;
216
+
217
+ function median(values) {
218
+ const list = values.filter((value) => Number.isFinite(value) && value > 0).sort((a, b) => a - b);
219
+ if (list.length === 0) return 0;
220
+ return list[Math.floor(list.length / 2)];
221
+ }
222
+
223
+ export async function runConsistency(options = {}) {
224
+ const urls = Array.isArray(options.urls) && options.urls.length > 0 ? options.urls.slice(0, 8) : [];
225
+ if (urls.length < 2) throw new Error("consistency: нужны 2+ URL");
226
+ const viewport = normalizeViewport(options);
227
+ const rows = [];
228
+ for (const url of urls) {
229
+ const target = normalizeTarget(url, { cwd: options.cwd ?? process.cwd() });
230
+ const data = await withSession({ ...options, target: url }, async ({ page }) => {
231
+ await page.setViewport(viewport.width, viewport.height);
232
+ await page.navigate(target.url, { timeoutMs: options.timeoutMs ?? 30_000, signal: options.signal });
233
+ return page.evaluate(CONSISTENCY_EXPRESSION, { timeoutMs: 8_000 });
234
+ });
235
+ rows.push({ url: target.url, ...(data ?? {}) });
236
+ }
237
+ const numbers = ["containerWidth", "h1", "h2", "sectionPaddingTop", "sectionPaddingBottom"];
238
+ const medians = Object.fromEntries(numbers.map((key) => [key, median(rows.map((row) => Number(row[key])))]));
239
+ const outliers = [];
240
+ for (const key of numbers) {
241
+ const base = medians[key];
242
+ if (!base) continue;
243
+ for (const row of rows) {
244
+ const value = Number(row[key]);
245
+ if (!value) continue;
246
+ const drift = Math.abs(value - base) / base;
247
+ if (drift > 0.15) outliers.push({ key, url: row.url, value, median: base, drift: Math.round(drift * 100) });
248
+ }
249
+ }
250
+ const ok = outliers.length === 0;
251
+ const lines = [
252
+ `browser_qa consistency: ${rows.length} страниц @ ${viewport.width}x${viewport.height}`,
253
+ `медианы: контейнер ${medians.containerWidth}px · h1 ${medians.h1}px · h2 ${medians.h2}px · паддинги ${medians.sectionPaddingTop}/${medians.sectionPaddingBottom}px`,
254
+ ...rows.map((row) => ` ${row.containerWidth}px контейнер · h1 ${row.h1} · h2 ${row.h2} · секция ${row.sectionPaddingTop}/${row.sectionPaddingBottom} — ${row.url}`),
255
+ ...outliers.slice(0, 15).map((row) => ` FAIL ${row.key}: ${row.value} против медианы ${row.median} (+${row.drift}%) — ${row.url}`),
256
+ ok ? "Итог: PASS — страницы согласованы" : "Итог: FAIL — страница выбивается из общей сетки",
257
+ ];
258
+ return { ok, action: "consistency", rows, medians, outliers, text: lines.join("\n") };
259
+ }
260
+
261
+ /* ------------------------------------------------------------------ */
262
+ /* content junk and images */
263
+ /* ------------------------------------------------------------------ */
264
+
265
+
266
+ function contentProbe() {
267
+ const JUNK = /(?:пример\s+(?:отзыв|текст|заголов)|lorem ipsum|ipsum dolor|todo|fixme|заглушк|placeholder|sample\s+text|тестов(?:ые|ый)\s+(?:данн|запис)|рыба\s+текста)/iu;
268
+ const issues = [];
269
+ const push = (rule, severity, node, detail) => {
270
+ if (issues.length < 120) issues.push({ rule, severity, node, detail });
271
+ };
272
+ const visible = (el) => {
273
+ const style = getComputedStyle(el);
274
+ const rect = el.getBoundingClientRect();
275
+ return style.display !== "none" && style.visibility !== "hidden" && rect.width >= 1 && rect.height >= 1;
276
+ };
277
+ const path = (el) => {
278
+ const parts = [];
279
+ let node = el;
280
+ while (node && node.nodeType === 1 && parts.length < 4) {
281
+ let part = node.tagName.toLowerCase();
282
+ if (node.id) { part += `#${node.id}`; parts.unshift(part); break; }
283
+ const cls = (node.getAttribute("class") || "").trim().split(/\s+/u).filter(Boolean).slice(0, 2);
284
+ if (cls.length > 0) part += `.${cls.join(".")}`;
285
+ parts.unshift(part);
286
+ node = node.parentElement;
287
+ }
288
+ return parts.join(" > ");
289
+ };
290
+
291
+ /* Placeholder and demo text. */
292
+ const junk = [];
293
+ for (const el of document.querySelectorAll("p, li, h1, h2, h3, blockquote, figcaption, [class*='text']")) {
294
+ if (!visible(el)) continue;
295
+ const text = (el.textContent || "").replace(/\s+/gu, " ").trim();
296
+ if (text.length < 8 || text.length > 400) continue;
297
+ if (JUNK.test(text)) junk.push({ node: path(el), text: text.slice(0, 80) });
298
+ }
299
+ for (const item of junk.slice(0, 15)) push("placeholder-text", "serious", item.node, `демо-текст: «${item.text}»`);
300
+
301
+ /* Empty sections: no text, no links, no media. */
302
+ for (const section of document.querySelectorAll("section, [data-section]")) {
303
+ if (!visible(section)) continue;
304
+ const text = (section.textContent || "").replace(/\s+/gu, "").length;
305
+ const media = section.querySelectorAll("img, video, svg, iframe, picture").length;
306
+ const links = section.querySelectorAll("a[href]").length;
307
+ if (text < 20 && media === 0 && links === 0) push("empty-section", "moderate", path(section), "секция пустая: ни текста, ни ссылок, ни медиа");
308
+ }
309
+
310
+ /* Heading duplicates. */
311
+ const h1 = [...document.querySelectorAll("h1")].filter(visible);
312
+ if (h1.length > 1) push("h1-many", "moderate", path(h1[1]), `h1 на странице ${h1.length}`);
313
+ const seen = new Map();
314
+ for (const heading of document.querySelectorAll("h2, h3")) {
315
+ if (!visible(heading)) continue;
316
+ const text = (heading.textContent || "").replace(/\s+/gu, " ").trim().toLowerCase();
317
+ if (text.length < 3) continue;
318
+ if (seen.has(text)) push("heading-duplicate", "minor", path(heading), `заголовок повторяется: «${text.slice(0, 50)}»`);
319
+ else seen.set(text, heading);
320
+ }
321
+
322
+ /* Images: aspect drift, missing dimensions, lazy below the fold, placeholders. */
323
+ const images = [...document.querySelectorAll("img")].filter(visible);
324
+ const ratios = [];
325
+ let missingDims = 0;
326
+ let lazyMissing = 0;
327
+ let placeholders = 0;
328
+ for (const img of images) {
329
+ const rect = img.getBoundingClientRect();
330
+ if (rect.width > 8 && rect.height > 8) ratios.push(rect.width / rect.height);
331
+ if (!img.getAttribute("width") || !img.getAttribute("height")) missingDims += 1;
332
+ const src = img.currentSrc || img.src || "";
333
+ if (/placeholder|placehold|via\.placeholder|data:image\/(?:gif|svg)/iu.test(src)) placeholders += 1;
334
+ if (rect.top + window.scrollY > window.innerHeight * 1.5 && img.getAttribute("loading") !== "lazy") lazyMissing += 1;
335
+ }
336
+ const mean = ratios.length > 0 ? ratios.reduce((sum, value) => sum + value, 0) / ratios.length : 0;
337
+ const spread = ratios.length > 1 ? Math.sqrt(ratios.reduce((sum, value) => sum + (value - mean) ** 2, 0) / ratios.length) : 0;
338
+ if (ratios.length > 2 && spread / (mean || 1) > 0.35) {
339
+ push("image-ratios", "moderate", "img", `разброс пропорций ${Math.round((spread / (mean || 1)) * 100)}% — фото «разного размера»`);
340
+ }
341
+ if (missingDims > 0) push("image-dims", "moderate", "img", `${missingDims} изображений без width/height (сдвиг раскладки)`);
342
+ if (lazyMissing > 0) push("image-lazy", "minor", "img", `${lazyMissing} изображений ниже фолда без loading=lazy`);
343
+ if (placeholders > 0) push("image-placeholder", "serious", "img", `${placeholders} изображений-заглушек`);
344
+
345
+ const counts = { serious: 0, moderate: 0, minor: 0 };
346
+ for (const issue of issues) counts[issue.severity] = (counts[issue.severity] || 0) + 1;
347
+ return {
348
+ counts,
349
+ issues,
350
+ stats: {
351
+ junk: junk.length,
352
+ images: images.length,
353
+ missingDims,
354
+ lazyMissing,
355
+ placeholders,
356
+ ratioSpread: Math.round((spread / (mean || 1)) * 100),
357
+ },
358
+ };
359
+ }
360
+
361
+ export const CONTENT_EXPRESSION = `(${contentProbe.toString()})()`;
362
+
363
+ export async function runContent(options = {}) {
364
+ const target = normalizeTarget(options.target ?? options.url, { cwd: options.cwd ?? process.cwd() });
365
+ const viewport = normalizeViewport(options);
366
+ const stage = await withSession({ ...options, target: options.target ?? options.url }, async ({ page }) => {
367
+ await page.setViewport(viewport.width, viewport.height);
368
+ const navigation = await page.navigate(target.url, { timeoutMs: options.timeoutMs ?? 30_000, signal: options.signal });
369
+ const data = await page.evaluate(CONTENT_EXPRESSION, { timeoutMs: 10_000 });
370
+ return { data, finalUrl: navigation.finalUrl };
371
+ });
372
+ const raw = stage.data ?? { counts: {}, issues: [], stats: {} };
373
+ const counts = raw.counts ?? { serious: 0, moderate: 0, minor: 0 };
374
+ const ok = counts.serious === 0;
375
+ const lines = [
376
+ `browser_qa content: ${stage.finalUrl}`,
377
+ `serious ${counts.serious ?? 0} · moderate ${counts.moderate ?? 0} · minor ${counts.minor ?? 0} · изображений ${raw.stats?.images ?? 0}`,
378
+ ...(raw.issues ?? []).slice(0, 15).map((issue) => ` ${issue.severity === "serious" ? "FAIL" : issue.severity === "moderate" ? "warn" : "info"} ${issue.rule}: ${issue.detail}`),
379
+ ok ? "Итог: PASS — демо-текста и заглушек нет" : "Итог: FAIL — на странице демо-контент или заглушки",
380
+ ];
381
+ return { ok, action: "content", target: { url: target.url, finalUrl: stage.finalUrl }, counts, stats: raw.stats, issues: raw.issues, text: lines.join("\n") };
382
+ }
383
+
384
+ /* ------------------------------------------------------------------ */
385
+ /* interactive states */
386
+ /* ------------------------------------------------------------------ */
387
+
388
+ const STATE_PROBE = `(() => {
389
+ const list = [...document.querySelectorAll("a[href], button, input, select, textarea")].filter((el) => {
390
+ const style = getComputedStyle(el);
391
+ const rect = el.getBoundingClientRect();
392
+ return style.display !== "none" && style.visibility !== "hidden" && rect.width >= 8 && rect.height >= 8;
393
+ }).slice(0, 10);
394
+ return list.map((el, index) => {
395
+ el.setAttribute("data-qa-state", String(index));
396
+ const style = getComputedStyle(el);
397
+ return {
398
+ index,
399
+ tag: el.tagName.toLowerCase(),
400
+ text: (el.getAttribute("aria-label") || el.textContent || el.value || "").replace(/\\s+/gu, " ").trim().slice(0, 40),
401
+ snapshot: {
402
+ color: style.color,
403
+ background: style.backgroundColor,
404
+ border: style.borderColor,
405
+ shadow: style.boxShadow,
406
+ transform: style.transform,
407
+ opacity: style.opacity,
408
+ outline: style.outlineStyle + " " + style.outlineWidth + " " + style.outlineColor,
409
+ transitionMs: Math.max(...(style.transitionDuration || "0s").split(",").map((part) => parseFloat(part) * (part.includes("ms") ? 1 : 1000))),
410
+ },
411
+ };
412
+ });
413
+ })()`;
414
+
415
+ const STATE_OF = (index) => `(() => {
416
+ const el = document.querySelector('[data-qa-state="${index}"]');
417
+ if (!el) return null;
418
+ const s = getComputedStyle(el);
419
+ return { color: s.color, background: s.backgroundColor, border: s.borderColor, shadow: s.boxShadow, transform: s.transform, opacity: s.opacity, outline: s.outlineStyle + " " + s.outlineWidth + " " + s.outlineColor };
420
+ })()`;
421
+
422
+ function changed(before, after) {
423
+ if (!before || !after) return false;
424
+ return ["color", "background", "border", "shadow", "transform", "opacity", "outline"].some((key) => before[key] !== after[key]);
425
+ }
426
+
427
+ export async function runStates(options = {}) {
428
+ const target = normalizeTarget(options.target ?? options.url, { cwd: options.cwd ?? process.cwd() });
429
+ const viewport = normalizeViewport(options);
430
+ return withSession({ ...options, target: options.target ?? options.url }, async ({ session, page }) => {
431
+ await page.setViewport(viewport.width, viewport.height);
432
+ const navigation = await page.navigate(target.url, { timeoutMs: options.timeoutMs ?? 30_000, signal: options.signal });
433
+ await page.cdp.send("DOM.enable", {}, 5_000);
434
+ try {
435
+ await page.cdp.send("CSS.enable", {}, 5_000);
436
+ } catch {
437
+ /* CSS domain is optional on some Chrome builds */
438
+ }
439
+ const { root } = await page.cdp.send("DOM.getDocument", { depth: 0 }, 10_000);
440
+ const elements = (await page.evaluate(STATE_PROBE, { timeoutMs: 10_000 })) ?? [];
441
+ const rows = [];
442
+ for (const element of elements) {
443
+ const { nodeId } = await page.cdp.send("DOM.querySelector", { nodeId: root.nodeId, selector: `[data-qa-state="${element.index}"]` }, 5_000).catch(() => ({ nodeId: 0 }));
444
+ const row = { index: element.index, tag: element.tag, text: element.text, transitionMs: Math.round(element.snapshot.transitionMs || 0) };
445
+ if (nodeId) {
446
+ for (const [state, pseudo] of [["hover", ["hover"]], ["focus", ["focus", "focus-visible"]]]) {
447
+ let after = null;
448
+ try {
449
+ await page.cdp.send("CSS.forcePseudoState", { nodeId, forcedPseudoClasses: pseudo }, 5_000);
450
+ await sleep(40);
451
+ after = await page.evaluate(STATE_OF(element.index), { timeoutMs: 3_000 });
452
+ } catch {
453
+ after = null;
454
+ }
455
+ /* Some Chrome builds ignore a forced focus-visible: real focus is the fallback. */
456
+ if (state === "focus" && !changed(element.snapshot, after)) {
457
+ try {
458
+ await page.evaluate(`(() => { const el = document.querySelector('[data-qa-state="${element.index}"]'); if (el && el.focus) el.focus(); return true; })()`, { timeoutMs: 3_000 });
459
+ await sleep(40);
460
+ after = await page.evaluate(STATE_OF(element.index), { timeoutMs: 3_000 });
461
+ } catch {
462
+ /* keep the previous result */
463
+ }
464
+ }
465
+ row[state] = changed(element.snapshot, after);
466
+ try {
467
+ await page.cdp.send("CSS.forcePseudoState", { nodeId, forcedPseudoClasses: [] }, 5_000);
468
+ } catch {
469
+ /* best effort */
470
+ }
471
+ }
472
+ }
473
+ if (element.tag === "button" || element.tag === "input" || element.tag === "select" || element.tag === "textarea") {
474
+ const after = await page.evaluate(
475
+ `(() => { const el = document.querySelector('[data-qa-state="${element.index}"]'); if (!el) return null; const was = el.disabled; el.disabled = true; const s = getComputedStyle(el); const snap = { opacity: s.opacity, background: s.backgroundColor, border: s.borderColor, color: s.color, shadow: s.boxShadow, transform: s.transform, outline: s.outlineStyle + " " + s.outlineWidth + " " + s.outlineColor }; el.disabled = was; return snap; })()`,
476
+ { timeoutMs: 3_000 },
477
+ );
478
+ row.disabled = changed(element.snapshot, after);
479
+ }
480
+ rows.push(row);
481
+ }
482
+ const missingFocus = rows.filter((row) => row.focus === false);
483
+ const slow = rows.filter((row) => row.transitionMs > 250 && row.transitionMs > 0);
484
+ const missingDisabled = rows.filter((row) => row.disabled === false);
485
+ const ok = missingFocus.length === 0 && missingDisabled.length === 0;
486
+ const lines = [
487
+ `browser_qa states: ${navigation.finalUrl} @ ${viewport.width}x${viewport.height}`,
488
+ `элементов ${rows.length} · без реакции на фокус ${missingFocus.length} · без disabled-стиля ${missingDisabled.length} · движение >250мс ${slow.length}`,
489
+ ...missingFocus.slice(0, 8).map((row) => ` FAIL focus ${row.tag} «${row.text}»`),
490
+ ...missingDisabled.slice(0, 5).map((row) => ` warn disabled ${row.tag} «${row.text}»`),
491
+ ...slow.slice(0, 5).map((row) => ` warn transition ${row.transitionMs}мс у ${row.tag} «${row.text}»`),
492
+ ok ? "Итог: PASS — состояния выражены" : "Итог: FAIL — есть элементы без видимого состояния",
493
+ ];
494
+ return {
495
+ ok,
496
+ action: "states",
497
+ target: { url: target.url, finalUrl: navigation.finalUrl },
498
+ viewport: { width: viewport.width, height: viewport.height },
499
+ chrome: session.chromeInfo(),
500
+ rows,
501
+ missingFocus: missingFocus.length,
502
+ missingDisabled: missingDisabled.length,
503
+ slow: slow.length,
504
+ text: lines.join("\n"),
505
+ };
506
+ });
507
+ }
508
+
509
+ /* ------------------------------------------------------------------ */
510
+ /* owner rules */
511
+ /* ------------------------------------------------------------------ */
512
+
513
+ export const RULES_FILE = path.join(".dsh", "rules", "design.md");
514
+
515
+ export function appendRule(cwd, text) {
516
+ const rule = String(text ?? "").replace(/\s+/gu, " ").trim();
517
+ if (rule.length < 8) return { ok: false, error: "правило слишком короткое" };
518
+ const file = path.join(cwd, RULES_FILE);
519
+ fs.mkdirSync(path.dirname(file), { recursive: true });
520
+ let content = fs.existsSync(file) ? fs.readFileSync(file, "utf8") : "---\nalways: true\n---\n# Правила дизайна\n";
521
+ const line = `- ${rule}`;
522
+ if (content.toLowerCase().includes(rule.toLowerCase())) return { ok: true, duplicate: true, file, text: `Правило уже есть: ${rule}` };
523
+ if (!content.endsWith("\n")) content += "\n";
524
+ fs.writeFileSync(file, `${content}${line}\n`, "utf8");
525
+ const count = (fs.readFileSync(file, "utf8").match(/^- /gmu) ?? []).length;
526
+ return { ok: true, duplicate: false, file, count, text: `Правило добавлено (${count} всего): ${rule}` };
527
+ }
528
+
529
+ /* ------------------------------------------------------------------ */
530
+ /* benchmark: measure the references we copy from */
531
+ /* ------------------------------------------------------------------ */
532
+
533
+ export async function runBenchmark(options = {}) {
534
+ const urls = Array.isArray(options.urls) ? options.urls.slice(0, 6) : [];
535
+ if (urls.length === 0) throw new Error("benchmark: нужен urls=[…]");
536
+ const viewport = normalizeViewport(options);
537
+ const cwd = options.cwd ?? process.cwd();
538
+ const outDir = resolveOutDir(options.outDir ?? path.join(".dsh", "browser-qa"), cwd);
539
+ fs.mkdirSync(outDir, { recursive: true });
540
+ const rows = [];
541
+ for (const url of urls) {
542
+ const target = normalizeTarget(url, { cwd });
543
+ const data = await withSession({ ...options, target: url }, async ({ page }) => {
544
+ await page.setViewport(viewport.width, viewport.height);
545
+ const navigation = await page.navigate(target.url, { timeoutMs: options.timeoutMs ?? 30_000, signal: options.signal });
546
+ const metrics = await page.evaluate(CONSISTENCY_EXPRESSION, { timeoutMs: 8_000 });
547
+ const timing = await page.evaluate(
548
+ `(() => { const nav = performance.getEntriesByType("navigation")[0] || {}; const paint = performance.getEntriesByType("paint") || []; const fcp = paint.find((entry) => entry.name === "first-contentful-paint"); return { lcp: null, fcp: fcp ? Math.round(fcp.startTime) : null, ttfb: nav.responseStart ? Math.round(nav.responseStart) : null }; })()`,
549
+ { timeoutMs: 5_000 },
550
+ );
551
+ const shot = await page.screenshot({ timeoutMs: 20_000 });
552
+ const file = path.join(outDir, `ref-${slugForTarget(target.url)}-${viewport.width}x${viewport.height}.png`);
553
+ fs.writeFileSync(file, Buffer.from(shot.base64, "base64"));
554
+ return { metrics, timing, file, finalUrl: navigation.finalUrl };
555
+ });
556
+ rows.push({
557
+ url: target.url,
558
+ finalUrl: data.finalUrl,
559
+ date: new Date().toISOString().slice(0, 10),
560
+ viewport: `${viewport.width}x${viewport.height}`,
561
+ metrics: {
562
+ container: data.metrics?.containerWidth ?? 0,
563
+ maxWidth: data.metrics?.maxWidth ?? "",
564
+ h1: data.metrics?.h1 ?? 0,
565
+ h2: data.metrics?.h2 ?? 0,
566
+ sectionPadding: data.metrics?.sectionPaddingTop ?? 0,
567
+ fcp: data.timing?.fcp ?? null,
568
+ ttfb: data.timing?.ttfb ?? null,
569
+ },
570
+ screenshot: path.relative(cwd, data.file),
571
+ });
572
+ }
573
+ const referencesFile = path.join(cwd, ".dsh", "design", "references.json");
574
+ fs.mkdirSync(path.dirname(referencesFile), { recursive: true });
575
+ let existing = [];
576
+ try {
577
+ existing = JSON.parse(fs.readFileSync(referencesFile, "utf8"));
578
+ } catch {
579
+ existing = [];
580
+ }
581
+ const merged = [...existing.filter((item) => !rows.some((row) => row.url === item.url)), ...rows];
582
+ fs.writeFileSync(referencesFile, `${JSON.stringify(merged, null, 2)}\n`, "utf8");
583
+ /* Feed the mission too: G1 checks measured reference cards there. */
584
+ try {
585
+ const { readMission, writeMission } = await import("../dsh-quality-pipeline/lib/store.js");
586
+ const mission = readMission(cwd);
587
+ if (mission) {
588
+ mission.design = mission.design ?? { brief: null, variants: [], references: [] };
589
+ mission.design.references = merged.slice(0, 10);
590
+ writeMission(cwd, mission);
591
+ }
592
+ } catch {
593
+ /* the pipeline plugin may be disabled: the file alone is still useful */
594
+ }
595
+ const lines = [
596
+ `browser_qa benchmark: ${rows.length} референсов @ ${viewport.width}x${viewport.height}`,
597
+ "| контейнер | h1 | h2 | паддинг | FCP |",
598
+ "|---|---|---|---|---|",
599
+ ...rows.map((row) => `| ${row.metrics.container} | ${row.metrics.h1} | ${row.metrics.h2} | ${row.metrics.sectionPadding} | ${row.metrics.fcp ?? "—"} |`),
600
+ ...rows.map((row) => ` ${row.url} → ${row.screenshot}`),
601
+ `Файл: ${referencesFile}`,
602
+ "Итог: PASS — референсы измерены, карточки записаны (G1 принимает их как evidence).",
603
+ ];
604
+ return { ok: true, action: "benchmark", references: merged, file: referencesFile, text: lines.join("\n") };
605
+ }
606
+
607
+ /* ------------------------------------------------------------------ */
608
+ /* report */
609
+ /* ------------------------------------------------------------------ */
610
+
611
+ export async function runReport(options, deps) {
612
+ const { auditPages, runA11y, runDesign, runContent, runTokens } = deps;
613
+ const target = normalizeTarget(options.target ?? options.url, { cwd: options.cwd ?? process.cwd() });
614
+ const cwd = options.cwd ?? process.cwd();
615
+ const outDir = resolveOutDir(options.outDir ?? path.join(".dsh", "browser-qa"), cwd);
616
+ fs.mkdirSync(outDir, { recursive: true });
617
+ const [audit, a11y, design, content, tokens] = await Promise.all([
618
+ auditPages({ target: target.url, matrix: "full", outDir, screenshots: true, cwd }),
619
+ runA11y({ target: target.url, focusLimit: 6, cwd }),
620
+ runDesign({ target: target.url, cwd }),
621
+ runContent({ target: target.url, cwd }),
622
+ runTokens({ target: target.url, cwd }),
623
+ ]);
624
+ const sections = [
625
+ ["Аудит", audit.summary ? `overflow ${audit.summary.widthsWithOverflow}/${audit.summary.widthsChecked} · console ${audit.summary.consoleErrors} · markup ${audit.summary.markupIssues} · matrix ${audit.summary.matrixComplete ? "4/4" : "неполная"}` : "нет данных", audit.summary?.widthsWithOverflow === 0 && audit.summary?.matrixComplete === true],
626
+ ["Доступность", `serious ${a11y.counts?.serious ?? 0} · moderate ${a11y.counts?.moderate ?? 0} · фокус невидим ${a11y.focusInvisible ?? 0}`, a11y.ok === true],
627
+ ["Дизайн-система", `дублей ${design.stats?.duplicates ?? 0} · ритм-выбросов ${design.stats?.rhythmOutliers ?? 0} · магических px ${design.stats?.magicValues ?? 0}`, design.ok === true],
628
+ ["Контент", `serious ${content.counts?.serious ?? 0} · изображений ${content.stats?.images ?? 0}`, content.ok === true],
629
+ ["Палитра", `пар ${tokens.pairs?.length ?? 0} · ниже нормы ${tokens.failures?.length ?? 0}`, tokens.ok === true],
630
+ ];
631
+ const shots = (audit.reports ?? []).filter((report) => report.screenshot?.file).map((report) => `${report.width}px — ${path.relative(cwd, report.screenshot.file)}`);
632
+ const ok = sections.every(([, , pass]) => pass === true);
633
+ const markdown = [
634
+ `# Design QA — ${target.url}`,
635
+ "",
636
+ `Сгенерировано: ${new Date().toISOString()} · браузер ${audit.chrome?.version ?? ""}`,
637
+ "",
638
+ "| Проверка | Результат | Вердикт |",
639
+ "|---|---|---|",
640
+ ...sections.map(([name, result, pass]) => `| ${name} | ${result} | ${pass ? "PASS" : "FAIL"} |`),
641
+ "",
642
+ "## Скриншоты",
643
+ ...shots.map((line) => `- ${line}`),
644
+ "",
645
+ "## Что чинить",
646
+ ...[
647
+ ...(a11y.issues ?? []).slice(0, 8).map((issue) => `- a11y ${issue.rule}: ${issue.detail} [${issue.node}]`),
648
+ ...(design.issues ?? []).slice(0, 8).map((issue) => `- design ${issue.rule}: ${issue.detail} [${issue.node}]`),
649
+ ...(content.issues ?? []).slice(0, 8).map((issue) => `- content ${issue.rule}: ${issue.detail} [${issue.node}]`),
650
+ ...(tokens.failures ?? []).map((row) => `- tokens ${row.fg} на ${row.bg}: ${row.ratio}:1`),
651
+ ],
652
+ "",
653
+ ok ? "**Итог: PASS**" : "**Итог: FAIL** — есть открытые пункты",
654
+ "",
655
+ ].join("\n");
656
+ const file = path.join(cwd, "docs", "design-qa.md");
657
+ fs.mkdirSync(path.dirname(file), { recursive: true });
658
+ fs.writeFileSync(file, markdown, "utf8");
659
+ return {
660
+ ok,
661
+ action: "report",
662
+ file,
663
+ sections: sections.map(([name, result, pass]) => ({ name, result, pass })),
664
+ text: `browser_qa report: ${target.url}\n${sections.map(([name, result, pass]) => ` ${pass ? "PASS" : "FAIL"} ${name}: ${result}`).join("\n")}\nОтчёт: ${file}\n${ok ? "Итог: PASS" : "Итог: FAIL"}`,
665
+ };
666
+ }
667
+
668
+ /** Attach "what we take" to a measured reference card; G1 requires it. */
669
+ export function annotateReference(cwd, url, take) {
670
+ const text = String(take ?? "").replace(/\s+/gu, " ").trim();
671
+ if (text.length < 3) return { ok: false, error: "take is too short" };
672
+ const file = path.join(cwd, ".dsh", "design", "references.json");
673
+ let cards = [];
674
+ try {
675
+ cards = JSON.parse(fs.readFileSync(file, "utf8"));
676
+ } catch {
677
+ cards = [];
678
+ }
679
+ const target = cards.find((card) => card.url === url || (card.finalUrl || "") === url);
680
+ if (!target) {
681
+ return { ok: false, error: "reference not found", text: `Референс не найден: ${url}. Сначала browser_qa action=benchmark urls=[…]` };
682
+ }
683
+ target.take = text;
684
+ target.annotatedAt = new Date().toISOString().slice(0, 10);
685
+ fs.mkdirSync(path.dirname(file), { recursive: true });
686
+ fs.writeFileSync(file, `${JSON.stringify(cards, null, 2)}\n`, "utf8");
687
+ return { ok: true, file, card: target, text: `Карточка ${url}: «что берём» = ${text}` };
688
+ }