command-code 1.93.0 → 1.93.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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,15 @@
1
1
  # command-code
2
2
 
3
+ ## 1.93.2
4
+
5
+ ### Patch Changes
6
+
7
+ - feat: open models like DeepSeek now follow `/design` instead of ignoring its instructions. Each turn names the skill sections that govern it, carries the reflex list, and ends with a bundled check that measures contrast and sweeps for reflexes before the work is called done. `check.mjs --pair` measures candidate colors before they are written, and the check now covers `/design variants` output and a broken design-system preview link
8
+
9
+ ## 1.93.1
10
+
11
+ - feat: /design support for open models
12
+
3
13
  ## 1.93.0
4
14
 
5
15
  ### Minor Changes
@@ -60,6 +60,7 @@ The model catalog — every id `/model`, `--model`, `model:effort` shorthand, an
60
60
  | `nvidia/nemotron-3.5-super-vl` | Nemotron 3.5 Super VL | 262K | low, medium, high | $0.2/$0.5 · cache $0.04 | Go and above | open vision-language model for coding and documents |
61
61
  | `thinkingmachines/inkling` | Inkling | 256K | — | $1/$4.05 · cache $0.17 | Go and above | multimodal MoE reasoning |
62
62
  | `thinkingmachines/inkling-small` | Inkling Small | 1M | — | $0.5/$1.2 · cache $0.1 | Go and above | lightweight MoE reasoning at lower cost and latency |
63
+ | `thinkingmachines/inkling-2-mini` | Inkling 2 Mini | 1.05M | off, low, medium, high, max | $0.075/$0.3 · cache $0.015 | Go and above | compact multimodal reasoning with 1M context |
63
64
  | `recursive/flint-v1.0:free` | Flint | 262K | — | $0/$0 · cache $0 | Go and above | open-weight MoE coding model, 2.5B active |
64
65
  | `inclusionai/ling-3.1-flash` | Ling 3.1 Flash | 262K | low, medium, high | $0.3/$0.9 · cache $0.06 | Go and above | hybrid-reasoning MoE for coding & tool-using agents |
65
66
  | `inclusionai/ling-3.1-flash-1019` | Ling 3.1 Flash 1019 | 1M | low, medium, high | $0.3/$0.9 · cache $0.06 | Go and above | hybrid-reasoning MoE for coding & tool-using agents |
@@ -347,6 +347,7 @@ Valid model ids (the /model catalog — use these EXACT ids):
347
347
  - nvidia/nemotron-3.5-super-vl
348
348
  - thinkingmachines/inkling
349
349
  - thinkingmachines/inkling-small
350
+ - thinkingmachines/inkling-2-mini
350
351
  - recursive/flint-v1.0:free
351
352
  - stealth/glyph-cluster:free
352
353
  - inclusionai/ling-3.1-flash
@@ -7,6 +7,10 @@ description: "Design partner for frontend interfaces. One command covers every v
7
7
 
8
8
  You are the user's design partner. One command for every visual discipline. Read this once, route to the right tool, do the work.
9
9
 
10
+ ## Reflexes
11
+
12
+ [references/reflexes.md](references/reflexes.md) names the patterns generated design converges on — purple-blue gradients, glassmorphism, card-ification, feature tile grids, pill-everything, floating stat cards, section eyebrow labels, reflex fonts, emoji copy, blanket fade-ins. These are reflexes, not decisions, and they hold in every tool and every mode: none of them appears in my output unless the user asked for that specific element by name, and a granted exception unlocks only the named element in the named place. Before I call design work done, I check the output against that file's gate.
13
+
10
14
  ## How a turn runs
11
15
 
12
16
  1. **Pick a tool.** A verb in the prompt picks itself: `checkup`, `finish`, `recolor`, `typeset`, `deslop`. A freeform prompt ("make this hero stronger") chooses the closest tool and proceeds without waiting for tool confirmation — but still runs steps 2 and 3 before acting. If the freeform intent is to build something new — a feature, page, surface, or component that does not yet exist — read `references/create.md` first and follow its guidance.
@@ -221,6 +225,7 @@ Audit modes (`smell`, `checkup`, `review`), `setup`, and behavior modes (`motion
221
225
 
222
226
  Discipline references, available to any tool:
223
227
 
228
+ - [references/reflexes.md](references/reflexes.md) — the generated-design reflexes no tool reaches for (see top of this file)
224
229
  - [references/color.md](references/color.md), [references/layout.md](references/layout.md), [references/border.md](references/border.md), [references/shadow.md](references/shadow.md), [references/motion.md](references/motion.md), [references/interaction.md](references/interaction.md), [references/responsive.md](references/responsive.md), [references/writing.md](references/writing.md)
225
230
  - [references/media.md](references/media.md) for art-directing, sourcing, and verifying real photos and video before they ship — required reading for any mode that adds an external image or video URL
226
231
  - [references/accessibility.md](references/accessibility.md) for focus, keyboard, ARIA, forms, live regions, hit areas, zoom (`a11y`) — required reading for any mode that touches a control, a form, an overlay, or motion
@@ -409,6 +414,8 @@ Deeper rules: [references/voice.md](references/voice.md), [references/surface.md
409
414
 
410
415
  I verify every completion claim before I say it.
411
416
 
417
+ Before the final message I run `scripts/check.mjs` from this skill's directory against the project (`node "<skill dir>/scripts/check.mjs" <project dir>`). It measures contrast — WCAG and APCA — and sweeps the reflexes in [references/reflexes.md](references/reflexes.md). Its contrast numbers outrank my own estimate, and I can name the decision behind each WARN. What I do with a FAIL follows the turn, not the script: in a report mode I fix nothing and carry it into the report as a finding. In a mode that changes files I fix every FAIL inside what the request covers and run the check again until none remain there; a FAIL outside the request, or on an element the user asked for by name, stays as it is and I name it in the final message. When the check says it read no files (JSX, Vue, Svelte, Tailwind classes), I measure contrast myself and say the check did not cover the project.
418
+
412
419
  Before the final message, I check each thing I plan to claim against the actual changed files and the rendered interface when a visual result is available.
413
420
 
414
421
  I only use "added", "fixed", "changed", "improved", "refined", "animated", "made", or "updated" when I can point to a real implementation change and see the effect in the UI or rendered output.
@@ -1,5 +1,7 @@
1
1
  # Checkup: `/design checkup`
2
2
 
3
+ The reflexes in [reflexes.md](reflexes.md) hold here: I don't produce them, and I flag every one I find, unless the user asked for that element by name.
4
+
3
5
  I use checkup for fast design triage. It tells me whether an interface is basically healthy or whether something is unsafe to ship.
4
6
 
5
7
  This is not a deep critique. It is a vital-sign read.
@@ -1,5 +1,7 @@
1
1
  # Deslop: `/design deslop`
2
2
 
3
+ The reflexes in [reflexes.md](reflexes.md) hold here: I don't produce them, and I flag every one I find, unless the user asked for that element by name.
4
+
3
5
  Deslop removes AI slop from a design surface. I don't repaint for its own sake, I don't polish what no report flagged, and I don't add new effects. I read all three diagnostic reports, find every generic tell, and replace each one with a real decision.
4
6
 
5
7
  This mode is the treatment that follows the full diagnostic pass. Reports find the rot. Deslop cuts it out and replaces it with authored work.
@@ -0,0 +1,132 @@
1
+ # Reflexes: The Patterns I Don't Reach For
2
+
3
+ Generated design has a look, and everyone can see it. It is not one bad element — it is the sum of reflexes: the gradient nobody chose, the grid nobody questioned, the font nobody considered. Each pattern below is a decision I skipped, dressed up as a decision I made.
4
+
5
+ This file holds in every tool and every mode. [smell.md](smell.md) diagnoses these tells after the fact; here I catch the reflex before it reaches the file.
6
+
7
+ ---
8
+
9
+ ## The Only Exception
10
+
11
+ A pattern from this file is right only when the user asks for that specific element by name in the current request.
12
+
13
+ "Make it modern" is not that. "Use glassmorphism on the nav" is.
14
+
15
+ When the exception fires, it covers exactly the named element in exactly the named place, and I execute it deliberately and well — a chosen pattern is different work from a reflexive one. Nothing else lifts a pattern off this list: not the brief, not the category, not a previous project, not my own taste. When in doubt, I design something else.
16
+
17
+ ---
18
+
19
+ ## Why These Patterns Fail
20
+
21
+ Generative models converge on the statistical average of their training data: the same gradients, the same card grids, the same fonts, the same fade-ins. The average of all design is not design — it is the absence of a point of view.
22
+
23
+ Competent and generic is still generic. Every pattern below fails not because it is ugly but because it means no one was making decisions.
24
+
25
+ ---
26
+
27
+ ## Color and Surface
28
+
29
+ I never use:
30
+
31
+ - **Purple-to-blue gradients** on heroes, backgrounds, buttons, or text. This is the single most recognized tell. The same ban covers indigo-to-violet, blue-purple-to-cyan, and every near neighbor of that family used as a default.
32
+ - **Glassmorphism**: frosted, semi-transparent panels floating on soft color fields. No `backdrop-filter` cards on gradient backgrounds.
33
+ - **Neon glows**: glowing borders, glowing text shadows, cyber accent halos.
34
+ - **Hacker monotone**: monospace-on-dark as a reflex for anything developer-adjacent. Monospace is for code, data, and deliberate art direction.
35
+ - **Pastel wash**: soft lavender, mint, or peach fields that exist because no color decision was made.
36
+ - **Heavy drop shadows**: dramatic elevation like `0 25px 50px -12px rgba(0,0,0,0.15)` on cards and images to fake depth. Real products do not need theatrical shadows to feel tactile. Depth comes from subtle borders, minimal shadows, or none.
37
+ - **Low-contrast text on color.** Every pair passes contrast checks. No exceptions.
38
+
39
+ Instead: a hue with a reason tied to this product, built in OKLCH, neutrals tinted toward the brand, one commitment level chosen and held.
40
+
41
+ ---
42
+
43
+ ## Layout and Structure
44
+
45
+ I never use:
46
+
47
+ - **Card-ification**: every section wrapped in a bordered, rounded card. Cards are for content that is genuinely card-shaped — discrete, self-contained, scannable as a unit.
48
+ - **Nested cards.** A card inside a card is never right. I flatten with type and dividers.
49
+ - **The feature tile grid**: icon + heading + one-sentence description, repeated in a uniform grid. The single most common generated section. I lead with the strongest item, vary the layout, or cut the section if it is filler. Uniform tiles need an explicit request.
50
+ - **The template hero**: badge + centered headline + subheadline + two pill buttons + image, or big number plus small label plus stat cards, or a "Trusted by" logo bar, in the order everyone has already seen. I recompose: asymmetry, a different content hierarchy, or one dominant action instead of the dual-button default.
51
+ - **Floating stat cards**: absolutely positioned cards with soft shadows hovering around a hero image for "visual interest." Stats belong in the content flow, not floating as decoration.
52
+ - **Uniform radius**: one border-radius applied globally by reflex. Radius is a decision per component role.
53
+ - **Pill-shaped everything**: `border-radius: 100px` or `9999px` on buttons, badges, and inputs as the default "modern" look. Full rounding is a deliberate choice for at most one component role, not a house style.
54
+ - **Section eyebrow labels**: a small uppercase label ("WHAT WE OFFER") above every heading. Decorative noise. Headings stand on their own.
55
+ - **Thick colored borders on rounded cards**, and **giant decorative icons above headings**.
56
+ - **Off-scale spacing**: random gaps, 18px next to 8px, misaligned grid elements. Every value comes from the spacing scale.
57
+ - **Stray whitespace and gradient cutoffs**: blank blocks and hard image edges that look like unfixed bugs.
58
+ - **Unnecessary modals**: content hidden behind popups because composing the page was harder. A modal needs a reason.
59
+
60
+ Instead: composition derived from the work pattern. If the layout could be pasted into an unrelated product without becoming wrong, it is too generic and I recompose.
61
+
62
+ ---
63
+
64
+ ## Typography and Copy
65
+
66
+ I never use:
67
+
68
+ - **Reflex fonts**: Inter, Roboto, Plus Jakarta Sans, or any generic sans chosen because it is safe. System fonts are legitimate for product UI. On brand surfaces the typeface is a decision.
69
+ - **Reflex pairings**: DM Sans + DM Serif Display, Inter + Playfair Display, Space Grotesk on anything "tech" — pairings that signal "friendly and premium" without a reason tied to this product. A pairing earns its place or I use system fonts and let composition carry the character.
70
+ - **Style hodgepodge**: one word of a headline in a different font, weight, or gradient fill for no structural reason.
71
+ - **Emoji in UI copy**: not in headings, buttons, labels, empty states, or microcopy.
72
+ - **Filler copy**: "Clean. Modern. Simple.", "Supercharge your workflow", "Unlock the power of", vague benefit-speak with no voice, placeholder text shipped as content.
73
+ - **Exclamation points, Title Case buttons, or em dashes**, per the writing rules.
74
+ - **Flat hierarchy**: heading levels so close they blur. Minimum 1.3 scale ratio on product surfaces.
75
+
76
+ Instead: copy that names the actual thing, the actual action, the actual work.
77
+
78
+ ---
79
+
80
+ ## Iconography and Assets
81
+
82
+ I never use:
83
+
84
+ - **3D abstract humans**: faceless gradient figures in impossible poses, floating geometric collaboration blobs.
85
+ - **Mixed icon sets**: outline next to filled next to duotone in one view. One set, one stroke weight, one size grid.
86
+ - **Hallucinated icons**: icons that do not match their labels, abstract shapes standing in for meaning. Every icon is verified against its label.
87
+ - **Off-theme strays**: a lone component in the wrong theme color or style, betraying a paste from another context.
88
+
89
+ Instead: one curated icon set used consistently, or real product imagery and domain artifacts as proof.
90
+
91
+ ---
92
+
93
+ ## Motion and Interaction
94
+
95
+ I never use:
96
+
97
+ - **Blanket scroll reveals**: every element fading in and rising as the page scrolls, uniformly.
98
+ - **Bounce and elastic easing.** Toys, dated on arrival.
99
+ - **Uniform stagger delays**: mechanical index-times-constant cascades. The eye reads mechanical precision as robotic.
100
+ - **Default parallax**: parallax as reflex rather than directed camera work.
101
+ - **Layout-property animation.** Only `transform` and `opacity`.
102
+ - **Idle-only components.** A component designed in one state is a sketch. All nine states exist.
103
+
104
+ Instead: motion as character — physics-based, sharp deceleration, exits at roughly 70% of entrance duration, `prefers-reduced-motion` respected.
105
+
106
+ ---
107
+
108
+ ## The Gate
109
+
110
+ Before I call design work done, I read the actual output the way a stranger would:
111
+
112
+ 1. **Gradient check** — search the styles for gradients. Any purple, blue, or violet family gradient without an explicit request gets removed.
113
+ 2. **Card census** — count cards. Nested cards get flattened. Cards holding non-card-shaped content get restructured. A uniform icon-heading-sentence tile grid gets broken or cut.
114
+ 3. **Radius and shadow sweep** — search for `border-radius` and `box-shadow`. Pill radii outside one deliberate role get squared to 4–8px. Theatrical shadows get replaced with borders or minimal elevation. One global radius gets differentiated per role.
115
+ 4. **Hero check** — does the hero follow badge-headline-subtext-two-buttons-image, or have floating decorative cards? It gets recomposed.
116
+ 5. **Font check** — is the typeface (and the pairing) a decision or a reflex? An unjustified Inter, Roboto, or DM Sans + DM Serif Display gets replaced or justified.
117
+ 6. **Copy read** — any emoji, filler phrase, exclamation point, Title Case button, or uppercase eyebrow label above a heading gets rewritten or removed.
118
+ 7. **Spacing lint** — every margin, padding, and gap on the scale. Off-scale values get fixed.
119
+ 8. **Icon audit** — one set, and every icon matches its label.
120
+ 9. **Motion audit** — no bounce, no blanket scroll reveal, reduced motion handled.
121
+ 10. **The two-second test** — if a stranger could glance at this and say "AI made that", it has failed. I rework the reflex, not the symptom.
122
+
123
+ In a mode that changes files, a failed check inside the request gets fixed before I respond. A failed check outside the request, or on an element the user named, stays as it is and I name it in my reply. In a report mode every failed check becomes a finding instead. The fix goes after the reflex, not the symptom — swapping a purple gradient for a teal one, or a pill button for its nearest rounded neighbor, is the same skipped decision wearing a different color.
124
+
125
+ ---
126
+
127
+ ## How I Know the Work Is Mine
128
+
129
+ - Every pattern in the output traces to a decision about this product, or to an element the user named
130
+ - "The brief implies it" and "it fits the category" never stood in for a decision
131
+ - The gate ran and every check passed
132
+ - A stranger glancing at the result would not say a machine made it
@@ -1,5 +1,7 @@
1
1
  # Smell: `/design smell`
2
2
 
3
+ The reflexes in [reflexes.md](reflexes.md) hold here: I don't produce them, and I flag every one I find, unless the user asked for that element by name.
4
+
3
5
  I use smell to catch generic design before it spreads. This is not a broad review. It is a detector for reflex, template, and generated sameness.
4
6
 
5
7
  When a surface smells wrong, I fix the category reflex first. Cosmetic edits do not remove the odor.
@@ -0,0 +1,213 @@
1
+ // Color math and parsing for check.mjs. A color is gamma-encoded sRGB, each channel 0–1.
2
+ import {NAMED_COLORS} from './named-colors.mjs';
3
+
4
+ /** @typedef {readonly number[]} Rgb */
5
+ /** @typedef {{readonly rgb: Rgb, readonly alpha: number}} Color */
6
+ /** @typedef {Readonly<Record<string, string>>} Vars */
7
+
8
+ const MAX_VAR_DEPTH = 12;
9
+ // `#abc`, `rgb(…)`, and bare words — a word only counts when it is a named color.
10
+ const COLOR_LITERAL =
11
+ /#[0-9a-f]{3,8}\b|(?:rgba?|hsla?|oklch)\([^)]*\)|\b[a-z]+\b/gi;
12
+ // Not colors: a path such as url("blue/blue.webp") or a quoted string.
13
+ const NON_COLOR_TEXT = /url\([^)]*\)|"[^"]*"|'[^']*'/gi;
14
+ const VAR_NAME = /var\(\s*(--[\w-]+)/g;
15
+ const VAR_REFERENCE =
16
+ /var\(\s*(--[\w-]+)\s*(?:,\s*([^()]*(?:\([^()]*\)[^()]*)*))?\)/g;
17
+
18
+ /** @param {number} c @returns {number} */
19
+ function toLinear(c) {
20
+ return c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;
21
+ }
22
+
23
+ /** @param {number} c @returns {number} */
24
+ function toGamma(c) {
25
+ const clamped = Math.min(Math.max(c, 0), 1);
26
+ return clamped <= 0.0031308
27
+ ? clamped * 12.92
28
+ : 1.055 * clamped ** (1 / 2.4) - 0.055;
29
+ }
30
+
31
+ /** @param {{l: number, c: number, h: number}} oklch @returns {Rgb} */
32
+ function oklchToRgb({l, c, h}) {
33
+ const a = c * Math.cos((h * Math.PI) / 180);
34
+ const b = c * Math.sin((h * Math.PI) / 180);
35
+ const l1 = (l + 0.3963377774 * a + 0.2158037573 * b) ** 3;
36
+ const m1 = (l - 0.1055613458 * a - 0.0638541728 * b) ** 3;
37
+ const s1 = (l - 0.0894841775 * a - 1.291485548 * b) ** 3;
38
+ return [
39
+ 4.0767416621 * l1 - 3.3077115913 * m1 + 0.2309699292 * s1,
40
+ -1.2684380046 * l1 + 2.6097574011 * m1 - 0.3413193965 * s1,
41
+ -0.0041960863 * l1 - 0.7034186147 * m1 + 1.707614701 * s1,
42
+ ].map(toGamma);
43
+ }
44
+
45
+ /** Gamma sRGB → OKLCH, for hue and chroma checks. @param {Rgb} rgb */
46
+ export function rgbToOklch(rgb) {
47
+ const [r, g, b] = rgb.map(toLinear);
48
+ const l = Math.cbrt(0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b);
49
+ const m = Math.cbrt(0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b);
50
+ const s = Math.cbrt(0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b);
51
+ const L = 0.2104542553 * l + 0.793617785 * m - 0.0040720468 * s;
52
+ const A = 1.9779984951 * l - 2.428592205 * m + 0.4505937099 * s;
53
+ const B = 0.0259040371 * l + 0.7827717662 * m - 0.808675766 * s;
54
+ const hue = ((Math.atan2(B, A) * 180) / Math.PI + 360) % 360;
55
+ return {l: L, c: Math.hypot(A, B), h: hue};
56
+ }
57
+
58
+ /** @param {{h: number, s: number, l: number}} hsl @returns {Rgb} */
59
+ function hslToRgb({h, s, l}) {
60
+ const k = n => (n + h / 30) % 12;
61
+ const a = s * Math.min(l, 1 - l);
62
+ return [0, 8, 4].map(
63
+ n => l - a * Math.max(-1, Math.min(k(n) - 3, 9 - k(n), 1)),
64
+ );
65
+ }
66
+
67
+ /** @param {{text: Rgb, background: Rgb}} pair @returns {number} */
68
+ export function wcagRatio({text, background}) {
69
+ const lum = rgb => {
70
+ const [r, g, b] = rgb.map(toLinear);
71
+ return 0.2126 * r + 0.7152 * g + 0.0722 * b;
72
+ };
73
+ const [hi, lo] = [lum(text), lum(background)].sort((x, y) => y - x);
74
+ return (hi + 0.05) / (lo + 0.05);
75
+ }
76
+
77
+ /** APCA-W3 0.0.98G — the measure color.md defaults to. @param {{text: Rgb, background: Rgb}} pair */
78
+ export function apcaLc({text, background}) {
79
+ const y = ([r, g, b]) => {
80
+ const raw =
81
+ 0.2126729 * r ** 2.4 + 0.7151522 * g ** 2.4 + 0.072175 * b ** 2.4;
82
+ // biome-ignore lint/suspicious/noApproximativeNumericConstant: APCA-W3 specifies blkClmp = 1.414 exactly; Math.SQRT2 would change the published formula.
83
+ return raw < 0.022 ? raw + (0.022 - raw) ** 1.414 : raw;
84
+ };
85
+ const yText = y(text);
86
+ const yBackground = y(background);
87
+ if (Math.abs(yBackground - yText) < 0.0005) return 0;
88
+ if (yBackground > yText) {
89
+ const sapc = (yBackground ** 0.56 - yText ** 0.57) * 1.14;
90
+ return sapc < 0.1 ? 0 : (sapc - 0.027) * 100;
91
+ }
92
+ const sapc = (yBackground ** 0.65 - yText ** 0.62) * 1.14;
93
+ return sapc > -0.1 ? 0 : (sapc + 0.027) * 100;
94
+ }
95
+
96
+ /** @param {{value: string, vars: Vars, depth?: number}} params @returns {string} */
97
+ export function resolveVars({value, vars, depth = 0}) {
98
+ if (depth > MAX_VAR_DEPTH) return value;
99
+ const next = value.replace(
100
+ VAR_REFERENCE,
101
+ (_, name, fallback) => vars[name] ?? fallback ?? '',
102
+ );
103
+ if (next === value) return next;
104
+ return resolveVars({value: next, vars, depth: depth + 1});
105
+ }
106
+
107
+ /** Every custom property a value reads, through the tokens it points at. */
108
+ export function referencedVars({value, vars, depth = 0}) {
109
+ if (depth > MAX_VAR_DEPTH) return [];
110
+ return [...value.matchAll(VAR_NAME)].flatMap(([, name = '']) => [
111
+ name,
112
+ ...referencedVars({value: vars[name] ?? '', vars, depth: depth + 1}),
113
+ ]);
114
+ }
115
+
116
+ /**
117
+ * Tokens a value reads that this cascade never sets and that have no fallback: the color is
118
+ * defined somewhere this script did not see, so it cannot be measured.
119
+ */
120
+ export function unresolvedVars({value, vars, depth = 0}) {
121
+ if (depth > MAX_VAR_DEPTH) return [];
122
+ return [...value.matchAll(VAR_REFERENCE)].flatMap(
123
+ ([, name = '', fallback]) => {
124
+ const set = vars[name];
125
+ if (set !== undefined)
126
+ return unresolvedVars({value: set, vars, depth: depth + 1});
127
+ if (fallback === undefined) return [name];
128
+ return unresolvedVars({value: fallback, vars, depth: depth + 1});
129
+ },
130
+ );
131
+ }
132
+
133
+ /** `50%` → 0.5 × scale; a bare number is returned as is. @param {{token: string, scale?: number}} params */
134
+ function parseNumber({token, scale = 1}) {
135
+ const text = token.trim();
136
+ if (text.endsWith('%')) return (Number.parseFloat(text) / 100) * scale;
137
+ return Number.parseFloat(text);
138
+ }
139
+
140
+ /** HSL saturation and lightness: `40%`, or a bare `40` (CSS Color 4) — both mean 0.4. */
141
+ function parseHslPercent(token) {
142
+ return Number.parseFloat(token) / 100;
143
+ }
144
+
145
+ /** @param {string} digits @returns {Color | null} */
146
+ function readHex(digits) {
147
+ if (![3, 4, 6, 8].includes(digits.length)) return null;
148
+ const full =
149
+ digits.length <= 4 ? [...digits].map(d => d + d).join('') : digits;
150
+ const channels = [0, 2, 4, 6].map(
151
+ i => Number.parseInt(full.slice(i, i + 2), 16) / 255,
152
+ );
153
+ const alpha = full.length === 8 ? (channels[3] ?? 1) : 1;
154
+ return {rgb: channels.slice(0, 3), alpha};
155
+ }
156
+
157
+ /** @param {{space: string, parts: readonly string[]}} params @returns {Rgb} */
158
+ function channelsToRgb({space, parts}) {
159
+ const [first = '', second = '', third = ''] = parts;
160
+ if (space.startsWith('rgb')) {
161
+ return [first, second, third].map(part =>
162
+ part.endsWith('%')
163
+ ? parseNumber({token: part})
164
+ : Number.parseFloat(part) / 255,
165
+ );
166
+ }
167
+ if (space.startsWith('hsl')) {
168
+ return hslToRgb({
169
+ h: Number.parseFloat(first),
170
+ s: parseHslPercent(second),
171
+ l: parseHslPercent(third),
172
+ });
173
+ }
174
+ return oklchToRgb({
175
+ l: parseNumber({token: first}),
176
+ c: parseNumber({token: second, scale: 0.4}),
177
+ h: Number.parseFloat(third),
178
+ });
179
+ }
180
+
181
+ /** Any color value, translucent or not, or null (gradient, keyword, unknown). */
182
+ function readColor({value, vars}) {
183
+ const text = resolveVars({value, vars}).trim().toLowerCase();
184
+ if (Object.hasOwn(NAMED_COLORS, text)) return readHex(NAMED_COLORS[text]);
185
+ const hex = text.match(/^#([0-9a-f]{3,8})$/);
186
+ if (hex) return readHex(hex[1] ?? '');
187
+ const fn = text.match(/^(rgba?|hsla?|oklch)\(([^)]*)\)$/);
188
+ if (!fn) return null;
189
+ const [channels = '', slashAlpha] = (fn[2] ?? '').split('/');
190
+ const parts = channels.split(/[\s,]+/).filter(Boolean);
191
+ if (parts.length < 3) return null;
192
+ const alphaToken = slashAlpha ?? parts[3];
193
+ const alpha = alphaToken ? parseNumber({token: alphaToken}) : 1;
194
+ return {rgb: channelsToRgb({space: fn[1] ?? '', parts}), alpha};
195
+ }
196
+
197
+ /** A solid, opaque color, or null. @param {{value: string, vars: Vars}} params @returns {Rgb | null} */
198
+ export function parseColor({value, vars}) {
199
+ const color = readColor({value, vars});
200
+ if (!color || color.alpha < 1) return null;
201
+ return color.rgb;
202
+ }
203
+
204
+ /** Every color in a value, solid or not — for hue sweeps inside gradients and shadows. */
205
+ export function colorsIn({value, vars}) {
206
+ const literals =
207
+ resolveVars({value, vars})
208
+ .replace(NON_COLOR_TEXT, ' ')
209
+ .match(COLOR_LITERAL) ?? [];
210
+ return literals
211
+ .map(literal => readColor({value: literal, vars: {}})?.rgb ?? null)
212
+ .filter(rgb => rgb !== null);
213
+ }
@@ -0,0 +1,141 @@
1
+ // Contrast for check.mjs: WCAG 2 AA on rules that set a text color, APCA as the second read.
2
+ import {
3
+ apcaLc,
4
+ parseColor,
5
+ referencedVars,
6
+ unresolvedVars,
7
+ wcagRatio,
8
+ } from './color.mjs';
9
+ import {
10
+ backgroundColor,
11
+ declarations,
12
+ hasBackground,
13
+ textSize,
14
+ } from './css.mjs';
15
+
16
+ export const NORMAL_RATIO = 4.5;
17
+ export const LARGE_RATIO = 3;
18
+ export const NORMAL_APCA = 60;
19
+ export const LARGE_APCA = 45;
20
+ // Text measured only against the page background: below 2:1 it almost certainly sits on its own
21
+ // section backdrop (light text in a dark band), so reporting it is noise. Muted text on the page
22
+ // itself — the real failure — lands between 2:1 and the threshold.
23
+ const PAGE_PAIR_FLOOR = 2;
24
+ const UNMEASURED_STATE = /disabled|::?placeholder|::selection/i;
25
+
26
+ /** @typedef {import('./css.mjs').Rule} Rule */
27
+ /** @typedef {{level: 'FAIL' | 'WARN', check: string, source: string, selector: string, detail: string}} Finding */
28
+
29
+ /** @typedef {{readonly rgb: readonly number[], readonly value: string}} Page */
30
+
31
+ /**
32
+ * Why a value's color is unknowable here: a token set differently in sheets of unknown order, or
33
+ * a token this cascade never sets (an @import or link this script could not follow, a sheet only a
34
+ * component imports). @returns {string | null}
35
+ */
36
+ function unknowable({value, vars, uncertain}) {
37
+ const conflicting = referencedVars({value, vars}).find(name =>
38
+ uncertain.has(name),
39
+ );
40
+ if (conflicting)
41
+ return `${conflicting} is set to different values in stylesheets whose load order is unknown`;
42
+ const missing = unresolvedVars({value, vars})[0];
43
+ if (missing)
44
+ return `${missing} is not set in any stylesheet this check could tie to the rule`;
45
+ return null;
46
+ }
47
+
48
+ /**
49
+ * A pair read through a token whose value is unknown is not measured at all: a pass and a fail
50
+ * are equally unfounded, and skipping it once hid a real 2.85:1 FAIL behind a clean report. Text
51
+ * with no background of its own is measured against the page, so the page's tokens count too.
52
+ * @param {{rule: Rule, decl: Readonly<Record<string, string>>, vars: Readonly<Record<string, string>>, uncertain: ReadonlySet<string>, page: Page}} params
53
+ * @returns {Finding | null}
54
+ */
55
+ function unverifiedFinding({rule, decl, vars, uncertain, page}) {
56
+ const own = [decl.color, decl['background-color'], decl.background].join(
57
+ ' ',
58
+ );
59
+ const value = hasBackground(decl) ? own : `${own} ${page.value}`;
60
+ const reason = unknowable({value, vars, uncertain});
61
+ if (!reason) return null;
62
+ return {
63
+ level: 'WARN',
64
+ check: 'contrast',
65
+ source: rule.source,
66
+ selector: rule.selector,
67
+ detail: `unverified — ${reason}; measure the rendered page`,
68
+ };
69
+ }
70
+
71
+ /**
72
+ * @param {{rule: Rule, vars: Readonly<Record<string, string>>, uncertain: ReadonlySet<string>, page: Page, rootPx: number}} params
73
+ * @returns {Finding | null}
74
+ */
75
+ function contrastFinding({rule, vars, uncertain, page, rootPx}) {
76
+ if (UNMEASURED_STATE.test(rule.selector)) return null;
77
+ const decl = declarations(rule.body);
78
+ if (!decl.color) return null;
79
+ const unverified = unverifiedFinding({rule, decl, vars, uncertain, page});
80
+ if (unverified) return unverified;
81
+ const text = parseColor({value: decl.color, vars});
82
+ if (!text) return null;
83
+ const own = backgroundColor({decl, vars});
84
+ // A background this script cannot measure (gradient, image, translucent) is still the text's
85
+ // real backdrop — comparing against the page instead would be noise.
86
+ if (!own && hasBackground(decl)) return null;
87
+
88
+ const pair = {text, background: own ?? page.rgb};
89
+ const ratio = wcagRatio(pair);
90
+ if (!own && ratio < PAGE_PAIR_FLOOR) return null;
91
+ const size = textSize({decl, rootPx});
92
+ const needed = size === 'large' ? LARGE_RATIO : NORMAL_RATIO;
93
+ const shown = `${ratio.toFixed(2)}:1`;
94
+ const where = {source: rule.source, selector: rule.selector};
95
+ const largeNote = size === 'large' ? ' (large text)' : '';
96
+
97
+ if (own && size === 'unknown' && ratio >= LARGE_RATIO && ratio < needed) {
98
+ return {
99
+ level: 'WARN',
100
+ check: 'contrast',
101
+ ...where,
102
+ detail: `${shown} on its own background passes only as large text, and font-size ${decl['font-size']} depends on the parent — measure the rendered size`,
103
+ };
104
+ }
105
+ if (own && ratio < needed) {
106
+ return {
107
+ level: 'FAIL',
108
+ check: 'contrast',
109
+ ...where,
110
+ detail: `${shown} on its own background, needs ${needed}:1${largeNote}`,
111
+ };
112
+ }
113
+ if (ratio < needed) {
114
+ return {
115
+ level: 'WARN',
116
+ check: 'contrast',
117
+ ...where,
118
+ detail: `${shown} against the page background, needs ${needed}:1 — measure against the real parent`,
119
+ };
120
+ }
121
+ const lc = Math.abs(apcaLc(pair));
122
+ const apcaMin = size === 'large' ? LARGE_APCA : NORMAL_APCA;
123
+ if (lc >= apcaMin) return null;
124
+ return {
125
+ level: 'WARN',
126
+ check: 'apca',
127
+ ...where,
128
+ detail: `Lc ${lc.toFixed(0)}, color.md minimum Lc ${apcaMin}${largeNote}`,
129
+ };
130
+ }
131
+
132
+ /**
133
+ * @param {{rules: readonly Rule[], vars: Readonly<Record<string, string>>, uncertain: ReadonlySet<string>, page: Page, rootPx: number}} params
134
+ * @returns {readonly Finding[]}
135
+ */
136
+ export function checkContrast({rules, vars, uncertain, page, rootPx}) {
137
+ return rules.flatMap(rule => {
138
+ const finding = contrastFinding({rule, vars, uncertain, page, rootPx});
139
+ return finding ? [finding] : [];
140
+ });
141
+ }