@uselazuli/cli 0.0.0-stage → 1.0.2

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 (179) hide show
  1. package/CHANGELOG.md +120 -0
  2. package/LICENSE +21 -0
  3. package/README.md +202 -2
  4. package/agents/lazuli-design-reviewer.md +30 -0
  5. package/agents/lazuli-first-look.md +22 -0
  6. package/agents/lazuli-task-tester.md +25 -0
  7. package/bin/lazuli.mjs +747 -0
  8. package/package.json +11 -4
  9. package/rules/accessibility/HYPOTHESES.md +8 -0
  10. package/rules/accessibility/_area.yaml +7 -0
  11. package/rules/accessibility/operable.yaml +100 -0
  12. package/rules/accessibility/perceivable.yaml +153 -0
  13. package/rules/accessibility/robust.yaml +24 -0
  14. package/rules/accessibility/understandable.yaml +72 -0
  15. package/rules/color/HYPOTHESES.md +27 -0
  16. package/rules/color/_area.yaml +10 -0
  17. package/rules/color/adapt.yaml +183 -0
  18. package/rules/color/create.yaml +259 -0
  19. package/rules/color/review.yaml +215 -0
  20. package/rules/color/signal.yaml +196 -0
  21. package/rules/content/HYPOTHESES.md +19 -0
  22. package/rules/content/_area.yaml +8 -0
  23. package/rules/content/review.yaml +378 -0
  24. package/rules/content/voice.yaml +144 -0
  25. package/rules/content/writing.yaml +202 -0
  26. package/rules/data/HYPOTHESES.md +11 -0
  27. package/rules/data/_area.yaml +7 -0
  28. package/rules/data/charts.yaml +189 -0
  29. package/rules/data/dashboards.yaml +141 -0
  30. package/rules/data/review.yaml +159 -0
  31. package/rules/graphic/HYPOTHESES.md +18 -0
  32. package/rules/graphic/_area.yaml +8 -0
  33. package/rules/graphic/identity.yaml +141 -0
  34. package/rules/graphic/pieces.yaml +164 -0
  35. package/rules/graphic/review.yaml +271 -0
  36. package/rules/graphic/symbol.yaml +141 -0
  37. package/rules/motion/HYPOTHESES.md +19 -0
  38. package/rules/motion/_area.yaml +7 -0
  39. package/rules/motion/micro.yaml +143 -0
  40. package/rules/motion/review.yaml +347 -0
  41. package/rules/motion/transitions.yaml +169 -0
  42. package/rules/typography/HYPOTHESES.md +12 -0
  43. package/rules/typography/_area.yaml +8 -0
  44. package/rules/typography/adapt.yaml +45 -0
  45. package/rules/typography/create.yaml +126 -0
  46. package/rules/typography/review.yaml +127 -0
  47. package/rules/ui/HYPOTHESES.md +23 -0
  48. package/rules/ui/_area.yaml +9 -0
  49. package/rules/ui/compose.yaml +246 -0
  50. package/rules/ui/grid.yaml +75 -0
  51. package/rules/ui/review.yaml +400 -0
  52. package/rules/ui/states.yaml +257 -0
  53. package/rules/ux/HYPOTHESES.md +13 -0
  54. package/rules/ux/_area.yaml +8 -0
  55. package/rules/ux/flows.yaml +164 -0
  56. package/rules/ux/forms.yaml +142 -0
  57. package/rules/ux/review.yaml +186 -0
  58. package/skills/lazuli/SKILL.md +183 -0
  59. package/skills/lazuli/procedures/create.md +29 -0
  60. package/skills/lazuli/procedures/explain-decisions.md +22 -0
  61. package/skills/lazuli/procedures/improve.md +30 -0
  62. package/skills/lazuli/procedures/remember-this.md +41 -0
  63. package/skills/lazuli/procedures/review-design.md +36 -0
  64. package/skills/lazuli/procedures/show-options.md +33 -0
  65. package/skills/lazuli-accessibility-check/SKILL.md +68 -0
  66. package/skills/lazuli-color-context-and-culture/SKILL.md +53 -0
  67. package/skills/lazuli-color-context-and-culture/references/sectors.md +26 -0
  68. package/skills/lazuli-color-palette-by-intent/SKILL.md +54 -0
  69. package/skills/lazuli-color-palette-by-intent/references/intent-chords.md +51 -0
  70. package/skills/lazuli-color-screen-review/SKILL.md +51 -0
  71. package/skills/lazuli-color-states-and-signals/SKILL.md +53 -0
  72. package/skills/lazuli-content-interface-writing/SKILL.md +53 -0
  73. package/skills/lazuli-content-voice/SKILL.md +40 -0
  74. package/skills/lazuli-data-charts-and-dashboards/SKILL.md +59 -0
  75. package/skills/lazuli-graphic-derived-pieces/SKILL.md +40 -0
  76. package/skills/lazuli-graphic-derived-pieces/references/piece-template.html +24 -0
  77. package/skills/lazuli-graphic-identity/SKILL.md +45 -0
  78. package/skills/lazuli-motion-micro-and-transitions/SKILL.md +49 -0
  79. package/skills/lazuli-typography-choose-and-pair/SKILL.md +50 -0
  80. package/skills/lazuli-typography-screen-review/SKILL.md +51 -0
  81. package/skills/lazuli-ui-composition/SKILL.md +42 -0
  82. package/skills/lazuli-ui-composition/references/option-template.html +34 -0
  83. package/skills/lazuli-ui-layout-review/SKILL.md +47 -0
  84. package/skills/lazuli-ui-states-and-system/SKILL.md +54 -0
  85. package/skills/lazuli-ux-flows-and-forms/SKILL.md +51 -0
  86. package/skills/lazuli-ux-task-test/SKILL.md +44 -0
  87. package/src/browser.mjs +162 -0
  88. package/src/commands/capture.mjs +313 -0
  89. package/src/commands/catalog.mjs +37 -0
  90. package/src/commands/check-design.mjs +463 -0
  91. package/src/commands/check-goals.mjs +57 -0
  92. package/src/commands/compare-designs.mjs +160 -0
  93. package/src/commands/draft-memo.mjs +162 -0
  94. package/src/commands/hooks.mjs +345 -0
  95. package/src/commands/install-hooks.mjs +120 -0
  96. package/src/commands/install.mjs +132 -0
  97. package/src/commands/list-rules.mjs +49 -0
  98. package/src/commands/map-page.mjs +594 -0
  99. package/src/commands/record-answers.mjs +79 -0
  100. package/src/commands/record-log.mjs +325 -0
  101. package/src/commands/record-task.mjs +250 -0
  102. package/src/commands/render-options.mjs +227 -0
  103. package/src/commands/start-project.mjs +32 -0
  104. package/src/measure/a11y.mjs +391 -0
  105. package/src/measure/asset.mjs +206 -0
  106. package/src/measure/at-rest.mjs +49 -0
  107. package/src/measure/cases.mjs +566 -0
  108. package/src/measure/chart-read.mjs +401 -0
  109. package/src/measure/chart.mjs +264 -0
  110. package/src/measure/coherence.mjs +145 -0
  111. package/src/measure/color.mjs +86 -0
  112. package/src/measure/content.mjs +82 -0
  113. package/src/measure/cvd.mjs +24 -0
  114. package/src/measure/extreme.mjs +241 -0
  115. package/src/measure/forms.mjs +150 -0
  116. package/src/measure/in-page/a11y.js +522 -0
  117. package/src/measure/in-page/color.js +348 -0
  118. package/src/measure/in-page/composition.js +1496 -0
  119. package/src/measure/in-page/contrast.js +15 -0
  120. package/src/measure/in-page/cvd.js +173 -0
  121. package/src/measure/in-page/extreme.js +377 -0
  122. package/src/measure/in-page/frames.js +781 -0
  123. package/src/measure/in-page/look.js +28 -0
  124. package/src/measure/in-page/motion-probe.js +171 -0
  125. package/src/measure/in-page/style.js +107 -0
  126. package/src/measure/in-page/svg-strokes.js +112 -0
  127. package/src/measure/in-page/svg-uses.js +50 -0
  128. package/src/measure/in-page/symbol.js +123 -0
  129. package/src/measure/in-page/type.js +269 -0
  130. package/src/measure/in-page/weight.js +207 -0
  131. package/src/measure/layout.mjs +100 -0
  132. package/src/measure/motion.mjs +509 -0
  133. package/src/measure/piece.mjs +195 -0
  134. package/src/measure/registry.mjs +253 -0
  135. package/src/measure/rhythm.mjs +81 -0
  136. package/src/measure/signature.mjs +65 -0
  137. package/src/measure/states.mjs +240 -0
  138. package/src/measure/style.mjs +13 -0
  139. package/src/measure/symbol.mjs +268 -0
  140. package/src/measure/terms.mjs +153 -0
  141. package/src/measure/tiles.mjs +20 -0
  142. package/src/measure/timeline.mjs +621 -0
  143. package/src/measure/type.mjs +167 -0
  144. package/src/measure/weight.mjs +18 -0
  145. package/src/private-strings.mjs +81 -0
  146. package/src/project/blind.mjs +70 -0
  147. package/src/project/edits.mjs +154 -0
  148. package/src/project/gate.mjs +168 -0
  149. package/src/project/lazuli-md.mjs +521 -0
  150. package/src/project/log.mjs +335 -0
  151. package/src/project/match.mjs +200 -0
  152. package/src/project/records.mjs +380 -0
  153. package/src/project/tasks.mjs +153 -0
  154. package/src/report/evaluate.mjs +27 -0
  155. package/src/report/evaluators/a11y.mjs +227 -0
  156. package/src/report/evaluators/chart.mjs +151 -0
  157. package/src/report/evaluators/coherence.mjs +103 -0
  158. package/src/report/evaluators/color.mjs +133 -0
  159. package/src/report/evaluators/content.mjs +112 -0
  160. package/src/report/evaluators/extreme.mjs +87 -0
  161. package/src/report/evaluators/forms.mjs +116 -0
  162. package/src/report/evaluators/layout.mjs +103 -0
  163. package/src/report/evaluators/motion.mjs +280 -0
  164. package/src/report/evaluators/piece.mjs +69 -0
  165. package/src/report/evaluators/rhythm.mjs +99 -0
  166. package/src/report/evaluators/states.mjs +39 -0
  167. package/src/report/evaluators/style.mjs +35 -0
  168. package/src/report/evaluators/symbol.mjs +110 -0
  169. package/src/report/evaluators/terms.mjs +49 -0
  170. package/src/report/evaluators/type.mjs +166 -0
  171. package/src/report/evaluators/weight.mjs +51 -0
  172. package/src/report/evidence.mjs +4 -0
  173. package/src/report/finding.mjs +11 -0
  174. package/src/report/format.mjs +215 -0
  175. package/src/rules/hypotheses.mjs +28 -0
  176. package/src/rules/load.mjs +274 -0
  177. package/src/rules/public-text.mjs +56 -0
  178. package/src/rules/schema.mjs +220 -0
  179. package/templates/LAZULI.md +88 -0
@@ -0,0 +1,240 @@
1
+ import fs from "node:fs/promises";
2
+ import { cdpSession } from "../browser.mjs";
3
+ import { REST_ID, restOn, restStill, restOff } from "./at-rest.mjs";
4
+
5
+ // A definition, not a cutoff: the computed properties a state is read on (on the control, its ::before,
6
+ // ::after and its first descendants). A state that changes only something else reads as no change.
7
+ export const STATE_PROPS = [
8
+ "color", "background-color", "background-image", "background-position", "background-size",
9
+ "border-color", "border-width", "border-style", "border-radius",
10
+ "outline-style", "outline-width", "outline-color", "box-shadow",
11
+ "text-decoration-line", "text-decoration-color", "font-weight", "letter-spacing",
12
+ "opacity", "transform", "translate", "scale", "rotate", "filter", "fill", "stroke",
13
+ ];
14
+ // Sampling limit, not a rule cutoff: controls forced per page, one per distinct look (the report notes the cut).
15
+ export const MAX_STATE_LOOKS = 40;
16
+ // The style element that turns transitions off while looks are read and states forced (running animations
17
+ // are finished or stopped, see at-rest.mjs); removed before the measurer returns.
18
+ export const FREEZE_ID = REST_ID;
19
+ const GROUP = "lazuli-states";
20
+ // Implementation tolerance, not a rule cutoff: one DevTools call that takes longer than this fails, so a
21
+ // stuck call cannot hold the run (the control is left out with a note; states are still cleared).
22
+ export const CDP_TIMEOUT_MS = 5000;
23
+ const MARKERS = ["disabled", "invalid", "busy", "alert", "status", "progressbar"];
24
+
25
+ let composition;
26
+ let look;
27
+
28
+ const plural = (n, one, many) => (n === 1 ? one : many);
29
+ // Equal when both looks have the same parts and properties with the same values (an ::after that exists
30
+ // only in one of them is a change).
31
+ const sameLook = (a, b) => {
32
+ const ka = Object.keys(a);
33
+ return ka.length === Object.keys(b).length && ka.every((k) => Object.hasOwn(b, k) && a[k] === b[k]);
34
+ };
35
+
36
+ // The promise, or a rejection after ms.
37
+ export function bounded(promise, ms, what) {
38
+ let timer;
39
+ const late = new Promise((_, reject) => {
40
+ timer = setTimeout(() => reject(new Error(`${what} took longer than ${ms} ms`)), ms);
41
+ });
42
+ return Promise.race([promise, late]).finally(() => clearTimeout(timer));
43
+ }
44
+
45
+ async function send(client, method, params) {
46
+ const out = await bounded(client.send(method, params), CDP_TIMEOUT_MS, method);
47
+ if (out?.exceptionDetails) throw new Error(`${method}: ${out.exceptionDetails.exception?.description ?? out.exceptionDetails.text}`);
48
+ return out;
49
+ }
50
+
51
+ // Each control in words for the report: its accessible name and its selector, numbered in document order
52
+ // when other controls share the kind, the name and the selector, so two controls never read the same.
53
+ export function describeControls(controls) {
54
+ const keyOf = (c) => `${c.kind}\n${c.label}\n${c.selector}`;
55
+ const total = new Map();
56
+ for (const c of controls) total.set(keyOf(c), (total.get(keyOf(c)) ?? 0) + 1);
57
+ const seen = new Map();
58
+ for (const c of controls) {
59
+ const k = keyOf(c);
60
+ seen.set(k, (seen.get(k) ?? 0) + 1);
61
+ const base = !c.label ? `an unlabeled ${c.kind}` : c.kind === "field" ? `the ${c.label} field` : `the "${c.label}" ${c.kind}`;
62
+ c.name = `${base} (${c.selector}${total.get(k) > 1 ? `, number ${seen.get(k)} of ${total.get(k)}` : ""})`;
63
+ }
64
+ }
65
+
66
+ // The first peer of the same kind whose self look is identical, among the allowed peers.
67
+ const alikeOf = (list, peers) => {
68
+ let checked = 0;
69
+ let lonely = 0;
70
+ const alike = [];
71
+ for (const c of list) {
72
+ const same = peers.filter((p) => p.kind === c.kind);
73
+ if (same.length === 0) {
74
+ lonely += 1;
75
+ continue;
76
+ }
77
+ checked += 1;
78
+ const twin = same.find((p) => sameLook(p.look, c.look));
79
+ if (twin) alike.push({ control: c.name, like: twin.name });
80
+ }
81
+ return { checked, alike, lonely };
82
+ };
83
+
84
+ // Forces :hover and :active on one visible, enabled button or link per distinct look and compares the look
85
+ // with the look at rest; compares disabled controls with enabled peers and aria-invalid fields with valid
86
+ // ones. Through DevTools: never clicks, never sets an attribute; a style element that turns transitions
87
+ // off is added and removed, running animations are finished or stopped (the endless ones played again),
88
+ // and every forced state is cleared before it returns.
89
+ export async function measureStates(page) {
90
+ composition ??= await fs.readFile(new URL("./in-page/composition.js", import.meta.url), "utf8");
91
+ look ??= await fs.readFile(new URL("./in-page/look.js", import.meta.url), "utf8");
92
+ const client = await cdpSession(page);
93
+ const forced = new Set();
94
+ let frozen = false;
95
+ try {
96
+ await send(client, "DOM.enable");
97
+ await send(client, "DOM.getDocument", { depth: 0 });
98
+ await send(client, "CSS.enable");
99
+ await send(client, "Runtime.enable");
100
+ frozen = true;
101
+ await send(client, "Runtime.evaluate", { expression: restOn() });
102
+
103
+ const opts = { read: "components", props: STATE_PROPS, keepPinned: true, elements: true };
104
+ const { result: reader } = await send(client, "Runtime.evaluate", { expression: `(${composition})(${JSON.stringify(opts)}, ${look})`, objectGroup: GROUP });
105
+ const { result: data } = await send(client, "Runtime.callFunctionOn", {
106
+ objectId: reader.objectId,
107
+ functionDeclaration: "function () { return { components: this.components, present: this.present, notes: this.notes }; }",
108
+ returnByValue: true,
109
+ });
110
+ const { components, present, notes: readerNotes } = data.value;
111
+ const { result: lookFn } = await send(client, "Runtime.evaluate", { expression: look, objectGroup: GROUP });
112
+ const { result: limitOut } = await send(client, "Runtime.callFunctionOn", {
113
+ objectId: lookFn.objectId,
114
+ functionDeclaration: "function () { return this.descendants; }",
115
+ returnByValue: true,
116
+ });
117
+ const limit = limitOut.value;
118
+
119
+ const indexed = components.map((c, index) => ({ ...c, index }));
120
+ const controls = indexed.filter((c) => c.kind === "button" || c.kind === "link" || c.kind === "field");
121
+ describeControls(controls);
122
+ const notes = [];
123
+ if (controls.length === 0) notes.push("No visible control, link or field to read states on.");
124
+ // The reader's descendant note counts every control on the page; this measurer notes only the ones it reads.
125
+ notes.push(...readerNotes.filter((n) => !n.includes("descendant elements")));
126
+
127
+ // Hover and pressed: one representative per distinct (kind, self look), first in document order.
128
+ const reps = [];
129
+ const keys = new Set();
130
+ for (const c of controls) {
131
+ if ((c.kind !== "button" && c.kind !== "link") || c.disabled) continue;
132
+ const key = `${c.kind} ${JSON.stringify(c.look)}`;
133
+ if (keys.has(key)) continue;
134
+ keys.add(key);
135
+ reps.push(c);
136
+ }
137
+ const looks = reps.length;
138
+ if (looks > MAX_STATE_LOOKS) notes.push(`Hover and pressed states were read on the first ${MAX_STATE_LOOKS} of ${looks} distinct control looks.`);
139
+ const hover = { checked: 0, unchanged: [] };
140
+ const active = { checked: 0, unchanged: [] };
141
+ const cut = [];
142
+ const failed = [];
143
+ for (const c of reps.slice(0, MAX_STATE_LOOKS)) {
144
+ let nodeId = null;
145
+ try {
146
+ const { result: el } = await send(client, "Runtime.callFunctionOn", {
147
+ objectId: reader.objectId,
148
+ functionDeclaration: "function (i) { return this.elements[i]; }",
149
+ arguments: [{ value: c.index }],
150
+ objectGroup: GROUP,
151
+ });
152
+ ({ nodeId } = await send(client, "DOM.requestNode", { objectId: el.objectId }));
153
+ const read = async () =>
154
+ (
155
+ await send(client, "Runtime.callFunctionOn", {
156
+ objectId: el.objectId,
157
+ functionDeclaration: "function (look, props) { return { look: look(this, props, true), descendants: this.querySelectorAll('*').length }; }",
158
+ arguments: [{ objectId: lookFn.objectId }, { value: STATE_PROPS }],
159
+ returnByValue: true,
160
+ })
161
+ ).result.value;
162
+ const force = async (states) => {
163
+ if (states.length) forced.add(nodeId);
164
+ await send(client, "CSS.forcePseudoState", { nodeId, forcedPseudoClasses: states });
165
+ if (!states.length) forced.delete(nodeId);
166
+ // A forced state can start animations: stopped again before the read (see at-rest.mjs).
167
+ else await send(client, "Runtime.evaluate", { expression: restStill() });
168
+ };
169
+ const rest = await read();
170
+ await force(["hover"]);
171
+ const hovered = await read();
172
+ await force([]);
173
+ // :active is forced alone: a style written for :hover:active is not seen (noted in the report).
174
+ await force(["active"]);
175
+ const pressed = await read();
176
+ await force([]);
177
+ if (rest.descendants > limit) cut.push(rest.descendants);
178
+ hover.checked += 1;
179
+ active.checked += 1;
180
+ if (sameLook(rest.look, hovered.look)) hover.unchanged.push(c.name);
181
+ if (sameLook(rest.look, pressed.look)) active.unchanged.push(c.name);
182
+ } catch {
183
+ // The control is left out; its forced state, if any, is cleared now (and again in finally).
184
+ failed.push(c.name);
185
+ if (nodeId !== null && forced.has(nodeId)) {
186
+ await bounded(client.send("CSS.forcePseudoState", { nodeId, forcedPseudoClasses: [] }), CDP_TIMEOUT_MS, "clear")
187
+ .then(() => forced.delete(nodeId))
188
+ .catch(() => {});
189
+ }
190
+ }
191
+ }
192
+ if (cut.length) {
193
+ notes.push(`Descendants were read on the first ${limit} of ${Math.max(...cut)} for ${cut.length} ${plural(cut.length, "control", "controls")}.`);
194
+ }
195
+ if (failed.length) {
196
+ notes.push(
197
+ `Hover and pressed states could not be read on ${failed.length} ${plural(failed.length, "control", "controls")} (a DevTools call failed or took longer than ${CDP_TIMEOUT_MS / 1000} s): ${failed.join(", ")}.`,
198
+ );
199
+ }
200
+ if (active.checked > 0) notes.push("Pressed states were read with :active forced alone; a style written for :hover:active is not seen.");
201
+
202
+ // Disabled against enabled peers, aria-invalid against valid peers, of the same kind.
203
+ const disabled = alikeOf(
204
+ controls.filter((c) => c.disabled && (c.kind === "button" || c.kind === "field")),
205
+ controls.filter((c) => !c.disabled && !c.invalid),
206
+ );
207
+ const invalid = alikeOf(
208
+ controls.filter((c) => c.invalid && c.kind === "field"),
209
+ controls.filter((c) => !c.disabled && !c.invalid),
210
+ );
211
+ if (disabled.lonely) {
212
+ notes.push(`${disabled.lonely} disabled ${plural(disabled.lonely, "control had", "controls had")} no enabled control of the same kind to compare with.`);
213
+ }
214
+ if (invalid.lonely) {
215
+ notes.push(`${invalid.lonely} ${plural(invalid.lonely, "field marked aria-invalid had", "fields marked aria-invalid had")} no valid field to compare with.`);
216
+ }
217
+ const marked = MARKERS.filter((k) => present[k] > 0);
218
+ if (marked.length) notes.push(`State markers in this render: ${marked.map((k) => `${k} ${present[k]}`).join(", ")}`);
219
+
220
+ return {
221
+ controls: controls.length,
222
+ looks,
223
+ hover,
224
+ active,
225
+ disabled: { checked: disabled.checked, alike: disabled.alike },
226
+ invalid: { checked: invalid.checked, alike: invalid.alike },
227
+ present,
228
+ notes,
229
+ };
230
+ } finally {
231
+ // Each step on its own: one failing does not skip the rest. Forced states are cleared and styles
232
+ // recomputed while transitions are still off, so nothing animates back after the style is gone.
233
+ // Every call bounded, so a stuck one cannot hold the run.
234
+ const quiet = (method, params) => bounded(client.send(method, params), CDP_TIMEOUT_MS, method).catch(() => {});
235
+ for (const nodeId of forced) await quiet("CSS.forcePseudoState", { nodeId, forcedPseudoClasses: [] });
236
+ if (frozen) await quiet("Runtime.evaluate", { expression: restOff() });
237
+ await quiet("Runtime.releaseObjectGroup", { objectGroup: GROUP });
238
+ await bounded(client.detach(), CDP_TIMEOUT_MS, "detach").catch(() => {});
239
+ }
240
+ }
@@ -0,0 +1,13 @@
1
+ import fs from "node:fs/promises";
2
+
3
+ // Sampling limit, not a rule cutoff: offenders listed per rule (the rule still counts all of them).
4
+ const MAX_OFFENDERS_LISTED = 5;
5
+
6
+ let script;
7
+
8
+ // Lets a learned rule be an executable test: a computed CSS property checked against forbid, min or max.
9
+ export async function measureStyle(page, ctx = {}) {
10
+ script ??= await fs.readFile(new URL("./in-page/style.js", import.meta.url), "utf8");
11
+ const rules = (ctx.rules ?? []).map((r) => ({ id: r.id, threshold: r.threshold }));
12
+ return page.evaluate(`(${script})(${JSON.stringify(rules)}, ${MAX_OFFENDERS_LISTED})`);
13
+ }
@@ -0,0 +1,268 @@
1
+ import fs from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { ASSET_RUN_CAP_MS, AssetInputError, loadAssetBytes, resolveAsset, withinCap } from "./asset.mjs";
4
+ import { sameTarget } from "../project/match.mjs";
5
+
6
+ // Definitions fixed before any asset was measured, never edited after a reading (not cutoffs).
7
+ // The ladder: 16 is the spec's smallest size; a size is the longer side of the symbol's box.
8
+ export const SYMBOL_SIZES = [512, 256, 128, 64, 48, 32, 24, 16];
9
+ // The two extremes a symbol is read on.
10
+ export const BACKGROUNDS = [
11
+ { name: "light", hex: "#ffffff" },
12
+ { name: "dark", hex: "#000000" },
13
+ ];
14
+ // Sampling limits, noted when they cut, and the sheet's display zoom (not rule cutoffs).
15
+ export const MAX_PARTS = 24;
16
+ export const MAX_STROKES = 50;
17
+ export const ZOOM = 8;
18
+ // Safety limit, not a rule cutoff: an SVG whose use references add more elements than this once drawn is not
19
+ // drawn at all (ten levels of ten nested uses in 2 KB draw 10^10 elements and hold the renderer until it crashes).
20
+ export const MAX_USE_COPIES = 10000;
21
+ // Layout of the render page (display only): space between tiles.
22
+ const GAP = 8;
23
+
24
+ let symbolScript;
25
+ let strokesScript;
26
+ let usesScript;
27
+ let contrastScript;
28
+
29
+ const TYPE_OF_EXT = { ".svg": "image/svg+xml", ".png": "image/png", ".ico": "image/x-icon" };
30
+ const plural = (n, one, many) => (n === 1 ? one : many);
31
+
32
+ function labelOf(target) {
33
+ const text = String(target).trim();
34
+ try {
35
+ const u = new URL(text);
36
+ if (u.protocol === "http:" || u.protocol === "https:") return decodeURIComponent(u.pathname.split("/").pop() || u.hostname);
37
+ } catch {
38
+ // a path, not a URL
39
+ }
40
+ return path.basename(text);
41
+ }
42
+
43
+ // The bytes of one file as a data URL, and its SVG text when it is an SVG.
44
+ async function loadFile(asset, browser) {
45
+ const { bytes, type } = await loadAssetBytes(asset, browser);
46
+ const mime = String(type ?? "").split(";")[0].trim().toLowerCase() || TYPE_OF_EXT[asset.ext] || "";
47
+ const svg = mime === "image/svg+xml" || asset.ext === ".svg";
48
+ return { url: `data:${svg ? "image/svg+xml" : mime};base64,${bytes.toString("base64")}`, svgText: svg ? bytes.toString("utf8") : null };
49
+ }
50
+
51
+ // The Brand symbol that serves a size below the main one: the smallest "up to <n> px" that covers it.
52
+ function servingSymbol(smaller, size) {
53
+ return smaller.filter((s) => size <= s.upTo).sort((a, b) => a.upTo - b.upTo)[0] ?? null;
54
+ }
55
+
56
+ const tilesHtml = (tiles) =>
57
+ `<!doctype html><html><head><style>html,body{margin:0;background:transparent}` +
58
+ `.t{position:absolute;top:0;display:flex;align-items:center;justify-content:center}` +
59
+ `.t img{width:100%;height:100%;object-fit:contain;display:block}</style></head><body>` +
60
+ tiles.map((t) => `<div class="t" style="left:${t.x}px;width:${t.size}px;height:${t.size}px"><img alt="" src="${t.url}"></div>`).join("") +
61
+ `</body></html>`;
62
+
63
+ // The label under a tile: its size only. The sheet is what the blind look (GR5) sees, so it carries no file
64
+ // name, host or brand.
65
+ export const sheetLabel = (size) => `${size} px`;
66
+
67
+ // The contact sheet: per background, the tiles at their real size labeled with their size, and under them
68
+ // the sizes up to 48 enlarged ZOOM times, pixelated.
69
+ export const sheetHtml = (shots) =>
70
+ `<!doctype html><html><head><style>html,body{margin:0;background:#808080;font:12px/1.3 sans-serif}` +
71
+ `.bg{width:max-content;min-width:100%}.row{display:flex;align-items:flex-end;gap:16px;padding:16px}` +
72
+ `.cell{display:flex;flex-direction:column;gap:4px;white-space:nowrap}` +
73
+ `.zoom img{image-rendering:pixelated}</style></head><body>` +
74
+ BACKGROUNDS.map(
75
+ (bg) =>
76
+ `<div class="bg" style="background:${bg.hex};color:${bg.name === "dark" ? "#ffffff" : "#000000"}">` +
77
+ `<div class="row">${shots.map((t) => `<div class="cell"><img alt="" width="${t.size}" height="${t.size}" src="${t.shot}"><span>${sheetLabel(t.size)}</span></div>`).join("")}</div>` +
78
+ `<div class="row zoom">${shots
79
+ .filter((t) => t.size <= 48)
80
+ .map((t) => `<div class="cell"><img alt="" width="${t.size * ZOOM}" height="${t.size * ZOOM}" src="${t.shot}"><span>${t.size} px x${ZOOM}</span></div>`)
81
+ .join("")}</div></div>`,
82
+ ).join("") +
83
+ `</body></html>`;
84
+
85
+ // Reads a symbol from its large size down to 16 px: silhouette kept, color parts drawn, edge contrast on light
86
+ // and dark, SVG stroke widths, and a contact sheet in ctx.dir. One context, device scale 1, every request
87
+ // aborted; the symbol is drawn through <img> (no script runs) and an SVG is read for strokes as a sanitized copy.
88
+ export async function measureSymbol(asset, ctx) {
89
+ const { browser, cwd = process.cwd(), brand, dir } = ctx;
90
+ symbolScript ??= await fs.readFile(new URL("./in-page/symbol.js", import.meta.url), "utf8");
91
+ strokesScript ??= await fs.readFile(new URL("./in-page/svg-strokes.js", import.meta.url), "utf8");
92
+ usesScript ??= await fs.readFile(new URL("./in-page/svg-uses.js", import.meta.url), "utf8");
93
+ contrastScript ??= await fs.readFile(new URL("./in-page/contrast.js", import.meta.url), "utf8");
94
+ const notes = [];
95
+
96
+ // Which Brand symbol this asset is: the main one (no range) may hand its small sizes to a symbol declared
97
+ // "up to <n> px"; a symbol with a range is read only up to n.
98
+ const symbols = brand?.symbols ?? [];
99
+ const mine = symbols.find((s) => sameTarget(s.file, asset.target, cwd)) ?? null;
100
+ let ladder = SYMBOL_SIZES;
101
+ let smaller = [];
102
+ if (mine?.upTo != null) {
103
+ ladder = SYMBOL_SIZES.filter((s) => s <= mine.upTo);
104
+ if (ladder.length === 0) throw new AssetInputError(`The Brand says ${mine.file} serves up to ${mine.upTo} px; the symbol ladder starts at 16 px.`);
105
+ } else if (mine) {
106
+ smaller = symbols.filter((s) => s.upTo != null);
107
+ }
108
+
109
+ const main = { label: labelOf(asset.target), ...(await loadFile(asset, browser)) };
110
+ const others = [];
111
+ for (const s of smaller) {
112
+ const other = resolveAsset({ target: s.file, cwd });
113
+ others.push({ label: labelOf(s.file), upTo: s.upTo, ...(await loadFile(other, browser)) });
114
+ }
115
+
116
+ const width = SYMBOL_SIZES.reduce((sum, s) => sum + s + GAP, GAP);
117
+ const context = await browser.newContext({ viewport: { width, height: SYMBOL_SIZES[0] + 2 * GAP }, deviceScaleFactor: 1 });
118
+ return withinCap(context, ctx.capMs ?? ASSET_RUN_CAP_MS, "The symbol measure", async () => {
119
+ await context.route("**/*", (route) => route.abort());
120
+ const page = await context.newPage();
121
+ await page.setContent("<!doctype html><html><body></body></html>");
122
+ // Each SVG is parsed (not drawn) first: markup that is not SVG, or use references that would draw past
123
+ // MAX_USE_COPIES, stop the measure before any drawing.
124
+ for (const f of [main, ...others].filter((x) => x.svgText !== null)) {
125
+ const u = await page.evaluate(`(${usesScript})(${JSON.stringify(f.svgText)}, ${MAX_USE_COPIES})`);
126
+ if (!u.parsed) throw new Error(`${f.label} could not be read as SVG markup; it was not drawn or measured.`);
127
+ if (u.copies > MAX_USE_COPIES) {
128
+ throw new Error(`${f.label} draws more than ${MAX_USE_COPIES} elements through use references (a safety limit); it was not drawn or measured.`);
129
+ }
130
+ }
131
+ const natural = await page.evaluate(async (url) => {
132
+ const img = new Image();
133
+ img.src = url;
134
+ await img.decode();
135
+ return { w: img.naturalWidth, h: img.naturalHeight };
136
+ }, main.url);
137
+ if (!(natural.w > 0 && natural.h > 0)) throw new Error(`The symbol ${main.label} has no size once decoded.`);
138
+ const long = Math.max(natural.w, natural.h);
139
+ if (!main.svgText) {
140
+ if (long < 16) throw new AssetInputError(`The asset is ${natural.w}x${natural.h} px; the symbol ladder needs at least 16 px.`);
141
+ const fits = ladder.filter((s) => s <= long);
142
+ if (fits.length < ladder.length) notes.push(`The file is ${natural.w}x${natural.h} px; sizes above ${fits[0]} px were not rendered.`);
143
+ ladder = fits;
144
+ }
145
+ const box = (s) => ({ w: Math.round((s * natural.w) / long), h: Math.round((s * natural.h) / long) });
146
+ if (natural.w !== natural.h) {
147
+ const b = box(16);
148
+ notes.push(`Sizes are the longer side of the symbol's box: at 16 px this symbol is ${b.w}x${b.h} px.`);
149
+ }
150
+
151
+ // Each size is drawn by the main file or by the Brand symbol that serves it.
152
+ const plan = ladder.map((size) => {
153
+ const other = servingSymbol(others, size);
154
+ return { size, file: other ?? main };
155
+ });
156
+ const ref = Math.max(...plan.filter((p) => p.file === main).map((p) => p.size), -Infinity);
157
+ if (!Number.isFinite(ref)) throw new AssetInputError(`Every size of ${main.label} is served by a smaller Brand symbol; nothing of it is read.`);
158
+ const files = [main, ...others]
159
+ .map((f) => ({ file: f.label, sizes: plan.filter((p) => p.file === f).map((p) => p.size) }))
160
+ .filter((f) => f.sizes.length > 0);
161
+
162
+ let x = GAP;
163
+ const tiles = plan.map((p) => {
164
+ const t = { size: p.size, file: p.file.label, url: p.file.url, x };
165
+ x += p.size + GAP;
166
+ return t;
167
+ });
168
+ await page.setContent(tilesHtml(tiles));
169
+ await page.evaluate(() => Promise.all([...document.images].map((img) => img.decode())));
170
+ const shots = [];
171
+ for (const t of tiles) {
172
+ const buf = await page.screenshot({ type: "png", omitBackground: true, clip: { x: t.x, y: 0, width: t.size, height: t.size } });
173
+ shots.push({ size: t.size, file: t.file, shot: `data:image/png;base64,${buf.toString("base64")}` });
174
+ }
175
+ const fileRefs = Object.fromEntries(files.map((f) => [f.file, Math.max(...f.sizes)]));
176
+ const input = {
177
+ tiles: shots.map((s) => ({ size: s.size, file: s.file, url: s.shot })),
178
+ ref,
179
+ main: main.label,
180
+ fileRefs,
181
+ backgrounds: BACKGROUNDS,
182
+ maxParts: MAX_PARTS,
183
+ };
184
+ const read = await page.evaluate(`(${symbolScript})(${JSON.stringify(input)}, ${contrastScript})`);
185
+ // The note names the rule that reads the silhouette when the run has one (ctx.rules).
186
+ const silhouetteId = ctx.rules?.find((r) => r.measure === "symbol.silhouette")?.id;
187
+ const silhouetteName = silhouetteId ? `the silhouette (${silhouetteId})` : "the silhouette";
188
+ if (read.opaque) notes.push(`The asset has no transparent pixel at ${ref} px, so its silhouette is its box; ${silhouetteName} was not measured.`);
189
+ else if (read.empty) notes.push(`The asset draws no pixel at ${ref} px; ${silhouetteName} was not measured.`);
190
+ for (const f of files) {
191
+ const n = read.colors[f.file];
192
+ if (n > MAX_PARTS) notes.push(`${f.file} has ${n} colors at ${fileRefs[f.file]} px (4 bits per channel); the ${MAX_PARTS} largest were read as parts.`);
193
+ }
194
+
195
+ // Strokes from each SVG file, at that file's own largest size.
196
+ let strokes = null;
197
+ const thinnest = [];
198
+ const svgFiles = [main, ...others].filter((f) => f.svgText !== null && fileRefs[f.label] !== undefined);
199
+ if (svgFiles.length === 0) {
200
+ notes.push("Strokes are read from an SVG only.");
201
+ } else {
202
+ strokes = [];
203
+ let found = 0;
204
+ let parsed = 0;
205
+ let liveText = 0;
206
+ let external = 0;
207
+ const byFile = new Map();
208
+ const strokePage = await context.newPage();
209
+ await strokePage.setContent("<!doctype html><html><head><style>html,body{margin:0}</style></head><body></body></html>");
210
+ for (const f of svgFiles) {
211
+ const fref = fileRefs[f.label];
212
+ // Selectors are built for the strokes the report lists (the first MAX_STROKES) and the thinnest only.
213
+ const listed = Math.max(0, MAX_STROKES - strokes.length);
214
+ const r = await strokePage.evaluate(`(${strokesScript})(${JSON.stringify(f.svgText)}, ${fref}, ${listed})`);
215
+ if (!r.parsed) notes.push(`${f.label} could not be read as SVG markup; its strokes were not read.`);
216
+ else parsed += 1;
217
+ liveText += r.liveText;
218
+ external += r.external;
219
+ found += r.strokes.length;
220
+ const kept = r.strokes.slice(0, Math.max(0, MAX_STROKES - strokes.length)).map((s) => ({ file: f.label, ...s }));
221
+ strokes.push(...kept);
222
+ // Every stroke is judged; MAX_STROKES caps only the list in the report.
223
+ byFile.set(f.label, { ref: fref, strokes: r.strokes });
224
+ }
225
+ if (found > MAX_STROKES) notes.push(`The symbol has ${found} stroked shapes; the first ${MAX_STROKES} are listed, every one is checked.`);
226
+ // Shapes drawn only through use references are not read for strokes.
227
+ if (found === 0 && parsed > 0) notes.push("No stroke was found outside use references; thin filled shapes are read by the parts check only.");
228
+ for (const p of plan) {
229
+ const own = byFile.get(p.file.label);
230
+ if (!own || own.strokes.length === 0) continue;
231
+ const at = own.strokes
232
+ .map((s) => ({ selector: s.selector, px: s.fixed ? s.refPx : (s.refPx * p.size) / own.ref }))
233
+ .sort((a, b) => a.px - b.px)[0];
234
+ thinnest.push({ size: p.size, px: +at.px.toFixed(3), selector: at.selector });
235
+ }
236
+ if (liveText > 0) {
237
+ notes.push(
238
+ `The symbol has ${liveText} live text ${plural(liveText, "element; it renders", "elements; they render")} in this machine's fonts. Outline the text for a stable mark.`,
239
+ );
240
+ }
241
+ if (external > 0) {
242
+ notes.push(`The symbol points to ${external} ${plural(external, "file outside itself; it was", "files outside itself; they were")} not loaded.`);
243
+ }
244
+ }
245
+
246
+ const sheet = await context.newPage();
247
+ await sheet.setContent(sheetHtml(shots));
248
+ await sheet.evaluate(() => Promise.all([...document.images].map((img) => img.decode())));
249
+ await fs.mkdir(dir, { recursive: true });
250
+ const sheetFile = path.join(dir, "symbol-sheet.png");
251
+ await sheet.screenshot({ type: "png", fullPage: true, path: sheetFile });
252
+
253
+ const b = box(ref);
254
+ return {
255
+ ref,
256
+ sizes: ladder,
257
+ files,
258
+ aspect: { width: b.w, height: b.h },
259
+ silhouette: read.silhouette,
260
+ parts: read.parts,
261
+ contrast: read.contrast,
262
+ strokes,
263
+ thinnest,
264
+ written: [sheetFile],
265
+ notes,
266
+ };
267
+ });
268
+ }