@ankhorage/rules-design 0.3.0 → 0.3.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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,11 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.3.1
4
+
5
+ ### Patch Changes
6
+
7
+ - d715c7a: Fix Contrast rule evaluation to apply canonical standards to observed facts.
8
+
3
9
  ## 0.3.0
4
10
 
5
11
  ### Minor Changes
package/README.md CHANGED
@@ -3,7 +3,7 @@
3
3
 
4
4
  # @ankhorage/rules-design
5
5
 
6
- ![license: MIT](././paradox/badges/license.svg) ![npm: v0.3.0](././paradox/badges/npm.svg) ![runtime: bun](././paradox/badges/runtime.svg) ![typescript: strict](././paradox/badges/typescript.svg) ![eslint: checked](././paradox/badges/eslint.svg) ![prettier: checked](././paradox/badges/prettier.svg) ![build: checked](././paradox/badges/build.svg) ![tests: checked](././paradox/badges/tests.svg) ![paradox: canonical](././paradox/badges/docs.svg)
6
+ ![license: MIT](././paradox/badges/license.svg) ![npm: v0.3.1](././paradox/badges/npm.svg) ![runtime: bun](././paradox/badges/runtime.svg) ![typescript: strict](././paradox/badges/typescript.svg) ![eslint: checked](././paradox/badges/eslint.svg) ![prettier: checked](././paradox/badges/prettier.svg) ![build: checked](././paradox/badges/build.svg) ![tests: checked](././paradox/badges/tests.svg) ![paradox: canonical](././paradox/badges/docs.svg)
7
7
 
8
8
  Declarative catalog for reusable design rules.
9
9
 
@@ -0,0 +1,8 @@
1
+ import type { FactEnvelope } from '@ankhorage/contracts/rules';
2
+ import type { Rule } from '@ankhorage/rules';
3
+ interface Context {
4
+ readonly facts: readonly FactEnvelope[];
5
+ }
6
+ /*** Creates the independent Contrast and Visual Hierarchy rule contribution without central registration. */
7
+ export declare function createContrastRules(): readonly Rule<Context>[];
8
+ export {};
@@ -0,0 +1,225 @@
1
+ import { isRecord } from '@ankhorage/utility/object';
2
+ import { hasValidContrastMeasurement } from './hasValidContrastMeasurement';
3
+ const definitions = [
4
+ {
5
+ id: 'design.contrast.text-ratio',
6
+ requiredCapabilities: ['dom.computed-style', 'dom.text-content'],
7
+ severity: 'error',
8
+ summary: 'Require observed effective text contrast to meet the selected WCAG standard.',
9
+ },
10
+ {
11
+ id: 'design.contrast.nontext-ratio',
12
+ requiredCapabilities: ['dom.computed-style'],
13
+ severity: 'error',
14
+ summary: 'Require observed non-text contrast to meet WCAG AA.',
15
+ },
16
+ {
17
+ id: 'design.contrast.focus-visible',
18
+ requiredCapabilities: ['dom.computed-style', 'browser.interaction-state'],
19
+ severity: 'error',
20
+ summary: 'Require a visible focus indicator with sufficient contrast.',
21
+ },
22
+ {
23
+ id: 'design.contrast.surface-separation',
24
+ requiredCapabilities: ['dom.computed-style'],
25
+ severity: 'error',
26
+ summary: 'Require adjacent effective surfaces to remain distinguishable.',
27
+ },
28
+ {
29
+ id: 'design.contrast.state-distinction',
30
+ requiredCapabilities: ['dom.computed-style', 'browser.interaction-state'],
31
+ severity: 'error',
32
+ summary: 'Require observed interactive states to remain distinct.',
33
+ },
34
+ {
35
+ id: 'design.contrast.link-distinction',
36
+ requiredCapabilities: ['dom.computed-style'],
37
+ severity: 'error',
38
+ summary: 'Require links to have a non-color cue or sufficient distinction.',
39
+ },
40
+ {
41
+ id: 'design.contrast.text-background-resolved',
42
+ requiredCapabilities: ['dom.computed-style'],
43
+ severity: 'error',
44
+ summary: 'Require an observed effective text background.',
45
+ },
46
+ {
47
+ id: 'design.contrast.cta-prominence',
48
+ requiredCapabilities: ['dom.computed-style'],
49
+ severity: 'warning',
50
+ summary: 'Require a primary CTA to exceed competing visual prominence.',
51
+ },
52
+ {
53
+ id: 'design.contrast.visual-hierarchy',
54
+ requiredCapabilities: ['dom.computed-style'],
55
+ severity: 'warning',
56
+ summary: 'Require observed visual emphasis to descend through a hierarchy.',
57
+ },
58
+ ];
59
+ /*** Creates the independent Contrast and Visual Hierarchy rule contribution without central registration. */
60
+ export function createContrastRules() {
61
+ return definitions.map(createRule);
62
+ }
63
+ /*** Creates one frozen rule whose policy is controlled by validated options or canonical standards. */
64
+ function createRule(definition) {
65
+ return {
66
+ defaultSeverity: definition.severity,
67
+ dependencies: [],
68
+ identity: { id: definition.id, version: '1.0.0' },
69
+ requiredCapabilities: definition.requiredCapabilities,
70
+ summary: definition.summary,
71
+ validateOptions: (options) => validateOptions(definition.id, options),
72
+ evaluate: ({ context, options, scope }) => evaluate(definition, context.facts, options, scope),
73
+ };
74
+ }
75
+ /*** Evaluates exact-scope observations, rejecting absent, malformed, and self-judging evidence. */
76
+ function evaluate(definition, facts, options, scope) {
77
+ const standard = standardFor(definition.id, options);
78
+ const scoped = facts.filter((fact) => matchesRuleScope(fact, definition.id, scope));
79
+ if (scoped.length === 0)
80
+ return incomplete(definition.id, scope);
81
+ const observations = scoped.flatMap((fact) => toContrastObservation(fact, definition.id));
82
+ if (observations.length !== scoped.length)
83
+ return incomplete(definition.id, scope);
84
+ const failures = observations.filter((observation) => !passes(definition.id, observation.value, standard));
85
+ return failures.length === 0
86
+ ? { findings: [], status: 'PASS' }
87
+ : {
88
+ findings: failures.map((observation) => failure(definition, standard, observation)),
89
+ status: 'FAIL',
90
+ };
91
+ }
92
+ /*** Selects only facts whose producer-declared kind identifies this exact frozen rule and scope. */
93
+ function matchesRuleScope(fact, id, scope) {
94
+ return fact.kind === id && fact.scope.id === scope.id && fact.scope.kind === scope.kind;
95
+ }
96
+ /*** Validates a closed versioned standard choice rather than arbitrary numeric acceptance criteria. */
97
+ function validateOptions(id, options) {
98
+ return options === undefined ||
99
+ (isRecord(options) &&
100
+ options.version === 1 &&
101
+ typeof options.standard === 'string' &&
102
+ supportsStandard(id, options.standard) &&
103
+ Object.keys(options).every((key) => key === 'version' || key === 'standard'))
104
+ ? []
105
+ : [
106
+ {
107
+ code: 'invalid-contrast-options',
108
+ message: 'Options must contain version 1 and a standard.',
109
+ },
110
+ ];
111
+ }
112
+ /*** Confines each frozen rule to the standards its policy can evaluate. */
113
+ function supportsStandard(id, standard) {
114
+ if (id === 'design.contrast.text-ratio')
115
+ return ['wcag-aa-large', 'wcag-aa-normal', 'wcag-aaa-large', 'wcag-aaa-normal'].includes(standard);
116
+ if (id === 'design.contrast.cta-prominence' || id === 'design.contrast.visual-hierarchy')
117
+ return ['heuristic-clear', 'heuristic-strong'].includes(standard);
118
+ if (id === 'design.contrast.text-background-resolved')
119
+ return standard === 'heuristic-clear';
120
+ return standard === 'wcag-aa-nontext';
121
+ }
122
+ /*** Resolves a canonical or validated standard owned by the rule rather than its fact envelope. */
123
+ function standardFor(id, options) {
124
+ const selected = isRecord(options) && typeof options.standard === 'string' ? options.standard : undefined;
125
+ if (id === 'design.contrast.text-ratio') {
126
+ return ['wcag-aa-large', 'wcag-aa-normal', 'wcag-aaa-large', 'wcag-aaa-normal'].includes(selected ?? '')
127
+ ? (selected ?? 'wcag-aa-normal')
128
+ : 'wcag-aa-normal';
129
+ }
130
+ return id === 'design.contrast.cta-prominence' || id === 'design.contrast.visual-hierarchy'
131
+ ? selected === 'heuristic-strong'
132
+ ? selected
133
+ : 'heuristic-clear'
134
+ : id === 'design.contrast.text-background-resolved'
135
+ ? 'heuristic-clear'
136
+ : 'wcag-aa-nontext';
137
+ }
138
+ /*** Converts one available contrast fact into a fully validated rule observation. */
139
+ function toContrastObservation(fact, id) {
140
+ if (fact.status !== 'available' || !valid(fact.value, id))
141
+ return [];
142
+ return [{ subject: fact.value.subject, value: fact.value }];
143
+ }
144
+ /*** Validates rule-specific observations and forbids evidence-provided comparisons or thresholds. */
145
+ function valid(value, id) {
146
+ return isBaseObservation(value, id) && hasValidContrastMeasurement(id, value);
147
+ }
148
+ /*** Verifies the evidence fields shared by every Contrast observation. */
149
+ function isBaseObservation(value, id) {
150
+ return (isRecord(value) &&
151
+ value.ruleId === id &&
152
+ isRuleSubject(value.subject) &&
153
+ !['comparison', 'expected', 'minimum', 'operator', 'threshold'].some((key) => key in value));
154
+ }
155
+ /*** Applies the rule-owned semantic standard to one complete observation. */
156
+ function passes(id, value, standard) {
157
+ if (id === 'design.contrast.text-background-resolved')
158
+ return true;
159
+ if (id === 'design.contrast.cta-prominence')
160
+ return (Number(value.primaryProminence) - Number(value.competingProminence) >=
161
+ (standard === 'heuristic-strong' ? 0.2 : 0.1));
162
+ if (id === 'design.contrast.visual-hierarchy') {
163
+ const { emphasis } = value;
164
+ if (!isJsonValueArray(emphasis) || emphasis.length < 2)
165
+ return false;
166
+ return emphasis.slice(1).every((entry, index) => {
167
+ const previous = emphasis.at(index);
168
+ return (isScore(entry) &&
169
+ isScore(previous) &&
170
+ previous.score - entry.score >= (standard === 'heuristic-strong' ? 0.2 : 0.1));
171
+ });
172
+ }
173
+ if (id === 'design.contrast.link-distinction')
174
+ return value.nonColorCueVisible === true || Number(value.distinguishingContrastRatio) >= 3;
175
+ if (id === 'design.contrast.focus-visible')
176
+ return value.focusIndicatorVisible === true && Number(value.contrastRatio) >= 3;
177
+ return (Number(value.contrastRatio) >=
178
+ (standard === 'wcag-aaa-normal'
179
+ ? 7
180
+ : standard === 'wcag-aa-large' || standard === 'wcag-aa-nontext'
181
+ ? 3
182
+ : 4.5));
183
+ }
184
+ /*** Produces an incomplete result when evidence cannot prove this exact-scope rule. */
185
+ function incomplete(id, scope) {
186
+ return {
187
+ findings: [
188
+ {
189
+ evidence: { scopeId: scope.id, scopeKind: scope.kind },
190
+ message: `Rule "${id}" is incomplete for scope "${scope.kind}:${scope.id}".`,
191
+ ruleId: id,
192
+ severity: 'info',
193
+ subjects: [{ id: scope.id, kind: scope.kind }],
194
+ },
195
+ ],
196
+ status: 'INCOMPLETE',
197
+ };
198
+ }
199
+ /*** Retains observed evidence and the applied canonical standard for a failed rule. */
200
+ function failure(definition, standard, observation) {
201
+ return {
202
+ evidence: { observation: observation.value, standard },
203
+ message: `Observed ${definition.id} evidence does not meet the ${standard} standard.`,
204
+ ruleId: definition.id,
205
+ severity: definition.severity,
206
+ subjects: [observation.subject],
207
+ };
208
+ }
209
+ /*** Narrows a serializable subject to the Rules finding contract. */
210
+ function isRuleSubject(value) {
211
+ return (isRecord(value) &&
212
+ typeof value.id === 'string' &&
213
+ value.id.length > 0 &&
214
+ typeof value.kind === 'string' &&
215
+ value.kind.length > 0 &&
216
+ (value.path === undefined || (typeof value.path === 'string' && value.path.length > 0)));
217
+ }
218
+ /*** Narrows a JSON value to an immutable sequence of JSON values. */
219
+ function isJsonValueArray(value) {
220
+ return Array.isArray(value);
221
+ }
222
+ /*** Narrows a hierarchy entry to a finite observed emphasis score. */
223
+ function isScore(value) {
224
+ return isRecord(value) && typeof value.score === 'number' && Number.isFinite(value.score);
225
+ }
@@ -0,0 +1,3 @@
1
+ import type { JsonValue } from '@ankhorage/rules';
2
+ /*** Verifies the complete observation shape required by one frozen Contrast rule. */
3
+ export declare function hasValidContrastMeasurement(id: string, value: Readonly<Record<string, JsonValue>>): boolean;
@@ -0,0 +1,66 @@
1
+ import { isRecord } from '@ankhorage/utility/object';
2
+ /*** Verifies the complete observation shape required by one frozen Contrast rule. */
3
+ export function hasValidContrastMeasurement(id, value) {
4
+ const validator = measurementValidators.get(id);
5
+ return validator?.(value) === true;
6
+ }
7
+ const measurementValidators = new Map([
8
+ [
9
+ 'design.contrast.cta-prominence',
10
+ (value) => number(value.primaryProminence) && number(value.competingProminence),
11
+ ],
12
+ [
13
+ 'design.contrast.focus-visible',
14
+ (value) => number(value.contrastRatio) &&
15
+ typeof value.focusIndicatorVisible === 'boolean' &&
16
+ text(value.effectiveBackground),
17
+ ],
18
+ [
19
+ 'design.contrast.link-distinction',
20
+ (value) => number(value.distinguishingContrastRatio) && typeof value.nonColorCueVisible === 'boolean',
21
+ ],
22
+ ['design.contrast.nontext-ratio', hasColorRatio],
23
+ [
24
+ 'design.contrast.state-distinction',
25
+ (value) => number(value.contrastRatio) &&
26
+ text(value.state) &&
27
+ text(value.comparedState) &&
28
+ value.state !== value.comparedState,
29
+ ],
30
+ [
31
+ 'design.contrast.surface-separation',
32
+ (value) => number(value.contrastRatio) &&
33
+ text(value.firstEffectiveBackground) &&
34
+ text(value.secondEffectiveBackground),
35
+ ],
36
+ [
37
+ 'design.contrast.text-background-resolved',
38
+ (value) => text(value.effectiveBackground) &&
39
+ Number.isInteger(value.backgroundLayerCount) &&
40
+ Number(value.backgroundLayerCount) > 0,
41
+ ],
42
+ ['design.contrast.text-ratio', hasColorRatio],
43
+ ['design.contrast.visual-hierarchy', (value) => isEmphasis(value.emphasis)],
44
+ ]);
45
+ /*** Validates a complete foreground-to-effective-background contrast measurement. */
46
+ function hasColorRatio(value) {
47
+ return number(value.contrastRatio) && text(value.effectiveBackground) && text(value.foreground);
48
+ }
49
+ /*** Narrows ordered hierarchy entries to finite observed emphasis scores. */
50
+ function isEmphasis(value) {
51
+ return (isJsonValueArray(value) &&
52
+ value.length > 1 &&
53
+ value.every((entry) => isRecord(entry) && number(entry.score)));
54
+ }
55
+ /*** Narrows a JSON value to an immutable sequence of JSON values. */
56
+ function isJsonValueArray(value) {
57
+ return Array.isArray(value);
58
+ }
59
+ /*** Checks finite non-negative numeric observations. */
60
+ function number(value) {
61
+ return typeof value === 'number' && Number.isFinite(value) && value >= 0;
62
+ }
63
+ /*** Checks non-empty textual observations. */
64
+ function text(value) {
65
+ return typeof value === 'string' && value.length > 0;
66
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ankhorage/rules-design",
3
- "version": "0.3.0",
3
+ "version": "0.3.1",
4
4
  "description": "Declarative catalog for reusable design rules.",
5
5
  "license": "MIT",
6
6
  "homepage": "https://github.com/ankhorage/rules-design#readme",