@ultimat3/cli 31.52.0 → 31.53.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 (111) hide show
  1. package/CLAUDE.md +1 -1
  2. package/package.json +29 -29
  3. package/src/app-kit-disk.ts +39 -0
  4. package/src/app-kit-forms.ts +27 -0
  5. package/src/app-kit.ts +146 -0
  6. package/src/budgets.ts +3 -1
  7. package/src/cdp-shot-driver-screen.ts +72 -0
  8. package/src/cdp-shot-driver.ts +17 -1
  9. package/src/cmd-design-capture.ts +210 -0
  10. package/src/cmd-design-errors.ts +50 -0
  11. package/src/cmd-design-paths.ts +47 -0
  12. package/src/cmd-design-publish.ts +64 -0
  13. package/src/cmd-design-run.ts +229 -0
  14. package/src/cmd-design-spec.ts +47 -0
  15. package/src/cmd-design-theme.ts +107 -0
  16. package/src/cmd-design-url.ts +201 -0
  17. package/src/cmd-design.ts +188 -0
  18. package/src/cmd-doctor.ts +3 -0
  19. package/src/cmd-generate-spec.ts +5 -0
  20. package/src/cmd-generate.ts +3 -1
  21. package/src/cmd-kit-spec.ts +13 -0
  22. package/src/cmd-kit.ts +133 -0
  23. package/src/cmd-shot-against.ts +275 -0
  24. package/src/cmd-shot-spec.ts +9 -1
  25. package/src/cmd-shot.ts +19 -0
  26. package/src/cmd-upgrade.ts +11 -0
  27. package/src/codemods/agent-kit.ts +130 -0
  28. package/src/codemods/agents-md-budget.ts +47 -0
  29. package/src/codemods/docs-visual-quality.ts +198 -0
  30. package/src/codemods/index.ts +8 -0
  31. package/src/codemods/settings-kit-allow.ts +49 -0
  32. package/src/design-extract-script.ts +187 -0
  33. package/src/design-extract.ts +311 -0
  34. package/src/design-map-colors.ts +180 -0
  35. package/src/design-map.ts +288 -0
  36. package/src/doctor-kit.ts +25 -0
  37. package/src/error-catalog.ts +4 -2
  38. package/src/error-codes-kit.ts +24 -0
  39. package/src/error-codes.ts +12 -10
  40. package/src/generate-files.ts +31 -1
  41. package/src/guards-shipped-names.ts +5 -0
  42. package/src/kit/agent-audit.ts +49 -0
  43. package/src/kit/agent-data.ts +32 -0
  44. package/src/kit/agent-server.ts +34 -0
  45. package/src/kit/agent-shape.ts +61 -0
  46. package/src/kit/agent-web.ts +49 -0
  47. package/src/kit/design-map.ts +106 -0
  48. package/src/kit/managed.ts +12 -0
  49. package/src/kit/registry.ts +89 -0
  50. package/src/kit/skill-design-research.ts +119 -0
  51. package/src/kit/skill-feature.ts +159 -0
  52. package/src/kit/skill-planx.ts +139 -0
  53. package/src/kit/skill-upgrade.ts +94 -0
  54. package/src/kit/skill-verify.ts +80 -0
  55. package/src/mcp-errors.ts +5 -0
  56. package/src/mcp-ui-diff.ts +13 -38
  57. package/src/mcp-ui.ts +30 -1
  58. package/src/messages-design.ts +104 -0
  59. package/src/messages-upgrade.ts +9 -0
  60. package/src/messages.ts +2 -0
  61. package/src/registry.ts +4 -0
  62. package/src/shot-diff.ts +96 -0
  63. package/src/shot-gpu.ts +17 -5
  64. package/src/templates/guard-animated-layout-script.ts +173 -0
  65. package/src/templates/guard-effect-without-fallback.ts +117 -0
  66. package/src/templates/guard-motion-adapter.ts +161 -0
  67. package/src/templates/guard-raw-frame-loop.ts +134 -0
  68. package/src/templates/guard-raw-motion-script.ts +132 -0
  69. package/src/templates/guard-raw-motion-ts-scan.ts +95 -0
  70. package/src/templates/guard-released-forms.ts +10 -0
  71. package/src/templates/index.ts +1 -2
  72. package/src/templates/island.ts +55 -8
  73. package/src/templates/kit-released-forms.ts +63 -0
  74. package/src/templates/motion-scale.ts +115 -0
  75. package/src/templates/scaffold-claude.ts +39 -26
  76. package/src/templates/scaffold-design.ts +41 -0
  77. package/src/templates/scaffold-docs.ts +31 -7
  78. package/src/templates/scaffold-guards.ts +31 -2
  79. package/src/templates/scaffold-verify-floor.ts +3 -0
  80. package/src/templates/shapes/blog-site.ts +15 -0
  81. package/src/templates/shapes/blog.ts +2 -0
  82. package/src/templates/shapes/content-site.ts +13 -0
  83. package/src/templates/shapes/content.ts +2 -0
  84. package/src/templates/shapes/dashboard-detail.ts +2 -0
  85. package/src/templates/shapes/dashboard-motion.ts +284 -0
  86. package/src/templates/shapes/dashboard.ts +19 -1
  87. package/src/templates/shapes/landing-motion.ts +67 -0
  88. package/src/templates/shapes/saas.ts +4 -0
  89. package/src/upgrade-gate.ts +14 -2
  90. package/src/upgrade-kit.ts +65 -0
  91. package/src/upgrade-report-kit.ts +28 -0
  92. package/src/upgrade-report.ts +3 -0
  93. package/src/verify-checks.ts +9 -1
  94. package/src/workspace-checks.ts +3 -3
  95. package/wiki/Agents.md +33 -1
  96. package/wiki/CLI-Reference-Tools.md +24 -3
  97. package/wiki/CLI-Reference.md +4 -2
  98. package/wiki/Design-Research.md +96 -0
  99. package/wiki/Effects.md +83 -0
  100. package/wiki/FAQ.md +1 -1
  101. package/wiki/Getting-Started.md +1 -1
  102. package/wiki/Home.md +2 -2
  103. package/wiki/Known-Gaps.md +3 -2
  104. package/wiki/MCP-And-AI.md +4 -0
  105. package/wiki/Motion.md +85 -0
  106. package/wiki/Project-Layout.md +1 -1
  107. package/wiki/Tutorial-02-First-Feature.md +1 -1
  108. package/wiki/UI-Components.md +2 -0
  109. package/wiki/Upgrading.md +4 -2
  110. package/src/templates/scaffold-claude-agents.ts +0 -161
  111. package/src/templates/scaffold-claude-commands.ts +0 -239
@@ -0,0 +1,311 @@
1
+ // What one reference capture measured, parsed out of the page's answer to `DESIGN_PASS`
2
+ // (`design-extract-script.ts`) and re-sanitised here. The page is untrusted: it can overwrite the
3
+ // recorder, so every value is schema-parsed, every number clamped, and every string that is not a
4
+ // CSS keyword, a bounded identifier or an http(s) URL is dropped — page text never reaches a file.
5
+
6
+ import { t } from '@ultimat3/schema';
7
+ import type { ShotPage } from './browser-launcher-port';
8
+ import { DESIGN_PASS } from './design-extract-script';
9
+
10
+ export type ColorUse = 'background' | 'text' | 'border';
11
+ export type MotionTrigger = 'enter' | 'hover' | 'scroll' | 'loop' | 'state';
12
+
13
+ export interface ObservedColor {
14
+ readonly rgb: readonly [number, number, number];
15
+ readonly alpha: number;
16
+ readonly use: ColorUse;
17
+ /** Painted area for a background, characters for text, elements for a border. */
18
+ readonly weight: number;
19
+ }
20
+
21
+ export interface ObservedFont {
22
+ readonly family: string;
23
+ readonly sizePx: number;
24
+ readonly weight: number;
25
+ readonly uses: number;
26
+ }
27
+
28
+ export interface ObservedShadow {
29
+ readonly x: number;
30
+ readonly y: number;
31
+ readonly blur: number;
32
+ readonly spread: number;
33
+ readonly inset: boolean;
34
+ readonly rgb: readonly [number, number, number];
35
+ readonly alpha: number;
36
+ readonly count: number;
37
+ }
38
+
39
+ export interface ObservedMotion {
40
+ readonly kind: 'animation' | 'transition';
41
+ readonly trigger: MotionTrigger;
42
+ readonly durationMs: number;
43
+ readonly delayMs: number;
44
+ /** A CSS easing keyword or function, or `other` when the page answered something else. */
45
+ readonly easing: string;
46
+ /** `-1` is infinite. */
47
+ readonly iterations: number;
48
+ readonly properties: readonly string[];
49
+ /** How many times this exact record was seen across the captures merged into it. */
50
+ readonly count: number;
51
+ }
52
+
53
+ export interface Extraction {
54
+ readonly colors: readonly ObservedColor[];
55
+ readonly fonts: readonly ObservedFont[];
56
+ readonly spacing: readonly { readonly px: number; readonly count: number }[];
57
+ readonly radii: readonly { readonly px: number; readonly count: number }[];
58
+ readonly shadows: readonly ObservedShadow[];
59
+ readonly backdrop: { readonly count: number; readonly blurPx: readonly number[] };
60
+ readonly canvases: number;
61
+ readonly motion: readonly ObservedMotion[];
62
+ readonly links: readonly string[];
63
+ }
64
+
65
+ const RGB = t.array(t.number);
66
+ const COUNTED = t.array(t.object({ px: t.number, count: t.number }));
67
+ const ANSWER = t.object({
68
+ colors: t.array(t.object({ rgb: RGB, alpha: t.number, use: t.string, weight: t.number })),
69
+ fonts: t.array(
70
+ t.object({ family: t.string, sizePx: t.number, weight: t.number, uses: t.number }),
71
+ ),
72
+ spacing: COUNTED,
73
+ radii: COUNTED,
74
+ shadows: t.array(
75
+ t.object({
76
+ x: t.number,
77
+ y: t.number,
78
+ blur: t.number,
79
+ spread: t.number,
80
+ inset: t.boolean,
81
+ rgb: RGB,
82
+ alpha: t.number,
83
+ count: t.number,
84
+ }),
85
+ ),
86
+ backdrop: t.object({ count: t.number, blurPx: t.array(t.number) }),
87
+ canvases: t.number,
88
+ motion: t.array(
89
+ t.object({
90
+ kind: t.string,
91
+ trigger: t.string,
92
+ durationMs: t.number,
93
+ delayMs: t.number,
94
+ easing: t.string,
95
+ iterations: t.number,
96
+ properties: t.array(t.string),
97
+ }),
98
+ ),
99
+ links: t.array(t.string),
100
+ });
101
+
102
+ const clamp = (value: number, min: number, max: number): number =>
103
+ Number.isFinite(value) ? Math.min(max, Math.max(min, value)) : min;
104
+
105
+ const channel = (value: number | undefined): number => Math.round(clamp(value ?? 0, 0, 255));
106
+
107
+ const rgbOf = (values: readonly number[]): readonly [number, number, number] => [
108
+ channel(values[0]),
109
+ channel(values[1]),
110
+ channel(values[2]),
111
+ ];
112
+
113
+ /**
114
+ * A font family is one bounded token (`Inter`, `system-ui`), then at most three words a family
115
+ * name is made of (`IBM Plex Sans`, `Roboto Mono`). Free text past the first word is refused:
116
+ * the family is page-chosen, and a phrase is an instruction, not a typeface.
117
+ */
118
+ const FAMILY_HEAD = /^[A-Za-z0-9][A-Za-z0-9-]{0,23}$/;
119
+ const FAMILY_WORDS = new Set([
120
+ 'sans',
121
+ 'serif',
122
+ 'mono',
123
+ 'display',
124
+ 'text',
125
+ 'pro',
126
+ 'plex',
127
+ 'code',
128
+ 'condensed',
129
+ 'grotesk',
130
+ 'grotesque',
131
+ 'neue',
132
+ 'ui',
133
+ 'rounded',
134
+ 'slab',
135
+ 'variable',
136
+ 'vf',
137
+ 'std',
138
+ 'new',
139
+ 'one',
140
+ 'next',
141
+ 'narrow',
142
+ 'wide',
143
+ 'extended',
144
+ 'light',
145
+ 'medium',
146
+ 'bold',
147
+ 'book',
148
+ 'regular',
149
+ 'black',
150
+ 'thin',
151
+ 'semibold',
152
+ 'compressed',
153
+ 'round',
154
+ 'italic',
155
+ 'symbol',
156
+ 'emoji',
157
+ 'color',
158
+ 'flex',
159
+ 'serif4',
160
+ ]);
161
+ const isFamily = (family: string): boolean => {
162
+ const [head, ...rest] = family.split(' ');
163
+ return (
164
+ head !== undefined &&
165
+ FAMILY_HEAD.test(head) &&
166
+ rest.length <= 3 &&
167
+ rest.every((word) => FAMILY_WORDS.has(word.toLowerCase()) || /^\d{1,3}$/.test(word))
168
+ );
169
+ };
170
+ const PROPERTY = /^-?[a-zA-Z][a-zA-Z-]{0,39}$/;
171
+ const EASING =
172
+ /^(?:linear|ease|ease-in|ease-out|ease-in-out|step-start|step-end|cubic-bezier\(\s*-?[\d.]+\s*(?:,\s*-?[\d.]+\s*){3}\)|steps\(\s*\d+\s*(?:,\s*[a-z-]+\s*)?\)|linear\([-\d.,%\s]{1,2000}\))$/;
173
+ const USES: readonly ColorUse[] = ['background', 'text', 'border'];
174
+ const TRIGGERS: readonly MotionTrigger[] = ['enter', 'hover', 'scroll', 'loop', 'state'];
175
+
176
+ const httpUrl = (text: string): string | undefined => {
177
+ try {
178
+ const url = new URL(text);
179
+ return url.protocol === 'http:' || url.protocol === 'https:' ? url.href : undefined;
180
+ } catch {
181
+ return undefined;
182
+ }
183
+ };
184
+
185
+ /** The page's answer, parsed and sanitised. A shape that does not parse throws schema's code. */
186
+ export function parseExtraction(value: unknown): Extraction {
187
+ const raw = ANSWER.parse(value, 'design extraction');
188
+ return {
189
+ colors: raw.colors.flatMap((color) => {
190
+ const use = USES.find((known) => known === color.use);
191
+ return use === undefined
192
+ ? []
193
+ : [
194
+ {
195
+ rgb: rgbOf(color.rgb),
196
+ alpha: clamp(color.alpha, 0, 1),
197
+ use,
198
+ weight: clamp(color.weight, 0, 1e9),
199
+ },
200
+ ];
201
+ }),
202
+ fonts: raw.fonts
203
+ .filter((font) => font.family.length <= 48 && isFamily(font.family))
204
+ .map((font) => ({
205
+ family: font.family,
206
+ sizePx: Math.round(clamp(font.sizePx, 1, 400)),
207
+ weight: Math.round(clamp(font.weight, 1, 1000)),
208
+ uses: clamp(font.uses, 0, 1e9),
209
+ })),
210
+ spacing: raw.spacing.map((s) => ({
211
+ px: Math.round(clamp(s.px, 0, 400)),
212
+ count: clamp(s.count, 0, 1e6),
213
+ })),
214
+ radii: raw.radii.map((r) => ({
215
+ px: Math.round(clamp(r.px, 0, 1000)),
216
+ count: clamp(r.count, 0, 1e6),
217
+ })),
218
+ shadows: raw.shadows.map((s) => ({
219
+ x: clamp(s.x, -500, 500),
220
+ y: clamp(s.y, -500, 500),
221
+ blur: clamp(s.blur, 0, 500),
222
+ spread: clamp(s.spread, -500, 500),
223
+ inset: s.inset,
224
+ rgb: rgbOf(s.rgb),
225
+ alpha: clamp(s.alpha, 0, 1),
226
+ count: clamp(s.count, 0, 1e6),
227
+ })),
228
+ backdrop: {
229
+ count: Math.round(clamp(raw.backdrop.count, 0, 1e6)),
230
+ blurPx: raw.backdrop.blurPx.slice(0, 20).map((px) => clamp(px, 0, 500)),
231
+ },
232
+ canvases: Math.round(clamp(raw.canvases, 0, 1e4)),
233
+ motion: raw.motion.slice(0, 600).map((m) => ({
234
+ kind: m.kind === 'transition' ? 'transition' : 'animation',
235
+ trigger: TRIGGERS.find((known) => known === m.trigger) ?? 'state',
236
+ durationMs: clamp(m.durationMs, 0, 60_000),
237
+ delayMs: clamp(m.delayMs, 0, 60_000),
238
+ easing: EASING.test(m.easing.trim()) ? m.easing.trim() : 'other',
239
+ iterations: m.iterations < 0 ? -1 : Math.round(clamp(m.iterations, 0, 1e6)),
240
+ properties: m.properties.filter((p) => PROPERTY.test(p)).slice(0, 12),
241
+ count: 1,
242
+ })),
243
+ links: raw.links.slice(0, 300).flatMap((link) => httpUrl(link) ?? []),
244
+ };
245
+ }
246
+
247
+ /** Run the pass on a page already navigated (with `DESIGN_PREPARE` installed) and parse it. */
248
+ export async function extractDesign(page: ShotPage): Promise<Extraction> {
249
+ return parseExtraction(await page.evaluate(DESIGN_PASS));
250
+ }
251
+
252
+ /** Entries equal under `key` folded into one, `add` summing their weight. */
253
+ function fold<T>(items: readonly T[], key: (item: T) => string, add: (a: T, b: T) => T): T[] {
254
+ const out = new Map<string, T>();
255
+ for (const item of items) {
256
+ const k = key(item);
257
+ const held = out.get(k);
258
+ out.set(k, held === undefined ? item : add(held, item));
259
+ }
260
+ return [...out.values()];
261
+ }
262
+
263
+ /** Several captures of one reference (each viewport, one scheme) as one census. */
264
+ export function mergeExtractions(list: readonly Extraction[]): Extraction {
265
+ const byWeight = <T extends { readonly weight: number }>(a: T, b: T): T => ({
266
+ ...a,
267
+ weight: a.weight + b.weight,
268
+ });
269
+ const byCount = <T extends { readonly count: number }>(a: T, b: T): T => ({
270
+ ...a,
271
+ count: a.count + b.count,
272
+ });
273
+ return {
274
+ colors: fold(
275
+ list.flatMap((e) => e.colors),
276
+ (c) => `${c.use} ${c.rgb.join(' ')} ${String(c.alpha)}`,
277
+ byWeight,
278
+ ),
279
+ fonts: fold(
280
+ list.flatMap((e) => e.fonts),
281
+ (f) => `${f.family}|${String(f.sizePx)}|${String(f.weight)}`,
282
+ (a, b) => ({ ...a, uses: a.uses + b.uses }),
283
+ ),
284
+ spacing: fold(
285
+ list.flatMap((e) => e.spacing),
286
+ (s) => String(s.px),
287
+ byCount,
288
+ ),
289
+ radii: fold(
290
+ list.flatMap((e) => e.radii),
291
+ (r) => String(r.px),
292
+ byCount,
293
+ ),
294
+ shadows: fold(
295
+ list.flatMap((e) => e.shadows),
296
+ (s) => JSON.stringify({ ...s, count: 0 }),
297
+ byCount,
298
+ ),
299
+ backdrop: {
300
+ count: list.reduce((sum, e) => sum + e.backdrop.count, 0),
301
+ blurPx: list.flatMap((e) => e.backdrop.blurPx).slice(0, 20),
302
+ },
303
+ canvases: Math.max(0, ...list.map((e) => e.canvases)),
304
+ motion: fold(
305
+ list.flatMap((e) => e.motion),
306
+ (m) => JSON.stringify({ ...m, count: 0 }),
307
+ byCount,
308
+ ),
309
+ links: [...new Set(list.flatMap((e) => e.links))],
310
+ };
311
+ }
@@ -0,0 +1,180 @@
1
+ // A reference's colours as `defineTheme` palette roles: cluster what was painted, give the page, the
2
+ // text, the accent, a surface and a line a role each, then hold the result to the theme's own
3
+ // contrast table — a role whose pairing fails is DROPPED (it falls back to the shipped palette), so
4
+ // the proposal can never be one `defineTheme` refuses.
5
+
6
+ import type { ColorUse, ObservedColor } from './design-extract';
7
+
8
+ /** `@ultimat3/ui`'s palette facts, handed in: the CLI does not depend on `@ultimat3/ui`. */
9
+ export interface ThemeTables {
10
+ /** Shipped channels per theme, by role (`colorTokens`). */
11
+ readonly colors: Readonly<Record<'light' | 'dark', Readonly<Record<string, string>>>>;
12
+ /** Alias role → the palette role it reads unset (`COLOR_ALIASES`). */
13
+ readonly aliases: Readonly<Record<string, string>>;
14
+ /** Every pairing `defineTheme` measures (`CONTRAST_PAIRS` + `ALIAS_CONTRAST_PAIRS`). */
15
+ readonly pairs: readonly { readonly fg: string; readonly bg: string; readonly minimum: number }[];
16
+ /** `contrastRatio` over two `'r g b'` channel strings. */
17
+ readonly contrast: (a: string, b: string) => number;
18
+ }
19
+
20
+ export interface PaletteCluster {
21
+ readonly channels: string;
22
+ readonly rgb: readonly [number, number, number];
23
+ /** Share of each use's total weight this cluster holds, `0..1`. */
24
+ readonly uses: Readonly<Record<ColorUse, number>>;
25
+ /** Painted area first, then text, then edges: how much of the page this colour is. */
26
+ readonly share: number;
27
+ readonly nearest?: { readonly role: string; readonly distance: number } | undefined;
28
+ }
29
+
30
+ /** Two colours closer than this (RGB distance) are one colour a designer picked. */
31
+ const CLUSTER_DISTANCE = 24;
32
+ /** Max minus min channel: below it a colour is a grey, never an accent. */
33
+ const ACCENT_CHROMA = 64;
34
+ const USES: readonly ColorUse[] = ['background', 'text', 'border'];
35
+
36
+ const distance = (a: readonly number[], b: readonly number[]): number =>
37
+ Math.hypot((a[0] ?? 0) - (b[0] ?? 0), (a[1] ?? 0) - (b[1] ?? 0), (a[2] ?? 0) - (b[2] ?? 0));
38
+
39
+ const channelsOf = (rgb: readonly number[]): string => rgb.join(' ');
40
+ const rgbOf = (channels: string): number[] => channels.split(' ').map(Number);
41
+
42
+ /** Opaque-enough colours only: a 10% scrim is an overlay, not a palette entry. */
43
+ export function clusterPalette(colors: readonly ObservedColor[]): PaletteCluster[] {
44
+ const totals = Object.fromEntries(USES.map((use) => [use, 0])) as Record<ColorUse, number>;
45
+ for (const color of colors) totals[color.use] += color.weight;
46
+ const clusters: { rgb: readonly [number, number, number]; weights: Record<ColorUse, number> }[] =
47
+ [];
48
+ for (const color of [...colors]
49
+ .filter((c) => c.alpha >= 0.5)
50
+ .sort((a, b) => b.weight - a.weight)) {
51
+ const near = clusters.find((cluster) => distance(cluster.rgb, color.rgb) < CLUSTER_DISTANCE);
52
+ if (near !== undefined) near.weights[color.use] += color.weight;
53
+ else {
54
+ const weights = { background: 0, text: 0, border: 0 };
55
+ weights[color.use] = color.weight;
56
+ clusters.push({ rgb: color.rgb, weights });
57
+ }
58
+ }
59
+ return clusters
60
+ .map((cluster) => {
61
+ const uses = {
62
+ background: totals.background > 0 ? cluster.weights.background / totals.background : 0,
63
+ text: totals.text > 0 ? cluster.weights.text / totals.text : 0,
64
+ border: totals.border > 0 ? cluster.weights.border / totals.border : 0,
65
+ };
66
+ return {
67
+ channels: channelsOf(cluster.rgb),
68
+ rgb: cluster.rgb,
69
+ uses,
70
+ share: uses.background * 0.6 + uses.text * 0.3 + uses.border * 0.1,
71
+ };
72
+ })
73
+ .sort((a, b) => b.share - a.share);
74
+ }
75
+
76
+ /** Each cluster beside the shipped role it is closest to in `theme`, for a reader to compare. */
77
+ export function withNearestRoles(
78
+ palette: readonly PaletteCluster[],
79
+ theme: 'light' | 'dark',
80
+ tables: ThemeTables,
81
+ ): PaletteCluster[] {
82
+ const roles = Object.entries(tables.colors[theme]).filter(([role]) => !(role in tables.aliases));
83
+ return palette.slice(0, 16).map((cluster) => {
84
+ let best = { role: '', distance: Number.POSITIVE_INFINITY };
85
+ for (const [role, channels] of roles) {
86
+ const gap = distance(cluster.rgb, rgbOf(channels));
87
+ if (gap < best.distance) best = { role, distance: Math.round(gap) };
88
+ }
89
+ return { ...cluster, nearest: best };
90
+ });
91
+ }
92
+
93
+ const chroma = (rgb: readonly number[]): number => Math.max(...rgb) - Math.min(...rgb);
94
+
95
+ /** Light theme: the page is closer to white than to black; dark: the reverse. */
96
+ const fits = (bg: string, theme: 'light' | 'dark', tables: ThemeTables): boolean => {
97
+ const towardBlack = tables.contrast(bg, '0 0 0');
98
+ const towardWhite = tables.contrast(bg, '255 255 255');
99
+ return theme === 'light' ? towardBlack > towardWhite : towardWhite > towardBlack;
100
+ };
101
+
102
+ /** The roles one scheme's capture proposes, before the contrast table has had its say. */
103
+ function assignRoles(
104
+ palette: readonly PaletteCluster[],
105
+ theme: 'light' | 'dark',
106
+ tables: ThemeTables,
107
+ ): Record<string, string> {
108
+ const byUse = (use: ColorUse) => [...palette].sort((a, b) => b.uses[use] - a.uses[use]);
109
+ const bg = byUse('background')[0];
110
+ if (bg === undefined || bg.uses.background === 0 || !fits(bg.channels, theme, tables)) return {};
111
+ const roles: Record<string, string> = { bg: bg.channels };
112
+ const fg = byUse('text').find(
113
+ (c) => c.uses.text > 0 && tables.contrast(c.channels, bg.channels) >= 4.5,
114
+ );
115
+ if (fg !== undefined) roles['fg'] = fg.channels;
116
+ const surface = byUse('background').find(
117
+ (c) => c !== bg && c.uses.background > 0 && tables.contrast(c.channels, bg.channels) < 1.6,
118
+ );
119
+ // Every surface a component paints on is the page or the one near tone beside it: left on the
120
+ // shipped palette, a surface would be measured against an accent the reference never put on it.
121
+ roles['surface'] = surface?.channels ?? bg.channels;
122
+ roles['bg-soft'] = surface?.channels ?? bg.channels;
123
+ roles['surface-raised'] = surface?.channels ?? bg.channels;
124
+ // A FILLED colour first (a button, a badge): text in a hue is as often the browser's default link
125
+ // blue as it is a brand, and a fill is always somebody's choice.
126
+ const accent = palette
127
+ .filter((c) => c !== bg && c !== fg && chroma(c.rgb) >= ACCENT_CHROMA)
128
+ .sort(
129
+ (a, b) =>
130
+ b.uses.background + b.uses.border - (a.uses.background + a.uses.border) ||
131
+ b.share - a.share,
132
+ )[0];
133
+ if (accent !== undefined) {
134
+ roles['accent'] = accent.channels;
135
+ // The text ON the accent: whichever of the page, white or near-black reads best on it.
136
+ const [onAccent] = [bg.channels, '255 255 255', '17 15 13'].sort(
137
+ (a, b) => tables.contrast(b, accent.channels) - tables.contrast(a, accent.channels),
138
+ );
139
+ if (onAccent !== undefined) roles['accent-fg'] = onAccent;
140
+ }
141
+ const line = byUse('border').find((c) => c !== bg && c.uses.border > 0);
142
+ if (line !== undefined) roles['line'] = line.channels;
143
+ return roles;
144
+ }
145
+
146
+ /**
147
+ * `defineTheme`'s own measurement, run until it passes: a failing pairing drops the proposed role
148
+ * on its foreground side (else its background), and the shipped palette — which passes every
149
+ * pairing — is what the role falls back to. Terminates: each round removes a role or stops.
150
+ */
151
+ export function repairContrast(
152
+ roles: Record<string, string>,
153
+ theme: 'light' | 'dark',
154
+ tables: ThemeTables,
155
+ ): Record<string, string> {
156
+ const out = { ...roles };
157
+ const source = (role: string): string => tables.aliases[role] ?? role;
158
+ const own = (role: string): string | undefined => out[role] ?? out[source(role)];
159
+ const resolved = (role: string): string =>
160
+ own(role) ?? tables.colors[theme][source(role)] ?? '0 0 0';
161
+ for (;;) {
162
+ const failing = tables.pairs.find(
163
+ (pair) =>
164
+ (own(pair.fg) !== undefined || own(pair.bg) !== undefined) &&
165
+ tables.contrast(resolved(pair.fg), resolved(pair.bg)) < pair.minimum,
166
+ );
167
+ if (failing === undefined) return out;
168
+ const drop = own(failing.fg) !== undefined ? failing.fg : failing.bg;
169
+ delete out[drop in out ? drop : source(drop)];
170
+ }
171
+ }
172
+
173
+ /** One scheme's capture as the colour overrides for that theme, contrast-checked; `{}` for none. */
174
+ export function proposeColors(
175
+ palette: readonly PaletteCluster[],
176
+ theme: 'light' | 'dark',
177
+ tables: ThemeTables,
178
+ ): Record<string, string> {
179
+ return repairContrast(assignRoles(palette, theme, tables), theme, tables);
180
+ }