@uselazuli/cli 0.0.0-stage → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (179) hide show
  1. package/CHANGELOG.md +98 -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 +699 -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 +18 -0
  22. package/rules/content/_area.yaml +8 -0
  23. package/rules/content/review.yaml +347 -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 +17 -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 +242 -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 +219 -0
  50. package/rules/ui/grid.yaml +75 -0
  51. package/rules/ui/review.yaml +399 -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 +180 -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 +35 -0
  64. package/skills/lazuli/procedures/show-options.md +32 -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 +39 -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 +43 -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 +161 -0
  88. package/src/commands/capture.mjs +313 -0
  89. package/src/commands/catalog.mjs +37 -0
  90. package/src/commands/check-design.mjs +428 -0
  91. package/src/commands/check-goals.mjs +57 -0
  92. package/src/commands/compare-designs.mjs +97 -0
  93. package/src/commands/draft-memo.mjs +161 -0
  94. package/src/commands/hooks.mjs +343 -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 +296 -0
  101. package/src/commands/record-task.mjs +250 -0
  102. package/src/commands/render-options.mjs +164 -0
  103. package/src/commands/start-project.mjs +32 -0
  104. package/src/measure/a11y.mjs +383 -0
  105. package/src/measure/asset.mjs +206 -0
  106. package/src/measure/at-rest.mjs +49 -0
  107. package/src/measure/cases.mjs +549 -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 +79 -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 +489 -0
  117. package/src/measure/in-page/color.js +346 -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 +355 -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 +169 -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 +266 -0
  130. package/src/measure/in-page/weight.js +207 -0
  131. package/src/measure/layout.mjs +91 -0
  132. package/src/measure/motion.mjs +508 -0
  133. package/src/measure/piece.mjs +195 -0
  134. package/src/measure/registry.mjs +252 -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 +159 -0
  149. package/src/project/lazuli-md.mjs +497 -0
  150. package/src/project/log.mjs +329 -0
  151. package/src/project/match.mjs +112 -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 +206 -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 +86 -0
  159. package/src/report/evaluators/content.mjs +112 -0
  160. package/src/report/evaluators/extreme.mjs +53 -0
  161. package/src/report/evaluators/forms.mjs +116 -0
  162. package/src/report/evaluators/layout.mjs +94 -0
  163. package/src/report/evaluators/motion.mjs +273 -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 +163 -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 +256 -0
  177. package/src/rules/public-text.mjs +56 -0
  178. package/src/rules/schema.mjs +212 -0
  179. package/templates/LAZULI.md +86 -0
@@ -0,0 +1,266 @@
1
+ // Evaluated inside the page as a function expression: (opts) => report parts.
2
+ // Plain script, no imports. The text elements whose rendered fonts Node reads through the
3
+ // DevTools protocol are left in globalThis[opts.stashKey]; the caller deletes the stash.
4
+ (opts) => {
5
+ const LETTER = /\p{L}/u;
6
+ const GENERIC = new Set([
7
+ "serif", "sans-serif", "monospace", "cursive", "fantasy", "system-ui", "ui-serif", "ui-sans-serif",
8
+ "ui-monospace", "ui-rounded", "emoji", "math", "fangsong", "-apple-system", "blinkmacsystemfont",
9
+ ]);
10
+ const SKIP = new Set(["SCRIPT", "STYLE", "NOSCRIPT", "TEMPLATE", "HEAD", "TITLE", "META", "LINK"]);
11
+ const BLOCK_SEL = "p, li, dd, blockquote, figcaption, div";
12
+ // Two line boxes whose tops differ by less than this are one line.
13
+ const SAME_LINE_PX = 2;
14
+ const TOP_BLOCKS = 10;
15
+
16
+ const selectorOf = (el) => {
17
+ const tag = el.tagName.toLowerCase();
18
+ if (el.id) return `${tag}#${CSS.escape(el.id)}`;
19
+ const first = (el.getAttribute("class") || "").split(/\s+/).find(Boolean);
20
+ return first ? `${tag}.${CSS.escape(first)}` : tag;
21
+ };
22
+ // Visually hidden boxes (sr-only, skip links): a box of 1 px or less in both dimensions that clips its content,
23
+ // clip: rect(0 0 0 0), or clip-path: inset(50%) or more, on the element or any ancestor.
24
+ const HIDDEN_CLIP = /^(rect\(0(px)?,? 0(px)?,? 0(px)?,? 0(px)?\)|inset\(\s*(?:(?:50|100)%\s*)+\))/;
25
+ const hiddenByBox = (el) => {
26
+ // The walk stops before body: its computed overflow stays hidden when it propagates to the
27
+ // viewport, and an app shell with an out-of-flow root gives it no height.
28
+ for (let e = el; e && e !== document.body && e !== document.documentElement; e = e.parentElement) {
29
+ const s = getComputedStyle(e);
30
+ const r = e.getBoundingClientRect();
31
+ const clips = s.overflowX !== "visible" || s.overflowY !== "visible";
32
+ if (clips && r.width <= 1 && r.height <= 1) return true;
33
+ if (s.clip !== "auto" && HIDDEN_CLIP.test(s.clip)) return true;
34
+ if (s.clipPath !== "none" && HIDDEN_CLIP.test(s.clipPath)) return true;
35
+ }
36
+ return false;
37
+ };
38
+ // The composition walk's rule: a box clipped away by its clipping ancestors (a collapsed menu at height 0
39
+ // with overflow hidden, text scrolled out of a scroll container or a carousel track) paints nothing. Only
40
+ // the ancestors on the containing-block chain clip (CSS 2 10.1): an absolute box skips static ancestors
41
+ // that do not form a containing block (no position, transform, filter, perspective, contain or will-change
42
+ // that makes one), a fixed box skips every ancestor that does not form one by transform and the like; body
43
+ // never clips (its overflow goes to the viewport).
44
+ // A box that scrolls on an axis (auto or scroll) is the page's scroller on that axis, and does not clip on
45
+ // it, when it spans at least the viewport there (an app shell's main at 100vh), or when the root does not
46
+ // scroll on that axis and the box reaches the viewport's far edge (a main of 100vh minus a header): text
47
+ // reached by scrolling it counts as on a normal page. A smaller scroll box (a carousel, a ticker, a chat
48
+ // pane) clips; hidden and clip always clip.
49
+ const scrolls = (v) => v === "auto" || v === "scroll";
50
+ // Subpixel layout: a flex child of 100vh minus a header can end a fraction short of the viewport edge.
51
+ const EDGE_PX = 1;
52
+ const formsBlockFor = (s, position) => {
53
+ const will = s.willChange || "";
54
+ const contain = s.contain || "";
55
+ const byEffect =
56
+ (s.transform && s.transform !== "none") ||
57
+ (s.perspective && s.perspective !== "none") ||
58
+ (s.filter && s.filter !== "none") ||
59
+ (s.backdropFilter && s.backdropFilter !== "none") ||
60
+ /\b(paint|layout|strict|content)\b/.test(contain) ||
61
+ /\b(transform|perspective|filter)\b/.test(will);
62
+ if (position === "fixed") return byEffect;
63
+ if (position === "absolute") return byEffect || s.position !== "static";
64
+ return true;
65
+ };
66
+ const clippedAway = (el, r) => {
67
+ const clip = { left: -Infinity, top: -Infinity, right: Infinity, bottom: Infinity };
68
+ const view = document.documentElement;
69
+ const rootX = view.scrollWidth > view.clientWidth;
70
+ const rootY = view.scrollHeight > view.clientHeight;
71
+ // The position of the box whose containing block is being looked for.
72
+ let position = getComputedStyle(el).position;
73
+ for (let e = el.parentElement; e && e !== document.body && e !== document.documentElement; e = e.parentElement) {
74
+ const s = getComputedStyle(e);
75
+ if (!formsBlockFor(s, position)) continue;
76
+ position = s.position;
77
+ const a = e.getBoundingClientRect();
78
+ const pageX = a.width >= view.clientWidth || (!rootX && a.right >= view.clientWidth - EDGE_PX);
79
+ const pageY = a.height >= view.clientHeight || (!rootY && a.bottom >= view.clientHeight - EDGE_PX);
80
+ const cx = s.overflowX !== "visible" && !(scrolls(s.overflowX) && pageX);
81
+ const cy = s.overflowY !== "visible" && !(scrolls(s.overflowY) && pageY);
82
+ if (!cx && !cy) continue;
83
+ if (cx) {
84
+ clip.left = Math.max(clip.left, a.left);
85
+ clip.right = Math.min(clip.right, a.right);
86
+ }
87
+ if (cy) {
88
+ clip.top = Math.max(clip.top, a.top);
89
+ clip.bottom = Math.min(clip.bottom, a.bottom);
90
+ }
91
+ }
92
+ return !(Math.min(r.right, clip.right) > Math.max(r.left, clip.left) && Math.min(r.bottom, clip.bottom) > Math.max(r.top, clip.top));
93
+ };
94
+ // A box entirely before the document origin or past its right edge (a skip link at left -9999px, a
95
+ // drawer moved off the page by a transform) is not shown to anyone scrolling the page.
96
+ const offPage = (r) =>
97
+ r.right + scrollX <= 0 || r.bottom + scrollY <= 0 || r.left + scrollX >= document.documentElement.scrollWidth;
98
+ const visible = (el) => {
99
+ const r = el.getBoundingClientRect();
100
+ if (!r.width || !r.height) return null;
101
+ if (hiddenByBox(el) || clippedAway(el, r) || offPage(r)) return null;
102
+ if (typeof el.checkVisibility === "function") {
103
+ return el.checkVisibility({ opacityProperty: true, visibilityProperty: true }) ? r : null;
104
+ }
105
+ for (let e = el; e; e = e.parentElement) {
106
+ const s = getComputedStyle(e);
107
+ if (s.display === "none" || s.visibility === "hidden" || parseFloat(s.opacity) === 0) return null;
108
+ }
109
+ return r;
110
+ };
111
+ const round = (n, d = 1) => Math.round(n * 10 ** d) / 10 ** d;
112
+ const norm = (s) => s.replace(/\s+/g, " ").trim();
113
+
114
+ // First family of a computed font-family list, and whether it is a named (non generic) family.
115
+ const firstFamily = (value) => {
116
+ const m = /^\s*(?:"([^"]*)"|'([^']*)'|([^,]+))/.exec(value || "");
117
+ const name = (m ? m[1] ?? m[2] ?? m[3] : "").trim();
118
+ return { declared: name, named: name !== "" && !GENERIC.has(name.toLowerCase()) };
119
+ };
120
+
121
+ // Text nodes that belong to this element (no nearer block-like element owns them) and are
122
+ // rendered: script, style and noscript text, and anything display:none or collapsed, has no rects.
123
+ const hasRects = (n) => {
124
+ const range = document.createRange();
125
+ range.selectNodeContents(n);
126
+ return [...range.getClientRects()].some((r) => r.width > 0 && r.height > 0);
127
+ };
128
+ const ownTextNodes = (el) => {
129
+ const out = [];
130
+ const walker = document.createTreeWalker(el, NodeFilter.SHOW_TEXT);
131
+ for (let n = walker.nextNode(); n; n = walker.nextNode()) {
132
+ const parent = n.parentElement;
133
+ if (!parent || SKIP.has(parent.tagName) || parent.closest(BLOCK_SEL) !== el || !n.nodeValue.trim()) continue;
134
+ if (hasRects(n) && !hiddenByBox(parent)) out.push(n);
135
+ }
136
+ return out;
137
+ };
138
+ const directText = (el) =>
139
+ [...el.childNodes].filter((n) => n.nodeType === 3).map((n) => n.nodeValue).join(" ");
140
+
141
+ // Distinct line tops from the rects of the given ranges, within SAME_LINE_PX as one line.
142
+ const lineTops = (rects) => {
143
+ const tops = [];
144
+ for (const r of [...rects].filter((x) => x.width > 0 && x.height > 0).sort((a, b) => a.top - b.top)) {
145
+ if (tops.length === 0 || r.top - tops[tops.length - 1] > SAME_LINE_PX) tops.push(r.top);
146
+ }
147
+ return tops;
148
+ };
149
+ const rectsOf = (nodes) =>
150
+ nodes.flatMap((n) => {
151
+ const range = document.createRange();
152
+ range.selectNodeContents(n);
153
+ return [...range.getClientRects()];
154
+ });
155
+
156
+ // Load status of each declared @font-face family: "loaded" when any face of it loaded.
157
+ const faceStatus = new Map();
158
+ for (const face of document.fonts) {
159
+ const key = face.family.replace(/^["']|["']$/g, "").toLowerCase();
160
+ if (faceStatus.get(key) !== "loaded") faceStatus.set(key, face.status);
161
+ }
162
+
163
+ // ---- text elements for the rendered-font read ----
164
+ const targets = [];
165
+ const targetMeta = [];
166
+ for (const el of document.body ? document.body.querySelectorAll("*") : []) {
167
+ if (SKIP.has(el.tagName) || el instanceof SVGElement && el.tagName.toLowerCase() !== "text") continue;
168
+ if (!LETTER.test(directText(el))) continue;
169
+ if (!visible(el)) continue;
170
+ targets.push(el);
171
+ const family = firstFamily(getComputedStyle(el).fontFamily);
172
+ targetMeta.push({ selector: selectorOf(el), ...family, webfont: faceStatus.get(family.declared.toLowerCase()) ?? null });
173
+ }
174
+ const total = targets.length;
175
+ const kept = targets.slice(0, opts.maxFontElements);
176
+ globalThis[opts.stashKey] = kept;
177
+
178
+ // ---- blocks of running text ----
179
+ const textOnly = (el) =>
180
+ [...el.children].every((c) => {
181
+ const d = getComputedStyle(c).display || "";
182
+ return d === "none" || d.startsWith("inline") || hiddenByBox(c);
183
+ });
184
+ const candidates = [];
185
+ for (const el of document.body ? document.body.querySelectorAll(BLOCK_SEL) : []) {
186
+ if (el.tagName === "DIV" && !textOnly(el)) continue;
187
+ if (!visible(el)) continue;
188
+ const nodes = ownTextNodes(el);
189
+ const text = norm(nodes.map((n) => n.nodeValue).join(" "));
190
+ if (!LETTER.test(text) || nodes.length === 0) continue;
191
+ candidates.push({ el, nodes, chars: text.length });
192
+ }
193
+ candidates.sort((a, b) => b.chars - a.chars);
194
+ const blocks = candidates.slice(0, TOP_BLOCKS).map(({ el, nodes, chars }) => {
195
+ const cs = getComputedStyle(el);
196
+ const size = parseFloat(cs.fontSize);
197
+ const rects = rectsOf(nodes);
198
+ const tops = lineTops(rects);
199
+ // Average width of one character of this block, from its own line boxes.
200
+ const textWidth = rects.reduce((s, r) => s + (r.width > 0 && r.height > 0 ? r.width : 0), 0);
201
+ const lines = tops.length;
202
+ const lh = parseFloat(cs.lineHeight); // NaN for "normal"
203
+ let ratio;
204
+ if (Number.isFinite(lh)) ratio = lh / size;
205
+ else if (tops.length >= 2) ratio = (tops[tops.length - 1] - tops[0]) / (tops.length - 1) / size;
206
+ else {
207
+ const box = el.getBoundingClientRect().height;
208
+ const pad = ["paddingTop", "paddingBottom", "borderTopWidth", "borderBottomWidth"].reduce((s, k) => s + (parseFloat(cs[k]) || 0), 0);
209
+ ratio = (box - pad) / size;
210
+ }
211
+ return {
212
+ selector: selectorOf(el),
213
+ chars,
214
+ lines,
215
+ charsPerLine: round(chars / lines),
216
+ sizePx: round(size, 2),
217
+ lineHeightRatio: round(ratio, 3),
218
+ charAdvancePx: round(textWidth / chars, 2),
219
+ };
220
+ });
221
+ const body = blocks[0] ?? null;
222
+
223
+ // ---- headings ----
224
+ const headingEls = [...(document.body ? document.body.querySelectorAll("h1, h2, h3, h4") : [])].filter(visible);
225
+ const wordsByLine = (el) => {
226
+ const tops = [];
227
+ const walker = document.createTreeWalker(el, NodeFilter.SHOW_TEXT);
228
+ for (let n = walker.nextNode(); n; n = walker.nextNode()) {
229
+ for (const m of n.nodeValue.matchAll(/\S+/g)) {
230
+ const range = document.createRange();
231
+ range.setStart(n, m.index);
232
+ range.setEnd(n, m.index + m[0].length);
233
+ const r = [...range.getClientRects()].find((x) => x.width > 0 && x.height > 0);
234
+ if (r) tops.push(r.top);
235
+ }
236
+ }
237
+ const lines = [];
238
+ for (const t of tops.sort((a, b) => a - b)) {
239
+ const last = lines[lines.length - 1];
240
+ if (last && t - last.top <= SAME_LINE_PX) last.words += 1;
241
+ else lines.push({ top: t, words: 1 });
242
+ }
243
+ return lines;
244
+ };
245
+ const twoViewports = innerHeight * 2;
246
+ const headings = headingEls
247
+ .filter((el) => /^H[1-3]$/.test(el.tagName) && el.getBoundingClientRect().top + scrollY < twoViewports)
248
+ .map((el) => {
249
+ const lines = wordsByLine(el);
250
+ return {
251
+ selector: selectorOf(el),
252
+ level: Number(el.tagName[1]),
253
+ sizePx: round(parseFloat(getComputedStyle(el).fontSize), 2),
254
+ lines: Math.max(1, lines.length),
255
+ lastLineWords: lines.length ? lines[lines.length - 1].words : 0,
256
+ };
257
+ });
258
+
259
+ // ---- scale: distinct rounded sizes of h1..h4 plus the body size, descending ----
260
+ const sizes = new Set(headingEls.map((el) => Math.round(parseFloat(getComputedStyle(el).fontSize))));
261
+ if (body) sizes.add(Math.round(body.sizePx));
262
+ const sizesPx = [...sizes].filter((s) => s > 0).sort((a, b) => b - a);
263
+ const ratios = sizesPx.slice(1).map((s, i) => round(sizesPx[i] / s, 3));
264
+
265
+ return { targetMeta: targetMeta.slice(0, opts.maxFontElements), totalTextElements: total, blocks, body, scale: { sizesPx, ratios }, headings };
266
+ }
@@ -0,0 +1,207 @@
1
+ // Evaluated inside the page as a function expression: (shotDataUrl, blurPx) => { order, primary }.
2
+ // Plain script, no imports.
3
+ async (shotDataUrl, blurPx) => {
4
+ const RING = 8;
5
+ const MIN_SIZE = 24;
6
+
7
+ // ---- blurred luminance map of the first viewport ----
8
+ const img = new Image();
9
+ await new Promise((res, rej) => {
10
+ img.onload = res;
11
+ img.onerror = () => rej(new Error("screenshot decode failed"));
12
+ img.src = shotDataUrl;
13
+ });
14
+ const W = img.naturalWidth, H = img.naturalHeight;
15
+ const scale = W / innerWidth;
16
+ const raw = document.createElement("canvas");
17
+ raw.width = W;
18
+ raw.height = H;
19
+ const rctx = raw.getContext("2d", { willReadFrequently: true });
20
+ rctx.drawImage(img, 0, 0);
21
+
22
+ // Pad by replicating edges so the blur does not fade toward transparent at the borders.
23
+ const pad = Math.ceil(blurPx * scale * 3);
24
+ const big = document.createElement("canvas");
25
+ big.width = W + 2 * pad;
26
+ big.height = H + 2 * pad;
27
+ const bctx = big.getContext("2d", { willReadFrequently: true });
28
+ bctx.filter = `blur(${blurPx * scale}px)`;
29
+ bctx.drawImage(raw, 0, 0, W, 1, pad, 0, W, pad + 1);
30
+ bctx.drawImage(raw, 0, H - 1, W, 1, pad, pad + H - 1, W, pad + 1);
31
+ bctx.drawImage(raw, 0, 0, 1, H, 0, pad, pad + 1, H);
32
+ bctx.drawImage(raw, W - 1, 0, 1, H, pad + W - 1, pad, pad + 1, H);
33
+ bctx.drawImage(raw, 0, 0, 1, 1, 0, 0, pad + 1, pad + 1);
34
+ bctx.drawImage(raw, W - 1, 0, 1, 1, pad + W - 1, 0, pad + 1, pad + 1);
35
+ bctx.drawImage(raw, 0, H - 1, 1, 1, 0, pad + H - 1, pad + 1, pad + 1);
36
+ bctx.drawImage(raw, W - 1, H - 1, 1, 1, pad + W - 1, pad + H - 1, pad + 1, pad + 1);
37
+ bctx.drawImage(raw, pad, pad);
38
+ const data = bctx.getImageData(pad, pad, W, H).data;
39
+ const L = new Float32Array(W * H);
40
+ for (let i = 0; i < W * H; i++) {
41
+ L[i] = (0.2126 * data[i * 4] + 0.7152 * data[i * 4 + 1] + 0.0722 * data[i * 4 + 2]) / 255;
42
+ }
43
+
44
+ // Mean luminance of a pixel rect, optionally with an inner rect excluded.
45
+ const stats = (x0, y0, x1, y1, hole) => {
46
+ let sum = 0, n = 0;
47
+ for (let y = y0; y < y1; y++) {
48
+ for (let x = x0; x < x1; x++) {
49
+ if (hole && x >= hole.x0 && x < hole.x1 && y >= hole.y0 && y < hole.y1) continue;
50
+ sum += L[y * W + x];
51
+ n++;
52
+ }
53
+ }
54
+ return { mean: n ? sum / n : 0, n };
55
+ };
56
+ const clampX = (v) => Math.max(0, Math.min(W, v));
57
+ const clampY = (v) => Math.max(0, Math.min(H, v));
58
+
59
+ // ---- candidates ----
60
+ const selectorOf = (el) => {
61
+ const tag = el.tagName.toLowerCase();
62
+ if (el.id) return `${tag}#${CSS.escape(el.id)}`;
63
+ const first = (el.getAttribute("class") || "").split(/\s+/).find(Boolean);
64
+ return first ? `${tag}.${CSS.escape(first)}` : tag;
65
+ };
66
+ const labelOf = (el) => {
67
+ if (el instanceof SVGElement) {
68
+ const t = (el.getAttribute("aria-label") || el.querySelector("title")?.textContent || "").trim();
69
+ if (t) return t.replace(/\s+/g, " ").slice(0, 40);
70
+ }
71
+ const text = (el.textContent || "").replace(/\s+/g, " ").trim();
72
+ if (text) return text.slice(0, 40);
73
+ const alt = (el.getAttribute("alt") || el.getAttribute("aria-label") || "").trim();
74
+ return alt ? alt.slice(0, 40) : el.tagName.toLowerCase();
75
+ };
76
+ const visible = (el) => {
77
+ const r = el.getBoundingClientRect();
78
+ if (!r.width || !r.height) return null;
79
+ for (let e = el; e; e = e.parentElement) {
80
+ const s = getComputedStyle(e);
81
+ if (s.display === "none" || s.visibility === "hidden" || parseFloat(s.opacity) === 0) return null;
82
+ }
83
+ return r;
84
+ };
85
+ // A link styled as a button: filled background or visible border, with padding.
86
+ const styledLink = (el) => {
87
+ if (!el.matches("a, [role=link]")) return false;
88
+ const s = getComputedStyle(el);
89
+ // Alpha of a computed color such as "rgb(1, 2, 3)", "rgba(1, 2, 3, 0.5)" or "rgb(1 2 3 / 50%)".
90
+ const alphaOf = (c) => {
91
+ if (c === "transparent") return 0;
92
+ const inner = c.slice(c.indexOf("(") + 1, c.lastIndexOf(")"));
93
+ const parts = inner.includes("/") ? inner.split("/") : inner.split(",");
94
+ if (parts.length < (inner.includes("/") ? 2 : 4)) return 1;
95
+ const raw = parts[parts.length - 1].trim();
96
+ const v = parseFloat(raw);
97
+ if (!Number.isFinite(v)) return 1;
98
+ return raw.endsWith("%") ? v / 100 : v;
99
+ };
100
+ // The 0.1 alpha cutoffs below are an implementation tolerance, not a rule threshold.
101
+ const filled = alphaOf(s.backgroundColor) > 0.1;
102
+ const borderSides = ["Top", "Right", "Bottom", "Left"];
103
+ const bordered = borderSides.some(
104
+ (k) =>
105
+ parseFloat(s["border" + k + "Width"]) > 0 &&
106
+ s["border" + k + "Style"] !== "none" &&
107
+ s["border" + k + "Style"] !== "hidden" &&
108
+ alphaOf(s["border" + k + "Color"]) > 0.1,
109
+ );
110
+ const padded = ["Top", "Right", "Bottom", "Left"].some((k) => parseFloat(s["padding" + k]) > 0);
111
+ return (filled || bordered) && padded;
112
+ };
113
+ const inFirstView = (r) => r.bottom > 0 && r.top < innerHeight && r.right > 0 && r.left < innerWidth;
114
+ const buttonish = (el) => el.matches("button, a[role=button], input[type=submit]") || styledLink(el);
115
+ // Guessing the main action: a menu toggle in the header, a button in a fixed or sticky bar or an icon button
116
+ // is not it. 44x44 CSS px is the WCAG 2.2 target size (enhanced, SC 2.5.5).
117
+ const MIN_TARGET = 44;
118
+ const pinned = (el) => {
119
+ for (let e = el; e; e = e.parentElement) {
120
+ const p = getComputedStyle(e).position;
121
+ if (p === "fixed" || p === "sticky") return true;
122
+ }
123
+ return false;
124
+ };
125
+ const inChrome = (el) => el.closest("nav, header, [role=navigation], [role=banner]") || pinned(el);
126
+ const explicitEl = document.querySelector("[data-primary]");
127
+ let primaryEl = explicitEl;
128
+ let primaryReason = null;
129
+ if (!primaryEl) {
130
+ primaryEl =
131
+ [...document.querySelectorAll("button, a, [role=link], input[type=submit]")].find((el) => {
132
+ if (!buttonish(el) || inChrome(el)) return false;
133
+ const r = visible(el);
134
+ return r && inFirstView(r) && r.width >= MIN_TARGET && r.height >= MIN_TARGET;
135
+ }) || null;
136
+ if (!primaryEl) {
137
+ primaryReason =
138
+ "No visible button-like element of at least 44x44 CSS px outside nav and header in the first view, and no data-primary.";
139
+ }
140
+ }
141
+
142
+ const all = new Set(
143
+ document.querySelectorAll("h1, h2, button, a[role=button], a.button, input[type=submit], [data-primary], img, svg"),
144
+ );
145
+ for (const el of document.querySelectorAll("a, [role=link]")) if (styledLink(el)) all.add(el);
146
+ const rows = [];
147
+ for (const el of all) {
148
+ // svg inside another svg is part of the same graphic
149
+ if (el instanceof SVGElement && el.tagName.toLowerCase() === "svg" && el.parentElement?.closest("svg")) continue;
150
+ const r = visible(el);
151
+ if (!r) continue;
152
+ const isMedia = el.matches("img, svg");
153
+ if (isMedia && (r.width <= MIN_SIZE || r.height <= MIN_SIZE)) continue;
154
+ const x0 = clampX(Math.round(r.left * scale)), x1 = clampX(Math.round(r.right * scale));
155
+ const y0 = clampY(Math.round(r.top * scale)), y1 = clampY(Math.round(r.bottom * scale));
156
+ if (x1 <= x0 || y1 <= y0) continue; // outside the first viewport
157
+ const hole = { x0, y0, x1, y1 };
158
+ const ring = Math.round(RING * scale);
159
+ let outer = stats(clampX(x0 - ring), clampY(y0 - ring), clampX(x1 + ring), clampY(y1 + ring), hole);
160
+ // A box that fills the viewport has no ring; compare against the whole blurred viewport.
161
+ if (!outer.n) outer = stats(0, 0, W, H);
162
+ let diff = 0, n = 0;
163
+ for (let y = y0; y < y1; y++) {
164
+ for (let x = x0; x < x1; x++) {
165
+ diff += Math.abs(L[y * W + x] - outer.mean);
166
+ n++;
167
+ }
168
+ }
169
+ const share = (n) / (W * H);
170
+ rows.push({ el, selector: selectorOf(el), label: labelOf(el), raw: (diff / n) * Math.sqrt(share) });
171
+ }
172
+ rows.sort((a, b) => b.raw - a.raw);
173
+ const max = rows.length ? rows[0].raw : 0;
174
+ const scored = rows.map((r) => ({
175
+ el: r.el,
176
+ selector: r.selector,
177
+ label: r.label,
178
+ score: max > 0 ? +(r.raw / max).toFixed(3) : 0,
179
+ }));
180
+
181
+ // Make selectors unique within the result set.
182
+ const counts = new Map();
183
+ for (const s of scored) counts.set(s.selector, (counts.get(s.selector) || 0) + 1);
184
+ const nth = (el) => [...el.parentElement.children].filter((c) => c.tagName === el.tagName).indexOf(el) + 1;
185
+ for (const s of scored) {
186
+ if (counts.get(s.selector) > 1 && s.el.parentElement) s.selector += `:nth-of-type(${nth(s.el)})`;
187
+ }
188
+
189
+ const order = scored.slice(0, 5).map(({ selector, label, score }) => ({ selector, label, score }));
190
+ let primary = null;
191
+ if (primaryEl) {
192
+ const idx = scored.findIndex((s) => s.el === primaryEl);
193
+ // Its place on the page (page px) against the height of the first view.
194
+ const box = primaryEl.getBoundingClientRect();
195
+ primary = {
196
+ selector: idx === -1 ? selectorOf(primaryEl) : scored[idx].selector,
197
+ label: labelOf(primaryEl),
198
+ href: primaryEl.getAttribute("href"),
199
+ rank: idx === -1 ? null : idx + 1,
200
+ explicit: primaryEl === explicitEl,
201
+ top: Math.round(box.top + scrollY),
202
+ bottom: Math.round(box.bottom + scrollY),
203
+ viewportPx: innerHeight,
204
+ };
205
+ }
206
+ return { order, primary, primaryReason };
207
+ }
@@ -0,0 +1,91 @@
1
+ import fs from "node:fs/promises";
2
+
3
+ // Resolution, not a composition rule: the first view is read as SPACE_CELLS by SPACE_CELLS cells for
4
+ // where its empty space sits.
5
+ const SPACE_CELLS = 3;
6
+ // Listing limit, not a rule cutoff: bleeds and crossings listed (the report notes when it cuts the list).
7
+ const MAX_LISTED = 20;
8
+
9
+ let script;
10
+
11
+ const round = (n) => (n === null ? null : Math.round(n * 100) / 100);
12
+ const median = (xs) => {
13
+ const s = [...xs].sort((a, b) => a - b);
14
+ const mid = Math.floor(s.length / 2);
15
+ return s.length % 2 ? s[mid] : (s[mid - 1] + s[mid]) / 2;
16
+ };
17
+ const unique = (list) => [...new Set(list)];
18
+
19
+ // First view scale contrast, empty space and focal point; sections and their grid edges; bleeds and crossings.
20
+ // Report shape as in LayoutReport, except sections[].left and sections[].right are
21
+ // number | null: null (and centered false) for a section with no blocks, which uniformGrid leaves out.
22
+ // ctx.options true is the render-options reading: elements marked data-block are the option blocks. Any other
23
+ // caller measures a finished page, and the marks it carries are ignored and noted.
24
+ export async function measureLayout(page, ctx = {}) {
25
+ script ??= await fs.readFile(new URL("./in-page/composition.js", import.meta.url), "utf8");
26
+ const raw = await page.evaluate(`(${script})(${JSON.stringify({ read: "layout", spaceCells: SPACE_CELLS, options: ctx?.options === true })})`);
27
+ const { w, h } = raw.viewport;
28
+ const notes = [];
29
+
30
+ // Areas and centers of the first-view blocks are read on their part inside the first view.
31
+ const areas = raw.clipped.map((c) => c.w * c.h);
32
+ const sized = raw.blocks.filter((b) => b.sizePx !== null).map((b) => b.sizePx);
33
+ const textRatio = raw.bodyPx && sized.length ? Math.max(...sized) / raw.bodyPx : null;
34
+ const areaRatio = areas.length >= 2 ? Math.max(...areas) / median(areas) : null;
35
+
36
+ let focal = null;
37
+ if (areas.length) {
38
+ // Largest area; ties go to the first block in document order.
39
+ const order = areas.map((a, i) => i).sort((a, b) => areas[b] - areas[a] || a - b);
40
+ const top = order[0];
41
+ const c = raw.clipped[top];
42
+ focal = {
43
+ selector: raw.blocks[top].selector,
44
+ dominance: areas.length >= 2 && areas[order[1]] > 0 ? round(areas[top] / areas[order[1]]) : null,
45
+ x: round((c.x + c.w / 2) / w),
46
+ y: round((c.y + c.h / 2) / h),
47
+ };
48
+ }
49
+
50
+ const emptyCells = raw.emptyCells.map(round);
51
+ if (raw.ground.length) notes.push(`Covers the whole first view, read as ground and not as a block: ${unique(raw.ground).join(", ")}.`);
52
+ if (raw.marks > 0 && ctx?.options !== true) notes.push("This page has data-block marks; check-design measures it as a finished page and ignores them (only render-options reads them).");
53
+ if (raw.spaces.length) notes.push(`Space blocks are not counted as figure: ${unique(raw.spaces).join(", ")}.`);
54
+ if (!raw.scrolls) notes.push("The page does not scroll; it was read as one section.");
55
+ if (raw.noSections && raw.pinnedContent) notes.push("Content sits in a fixed container and was not measured.");
56
+ const textOnly = raw.sections.filter((s) => s.textOnly).map((s) => s.selector);
57
+ if (textOnly.length) notes.push(`Grid edges read from text only: ${unique(textOnly).join(", ")}.`);
58
+ if (raw.sideways) notes.push("The page scrolls sideways; blocks past the edge are not counted as bleeds.");
59
+ const listed = (list, what) => {
60
+ const all = unique(list);
61
+ if (all.length > MAX_LISTED) notes.push(`Showing ${MAX_LISTED} of ${all.length} ${what}.`);
62
+ return all.slice(0, MAX_LISTED);
63
+ };
64
+
65
+ return {
66
+ viewport: { w, h },
67
+ // Whether the page scrolls sideways (past ALIGN_PX, unless html or body hides that overflow) and its content width.
68
+ sideways: raw.sideways,
69
+ scrollWidth: raw.scrollWidth,
70
+ bodyPx: round(raw.bodyPx),
71
+ blocks: raw.blocks.map((b) => ({ ...b, x: round(b.x), y: round(b.y), w: round(b.w), h: round(b.h), sizePx: round(b.sizePx) })),
72
+ textRatio: round(textRatio),
73
+ areaRatio: round(areaRatio),
74
+ emptyShare: round(raw.emptyShare),
75
+ emptyCells,
76
+ emptySpread: round(Math.max(...raw.emptyCells) - Math.min(...raw.emptyCells)),
77
+ focal,
78
+ sections: raw.sections.map((s) => ({
79
+ selector: s.selector,
80
+ top: round(s.top),
81
+ height: round(s.height),
82
+ left: round(s.left),
83
+ right: round(s.right),
84
+ centered: s.centered,
85
+ })),
86
+ uniformGrid: raw.uniformGrid,
87
+ bleeds: listed(raw.bleeds, "bleeds"),
88
+ crossings: listed(raw.crossings, "crossings"),
89
+ notes,
90
+ };
91
+ }