@ankhorage/rules-design 0.2.2 → 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,17 @@
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
+
9
+ ## 0.3.0
10
+
11
+ ### Minor Changes
12
+
13
+ - c1bd0c9: Support normalized versioned facts for Typography and Heading rule evaluation.
14
+
3
15
  ## 0.2.2
4
16
 
5
17
  ### Patch 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.2.2](././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
+ }
@@ -0,0 +1,18 @@
1
+ import type { TypographyObservation } from '../../types/typography';
2
+ /*** Creates the shared completeness and viewport grouping operations for Typography evidence. */
3
+ export declare function createTypographyObservationTools(): {
4
+ measurementsComplete: typeof measurementsComplete;
5
+ orderedHeadings: typeof orderedHeadings;
6
+ viewports: typeof viewports;
7
+ };
8
+ type TypographyMeasurement = keyof TypographyObservation;
9
+ /*** Checks required measurements and document-order uniqueness when a rule needs it. */
10
+ declare function measurementsComplete(observations: readonly TypographyObservation[], measurements: readonly TypographyMeasurement[]): boolean;
11
+ /*** Groups observations by responsive viewport so rendered variants remain independent. */
12
+ declare function viewports(observations: readonly TypographyObservation[]): readonly (readonly TypographyObservation[])[];
13
+ /*** Sorts complete heading observations by explicit document order. */
14
+ declare function orderedHeadings(observations: readonly TypographyObservation[]): readonly (TypographyObservation & {
15
+ readonly documentOrder: number;
16
+ readonly headingLevel: number;
17
+ })[];
18
+ export {};
@@ -0,0 +1,53 @@
1
+ /*** Creates the shared completeness and viewport grouping operations for Typography evidence. */
2
+ export function createTypographyObservationTools() {
3
+ return { measurementsComplete, orderedHeadings, viewports };
4
+ }
5
+ /*** Checks required measurements and document-order uniqueness when a rule needs it. */
6
+ function measurementsComplete(observations, measurements) {
7
+ return (observations.every((observation) => measurements.every((measurement) => measurementAvailable(observation, measurement))) &&
8
+ (!measurements.includes('documentOrder') ||
9
+ viewports(observations).every((viewport) => uniqueDocumentOrder(viewport))));
10
+ }
11
+ /*** Checks one named observation measurement without indexing dynamic external property names. */
12
+ function measurementAvailable(observation, measurement) {
13
+ switch (measurement) {
14
+ case 'documentOrder':
15
+ return observation.documentOrder !== null;
16
+ case 'headingLevel':
17
+ return observation.headingLevel !== null;
18
+ case 'marginAfter':
19
+ return observation.marginAfter !== null;
20
+ case 'marginBefore':
21
+ return observation.marginBefore !== null;
22
+ case 'paragraphMeasure':
23
+ return observation.paragraphMeasure !== null;
24
+ case 'responsiveRole':
25
+ return observation.responsiveRole !== null;
26
+ case 'semanticStyle':
27
+ return observation.semanticStyle !== null;
28
+ case 'textClipped':
29
+ return observation.textClipped !== null;
30
+ default:
31
+ return true;
32
+ }
33
+ }
34
+ /*** Groups observations by responsive viewport so rendered variants remain independent. */
35
+ function viewports(observations) {
36
+ return Object.values(Object.groupBy(observations, (observation) => observation.viewport)).flatMap((viewport) => (viewport === undefined ? [] : [viewport]));
37
+ }
38
+ /*** Confirms that every heading in one viewport has a distinct document position. */
39
+ function uniqueDocumentOrder(observations) {
40
+ const documentOrders = observations.map((observation) => observation.documentOrder);
41
+ return (documentOrders.every((order) => order !== null) &&
42
+ new Set(documentOrders).size === documentOrders.length);
43
+ }
44
+ /*** Sorts complete heading observations by explicit document order. */
45
+ function orderedHeadings(observations) {
46
+ return observations
47
+ .filter(hasDocumentOrderAndHeadingLevel)
48
+ .toSorted((left, right) => left.documentOrder - right.documentOrder);
49
+ }
50
+ /*** Confirms that an observation can participate in a document heading hierarchy. */
51
+ function hasDocumentOrderAndHeadingLevel(observation) {
52
+ return observation.documentOrder !== null && observation.headingLevel !== null;
53
+ }
@@ -0,0 +1,6 @@
1
+ import type { RuleSet } from '@ankhorage/rules';
2
+ import type { DesignContext } from '../../types/designRuleProvider';
3
+ import type { TypographyRulePolicy } from '../../types/typography';
4
+ export type { TypographyRulePolicy } from '../../types/typography';
5
+ /*** Creates the independent Typography and Heading RuleSet from explicit serialized-fact policy. */
6
+ export declare function createTypographyRuleSet(policy: TypographyRulePolicy): RuleSet<DesignContext>;
@@ -0,0 +1,114 @@
1
+ import { createTypographyObservationTools } from './createTypographyObservationTools';
2
+ import { parseTypographyObservation } from './parseTypographyObservation';
3
+ import { validateTypographyRulePolicy } from './validateTypographyRulePolicy';
4
+ const typographyObservationTools = createTypographyObservationTools();
5
+ /*** Creates the independent Typography and Heading RuleSet from explicit serialized-fact policy. */
6
+ export function createTypographyRuleSet(policy) {
7
+ validateTypographyRulePolicy(policy);
8
+ return {
9
+ id: 'ankhorage.rules-design.typography',
10
+ rules: ruleDefinitions.map((definition) => createRule(definition, policy)),
11
+ };
12
+ }
13
+ const ruleDefinitions = [
14
+ definition('design.typography.font-family', 'Typography uses configured font families.', (facts, policy) => facts.filter((fact) => !policy.allowedFontFamilies.includes(fact.fontFamily)), requiredMeasurements('fontFamily')),
15
+ definition('design.typography.scale', 'Typography sizes use the configured scale.', (facts, policy) => facts.filter((fact) => !policy.allowedFontSizes.includes(fact.fontSize)), requiredMeasurements('fontSize')),
16
+ definition('design.typography.weight', 'Typography uses configured font weights.', (facts, policy) => facts.filter((fact) => !policy.allowedFontWeights.includes(fact.fontWeight)), requiredMeasurements('fontWeight')),
17
+ definition('design.typography.line-height', 'Typography uses configured line heights.', (facts, policy) => facts.filter((fact) => !policy.allowedLineHeights.includes(fact.lineHeight)), requiredMeasurements('lineHeight')),
18
+ definition('design.typography.letter-spacing', 'Typography uses configured letter spacing.', (facts, policy) => facts.filter((fact) => !policy.allowedLetterSpacings.includes(fact.letterSpacing)), requiredMeasurements('letterSpacing')),
19
+ definition('design.typography.paragraph-measure', 'Paragraphs stay within the configured readable measure.', (facts, policy) => facts.filter((fact) => fact.paragraphMeasure !== null &&
20
+ (fact.paragraphMeasure < policy.minimumParagraphMeasure ||
21
+ fact.paragraphMeasure > policy.maximumParagraphMeasure)), requiredMeasurements('paragraphMeasure'), 'warning'),
22
+ definition('design.typography.body-minimum', 'Body text meets the configured minimum font size.', (facts, policy) => facts.filter((fact) => fact.headingLevel === null && fact.fontSize < policy.minimumBodyFontSize), () => true),
23
+ definition('design.typography.responsive-scale', 'Responsive text sizes follow the configured scale for their role.', (facts, policy) => facts.filter((fact) => fact.responsiveRole !== null &&
24
+ !configuredValues(policy.responsiveFontSizes, fact.responsiveRole).includes(fact.fontSize)), requiredMeasurements('responsiveRole', 'fontSize')),
25
+ definition('design.heading.h1-presence', 'A page contains the configured minimum number of H1 headings.', (facts, policy) => typographyObservationTools
26
+ .viewports(facts)
27
+ .flatMap((factsForViewport) => factsForViewport.filter((fact) => fact.headingLevel === 1).length < policy.minimumH1Count
28
+ ? factsForViewport.slice(0, 1)
29
+ : []), requiredMeasurements('headingLevel', 'viewport'), 'error', 'design.heading-facts'),
30
+ definition('design.heading.h1-count', 'A page does not exceed the configured number of H1 headings.', (facts, policy) => typographyObservationTools.viewports(facts).flatMap((factsForViewport) => {
31
+ const h1Headings = typographyObservationTools
32
+ .orderedHeadings(factsForViewport)
33
+ .filter((fact) => fact.headingLevel === 1);
34
+ return h1Headings.slice(policy.maximumH1Count);
35
+ }), requiredMeasurements('documentOrder', 'headingLevel', 'viewport'), 'error', 'design.heading-facts'),
36
+ definition('design.heading.level-order', 'Heading levels do not skip hierarchy levels.', (facts) => typographyObservationTools
37
+ .viewports(facts)
38
+ .flatMap((factsForViewport) => typographyObservationTools
39
+ .orderedHeadings(factsForViewport)
40
+ .filter((fact, index, ordered) => index > 0 && fact.headingLevel > (ordered[index - 1]?.headingLevel ?? 0) + 1)), requiredMeasurements('documentOrder', 'headingLevel'), 'error', 'design.heading-facts'),
41
+ definition('design.heading.semantic-style', 'Heading semantics use a configured visual style.', (facts, policy) => facts.filter((fact) => fact.semanticStyle !== null &&
42
+ !configuredValues(policy.allowedSemanticStyles, `h${fact.headingLevel}`).includes(fact.semanticStyle)), requiredMeasurements('headingLevel', 'semanticStyle'), 'error', 'design.heading-facts'),
43
+ definition('design.heading.spacing-before', 'Headings use configured preceding spacing.', (facts, policy) => facts.filter((fact) => fact.marginBefore !== null && !policy.allowedSpacingBefore.includes(fact.marginBefore)), requiredMeasurements('headingLevel', 'marginBefore'), 'error', 'design.heading-facts'),
44
+ definition('design.heading.spacing-after', 'Headings use configured following spacing.', (facts, policy) => facts.filter((fact) => fact.marginAfter !== null && !policy.allowedSpacingAfter.includes(fact.marginAfter)), requiredMeasurements('headingLevel', 'marginAfter'), 'error', 'design.heading-facts'),
45
+ definition('design.heading.text-clipping', 'Heading text is not clipped in the rendered layout.', (facts) => facts.filter((fact) => fact.textClipped === true), requiredMeasurements('headingLevel', 'textClipped'), 'error', 'design.heading-facts'),
46
+ ];
47
+ /*** Builds one pure generic Rules rule from a Typography fact predicate. */
48
+ function createRule(definition, policy) {
49
+ return {
50
+ defaultSeverity: definition.severity,
51
+ dependencies: [],
52
+ evaluate: ({ context, scope }) => {
53
+ const [complete, observations] = typographyEvidence(context, definition.capability, scope);
54
+ if (!complete || observations.length === 0 || !definition.measurementsComplete(observations))
55
+ return incomplete(definition.id);
56
+ const violations = definition.evaluate(observations, policy);
57
+ return violations.length === 0
58
+ ? { findings: [], status: 'PASS' }
59
+ : {
60
+ findings: violations.map((fact) => violationFinding(definition.id, fact)),
61
+ status: 'FAIL',
62
+ };
63
+ },
64
+ identity: { id: definition.id, version: '1.0.0' },
65
+ requiredCapabilities: [definition.capability],
66
+ summary: definition.summary,
67
+ };
68
+ }
69
+ /*** Creates a Typography rule definition with its capability inferred from its stable ID. */
70
+ function definition(id, summary, evaluate, measurementsComplete, severity = 'error', capability = 'design.typography-facts') {
71
+ return { capability, evaluate, id, measurementsComplete, severity, summary };
72
+ }
73
+ /*** Reads scoped Typography facts without discarding malformed or unavailable evidence. */
74
+ function typographyEvidence(context, capability, scope) {
75
+ const factObservations = (context.facts ?? [])
76
+ .filter((fact) => fact.kind === capability && fact.scope.id === scope.id && fact.scope.kind === scope.kind)
77
+ .map((fact) => fact.status === 'available' ? parseTypographyObservation(fact.value, fact.id) : []);
78
+ return [
79
+ factObservations.every((observations) => observations.length > 0),
80
+ factObservations.flat(),
81
+ ];
82
+ }
83
+ /*** Returns an explicit incomplete outcome when required measurements cannot support a verdict. */
84
+ function incomplete(ruleId) {
85
+ return { findings: [missingEvidenceFinding(ruleId)], status: 'INCOMPLETE' };
86
+ }
87
+ /*** Produces a serializable incomplete finding when a rule has no valid measured observation. */
88
+ function missingEvidenceFinding(ruleId) {
89
+ return {
90
+ evidence: { reason: 'No valid normalized Typography observation was supplied.' },
91
+ message: `Rule "${ruleId}" is incomplete because Typography evidence is missing.`,
92
+ ruleId,
93
+ severity: 'info',
94
+ subjects: [{ id: 'design-context', kind: 'design-context' }],
95
+ };
96
+ }
97
+ /*** Produces a serializable finding for one measured Typography policy violation. */
98
+ function violationFinding(ruleId, fact) {
99
+ return {
100
+ evidence: { observationId: fact.id, viewport: fact.viewport },
101
+ message: `Rule "${ruleId}" is violated by Typography observation "${fact.id}".`,
102
+ ruleId,
103
+ severity: 'error',
104
+ subjects: [{ id: fact.id, kind: 'typography-observation' }],
105
+ };
106
+ }
107
+ /*** Reads a configured allow-list without treating an unknown role as allowed. */
108
+ function configuredValues(values, key) {
109
+ return Object.entries(values).find(([candidate]) => candidate === key)?.[1] ?? [];
110
+ }
111
+ /*** Builds a completeness predicate from one frozen rule's required measurements. */
112
+ function requiredMeasurements(...keys) {
113
+ return (observations) => typographyObservationTools.measurementsComplete(observations, keys);
114
+ }
@@ -0,0 +1,3 @@
1
+ import type { TypographyObservation } from '../../types/typography';
2
+ /*** Parses one available serialized fact into a normalized Typography observation. */
3
+ export declare function parseTypographyObservation(value: unknown, id: string): readonly TypographyObservation[];
@@ -0,0 +1,62 @@
1
+ import { isRecord } from '@ankhorage/utility/object';
2
+ /*** Parses one available serialized fact into a normalized Typography observation. */
3
+ export function parseTypographyObservation(value, id) {
4
+ if (!isRecord(value) ||
5
+ !isString(value.fontFamily) ||
6
+ !isNumber(value.fontSize) ||
7
+ !isString(value.fontWeight) ||
8
+ !isNumber(value.letterSpacing) ||
9
+ !isNumber(value.lineHeight) ||
10
+ !isString(value.viewport))
11
+ return [];
12
+ const headingLevel = nullableHeadingLevel(value.headingLevel);
13
+ if (headingLevel === undefined)
14
+ return [];
15
+ return [
16
+ {
17
+ fontFamily: value.fontFamily,
18
+ fontSize: value.fontSize,
19
+ fontWeight: value.fontWeight,
20
+ documentOrder: nullableNumber(value.documentOrder),
21
+ headingLevel: headingLevel ?? null,
22
+ id,
23
+ letterSpacing: value.letterSpacing,
24
+ lineHeight: value.lineHeight,
25
+ marginAfter: nullableNumber(value.marginAfter),
26
+ marginBefore: nullableNumber(value.marginBefore),
27
+ paragraphMeasure: nullableNumber(value.paragraphMeasure),
28
+ responsiveRole: nullableString(value.responsiveRole),
29
+ semanticStyle: nullableString(value.semanticStyle),
30
+ textClipped: nullableBoolean(value.textClipped),
31
+ viewport: value.viewport,
32
+ },
33
+ ];
34
+ }
35
+ /*** Narrows an unknown serialized value to a finite number. */
36
+ function isNumber(value) {
37
+ return typeof value === 'number' && Number.isFinite(value);
38
+ }
39
+ /*** Narrows an optional serialized value to a nullable boolean. */
40
+ function nullableBoolean(value) {
41
+ return value === undefined || value === null ? null : typeof value === 'boolean' ? value : null;
42
+ }
43
+ /*** Narrows an optional serialized value to a valid nullable heading level. */
44
+ function nullableHeadingLevel(value) {
45
+ return value === undefined || value === null
46
+ ? null
47
+ : isNumber(value) && Number.isInteger(value) && value >= 1 && value <= 6
48
+ ? value
49
+ : undefined;
50
+ }
51
+ /*** Narrows an optional serialized value to a nullable finite number. */
52
+ function nullableNumber(value) {
53
+ return value === undefined || value === null ? null : isNumber(value) ? value : null;
54
+ }
55
+ /*** Narrows an optional serialized value to a nullable string. */
56
+ function nullableString(value) {
57
+ return value === undefined || value === null ? null : isString(value) ? value : null;
58
+ }
59
+ /*** Narrows an unknown serialized value to a string. */
60
+ function isString(value) {
61
+ return typeof value === 'string';
62
+ }
@@ -0,0 +1,3 @@
1
+ import type { TypographyRulePolicy } from '../../types/typography';
2
+ /*** Rejects malformed policy before rule construction can produce ambiguous verdicts. */
3
+ export declare function validateTypographyRulePolicy(policy: TypographyRulePolicy): void;
@@ -0,0 +1,68 @@
1
+ /*** Rejects malformed policy before rule construction can produce ambiguous verdicts. */
2
+ export function validateTypographyRulePolicy(policy) {
3
+ if (invalidTypographyRulePolicy(policy)) {
4
+ throw new Error('Typography rule policy must contain complete, internally consistent measurements.');
5
+ }
6
+ }
7
+ /*** Checks every policy invariant required by the Typography rule family. */
8
+ function invalidTypographyRulePolicy(policy) {
9
+ return (!hasNonEmptyStrings(policy.allowedFontFamilies) ||
10
+ !hasPositiveNumbers(policy.allowedFontSizes) ||
11
+ !hasNonEmptyStrings(policy.allowedFontWeights) ||
12
+ !hasFiniteNumbers(policy.allowedLetterSpacings) ||
13
+ !hasPositiveNumbers(policy.allowedLineHeights) ||
14
+ !hasNonNegativeNumbers(policy.allowedSpacingAfter) ||
15
+ !hasNonNegativeNumbers(policy.allowedSpacingBefore) ||
16
+ !hasConfiguredValues(policy.allowedSemanticStyles, hasNonEmptyStrings) ||
17
+ !hasConfiguredValues(policy.responsiveFontSizes, hasPositiveNumbers) ||
18
+ !hasValidH1Counts(policy) ||
19
+ !hasValidTypographyThresholds(policy));
20
+ }
21
+ /*** Checks that H1 count bounds are non-negative integers in ascending order. */
22
+ function hasValidH1Counts(policy) {
23
+ return (Number.isInteger(policy.minimumH1Count) &&
24
+ Number.isInteger(policy.maximumH1Count) &&
25
+ policy.minimumH1Count >= 0 &&
26
+ policy.maximumH1Count >= policy.minimumH1Count);
27
+ }
28
+ /*** Checks positive Typography thresholds and paragraph-measure bounds. */
29
+ function hasValidTypographyThresholds(policy) {
30
+ return (isPositiveFiniteNumber(policy.minimumBodyFontSize) &&
31
+ isPositiveFiniteNumber(policy.minimumParagraphMeasure) &&
32
+ isPositiveFiniteNumber(policy.maximumParagraphMeasure) &&
33
+ policy.maximumParagraphMeasure >= policy.minimumParagraphMeasure);
34
+ }
35
+ /*** Checks a non-empty serializable string allow-list. */
36
+ function hasNonEmptyStrings(values) {
37
+ return (Array.isArray(values) &&
38
+ values.length > 0 &&
39
+ values.every((value) => typeof value === 'string' && value.length > 0));
40
+ }
41
+ /*** Checks a non-empty serializable positive numeric allow-list. */
42
+ function hasPositiveNumbers(values) {
43
+ return Array.isArray(values) && values.length > 0 && values.every(isPositiveFiniteNumber);
44
+ }
45
+ /*** Checks a non-empty serializable finite numeric allow-list. */
46
+ function hasFiniteNumbers(values) {
47
+ return (Array.isArray(values) &&
48
+ values.length > 0 &&
49
+ values.every((value) => typeof value === 'number' && Number.isFinite(value)));
50
+ }
51
+ /*** Checks a non-empty serializable non-negative numeric allow-list. */
52
+ function hasNonNegativeNumbers(values) {
53
+ return (Array.isArray(values) &&
54
+ values.length > 0 &&
55
+ values.every((value) => typeof value === 'number' && Number.isFinite(value) && value >= 0));
56
+ }
57
+ /*** Checks a finite positive measurement. */
58
+ function isPositiveFiniteNumber(value) {
59
+ return typeof value === 'number' && Number.isFinite(value) && value > 0;
60
+ }
61
+ /*** Checks every named policy role supplies a non-empty valid allow-list. */
62
+ function hasConfiguredValues(values, validate) {
63
+ return (typeof values === 'object' &&
64
+ values !== null &&
65
+ !Array.isArray(values) &&
66
+ Object.keys(values).length > 0 &&
67
+ Object.entries(values).every(([key, value]) => key.length > 0 && validate(value)));
68
+ }
@@ -1,3 +1,4 @@
1
+ import type { FactEnvelope } from '@ankhorage/contracts/rules';
1
2
  import type { RuleSet } from '@ankhorage/rules';
2
3
  /*** One provider-neutral design observation supplied by a Design context. */
3
4
  export interface DesignEvidence {
@@ -7,6 +8,7 @@ export interface DesignEvidence {
7
8
  /*** The minimal context shared by Design rules without prescribing its source. */
8
9
  export interface DesignContext {
9
10
  readonly evidence: readonly DesignEvidence[];
11
+ readonly facts?: readonly FactEnvelope[];
10
12
  }
11
13
  /*** The public identity and generic Rules contribution for the Design provider. */
12
14
  export interface DesignRuleProvider {
@@ -0,0 +1,35 @@
1
+ /** One normalized, provider-neutral rendered Typography observation. */
2
+ export interface TypographyObservation {
3
+ readonly documentOrder: number | null;
4
+ readonly fontFamily: string;
5
+ readonly fontSize: number;
6
+ readonly fontWeight: string;
7
+ readonly headingLevel: number | null;
8
+ readonly id: string;
9
+ readonly letterSpacing: number;
10
+ readonly lineHeight: number;
11
+ readonly marginAfter: number | null;
12
+ readonly marginBefore: number | null;
13
+ readonly paragraphMeasure: number | null;
14
+ readonly responsiveRole: string | null;
15
+ readonly semanticStyle: string | null;
16
+ readonly textClipped: boolean | null;
17
+ readonly viewport: string;
18
+ }
19
+ /** Explicit allow-lists and thresholds used to evaluate Typography observations. */
20
+ export interface TypographyRulePolicy {
21
+ readonly allowedFontFamilies: readonly string[];
22
+ readonly allowedFontSizes: readonly number[];
23
+ readonly allowedFontWeights: readonly string[];
24
+ readonly allowedLetterSpacings: readonly number[];
25
+ readonly allowedLineHeights: readonly number[];
26
+ readonly allowedSemanticStyles: Readonly<Record<string, readonly string[]>>;
27
+ readonly allowedSpacingAfter: readonly number[];
28
+ readonly allowedSpacingBefore: readonly number[];
29
+ readonly maximumH1Count: number;
30
+ readonly maximumParagraphMeasure: number;
31
+ readonly minimumBodyFontSize: number;
32
+ readonly minimumH1Count: number;
33
+ readonly minimumParagraphMeasure: number;
34
+ readonly responsiveFontSizes: Readonly<Record<string, readonly number[]>>;
35
+ }
File without changes
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ankhorage/rules-design",
3
- "version": "0.2.2",
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",