@ankhorage/rules-design 0.2.1 → 0.2.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,11 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.2.2
4
+
5
+ ### Patch Changes
6
+
7
+ - bc8863f: Add the published contracts and utility dependencies required by the alignment rules.
8
+
3
9
  ## 0.2.1
4
10
 
5
11
  ### 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.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)
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)
7
7
 
8
8
  Declarative catalog for reusable design rules.
9
9
 
@@ -0,0 +1,14 @@
1
+ import type { FactEnvelope } from '@ankhorage/contracts/rules';
2
+ import type { Rule } from '@ankhorage/rules';
3
+ /*** Supplies portable layout facts to the Alignment and Layout rule family. */
4
+ export interface AlignmentRuleContext {
5
+ readonly facts: readonly FactEnvelope[];
6
+ }
7
+ type AlignmentRuleId = 'design.alignment.shared-edges' | 'design.alignment.grid-tracks' | 'design.alignment.baselines' | 'design.alignment.text' | 'design.alignment.flex-items' | 'design.alignment.component-axes' | 'design.layout.container-width' | 'design.layout.grid-gap' | 'design.layout.horizontal-overflow' | 'design.layout.vertical-clipping' | 'design.layout.unintended-overlap' | 'design.layout.unnecessary-wrapper' | 'design.layout.visual-balance';
8
+ /*** Configures trusted, group-local acceptance tolerances by frozen Alignment and Layout rule ID. */
9
+ export interface AlignmentRuleOptions {
10
+ readonly tolerances?: Partial<Record<AlignmentRuleId, number>>;
11
+ }
12
+ /*** Creates the independently registrable Alignment and Layout rules without mutating a provider registry. */
13
+ export declare function createAlignmentRules(options?: AlignmentRuleOptions): readonly Rule<AlignmentRuleContext>[];
14
+ export {};
@@ -0,0 +1,151 @@
1
+ import { isRecord } from '@ankhorage/utility/object';
2
+ const definitions = [
3
+ metricRule('design.alignment.shared-edges', 'edge-offset', 'Shared visual edges align.'),
4
+ metricRule('design.alignment.grid-tracks', 'grid-track-offset', 'Elements follow grid tracks.'),
5
+ metricRule('design.alignment.baselines', 'baseline-offset', 'Typical baselines align.'),
6
+ metricRule('design.alignment.text', 'text-alignment-offset', 'Text alignment is intentional and consistent.'),
7
+ metricRule('design.alignment.flex-items', 'flex-alignment-offset', 'Flex alignment follows its defined pattern.'),
8
+ metricRule('design.alignment.component-axes', 'component-axis-offset', 'Equivalent components share axes.'),
9
+ metricRule('design.layout.container-width', 'container-width-deviation', 'Container widths obey configured bounds.'),
10
+ metricRule('design.layout.grid-gap', 'grid-gap-deviation', 'Grid gaps follow the system.'),
11
+ {
12
+ ...metricRule('design.layout.horizontal-overflow', 'horizontal-overflow', 'Unexpected horizontal overflow is absent.'),
13
+ capability: 'viewport.layout',
14
+ criterion: 'horizontal overflow',
15
+ },
16
+ {
17
+ ...metricRule('design.layout.vertical-clipping', 'vertical-clipping', 'Unexpected vertical clipping is absent.'),
18
+ criterion: 'vertical clipping',
19
+ },
20
+ {
21
+ ...metricRule('design.layout.unintended-overlap', 'overlap-area', 'Unexpected overlap is absent.'),
22
+ criterion: 'unintended overlap area',
23
+ },
24
+ {
25
+ ...metricRule('design.layout.unnecessary-wrapper', 'avoidable-wrapper-count', 'Avoidable structural wrappers are identified.'),
26
+ assessment: 'heuristic',
27
+ criterion: 'avoidable wrapper count',
28
+ },
29
+ {
30
+ ...metricRule('design.layout.visual-balance', 'visual-weight-imbalance', 'Visual weight is balanced.'),
31
+ assessment: 'heuristic',
32
+ capability: 'rendered.area-analysis',
33
+ criterion: 'visual weight imbalance',
34
+ tolerance: 0.1,
35
+ },
36
+ ];
37
+ /*** Creates the independently registrable Alignment and Layout rules without mutating a provider registry. */
38
+ export function createAlignmentRules(options = {}) {
39
+ return definitions.map((definition) => createAlignmentRule({ ...definition, tolerance: resolveTolerance(definition, options) }));
40
+ }
41
+ /*** Creates one pure rule from its frozen catalog definition. */
42
+ function createAlignmentRule(definition) {
43
+ return {
44
+ defaultSeverity: definition.assessment === 'objective' ? 'warning' : 'info',
45
+ dependencies: [],
46
+ evaluate: (input) => evaluateAlignmentMetric(definition, input),
47
+ facets: [
48
+ { id: 'assessment', value: definition.assessment },
49
+ { id: 'group', value: 'alignment-layout' },
50
+ { id: 'measurement', value: definition.measurement },
51
+ ],
52
+ identity: { id: definition.id, version: '1.0.0' },
53
+ requiredCapabilities: [definition.capability],
54
+ summary: definition.summary,
55
+ };
56
+ }
57
+ /*** Evaluates the normalized metric for one fact at the exact rule scope. */
58
+ function evaluateAlignmentMetric(definition, input) {
59
+ const metric = findAlignmentMetric(input.context.facts, definition, input.scope);
60
+ if (!metric)
61
+ return incompleteOutcome(definition, input);
62
+ if (metric.observed <= definition.tolerance)
63
+ return { findings: [], status: 'PASS' };
64
+ return { findings: [finding(definition, input, metric)], status: 'FAIL' };
65
+ }
66
+ /*** Finds one unambiguous, valid metric fact at the exact active Rules scope. */
67
+ function findAlignmentMetric(facts, definition, scope) {
68
+ const matchingFacts = facts.filter((fact) => fact.kind === definition.id && scopeMatches(fact.scope, scope));
69
+ const metrics = matchingFacts.map((fact) => fact.status === 'available' ? parseMetric(fact.value, definition.measurement) : undefined);
70
+ const [metric, ...otherMetrics] = metrics;
71
+ if (!metric || otherMetrics.some((otherMetric) => !sameMetric(metric, otherMetric))) {
72
+ return undefined;
73
+ }
74
+ return metric;
75
+ }
76
+ /*** Compares the full Rules scope rather than accepting another scope with the same identifier. */
77
+ function scopeMatches(factScope, scope) {
78
+ return factScope.id === scope.id && factScope.kind === scope.kind;
79
+ }
80
+ /*** Validates the group-local observed geometry payload without trusting adapter acceptance criteria. */
81
+ function parseMetric(value, measurement) {
82
+ if (!isRecord(value))
83
+ return undefined;
84
+ const { measurement: candidateMeasurement, observed, subjectIds } = value;
85
+ if (candidateMeasurement !== measurement ||
86
+ typeof observed !== 'number' ||
87
+ !Number.isFinite(observed) ||
88
+ observed < 0 ||
89
+ !Array.isArray(subjectIds) ||
90
+ subjectIds.length === 0 ||
91
+ !subjectIds.every((id) => typeof id === 'string' && id.trim().length > 0) ||
92
+ new Set(subjectIds).size !== subjectIds.length) {
93
+ return undefined;
94
+ }
95
+ return { measurement, observed, subjectIds };
96
+ }
97
+ /*** Requires duplicate facts to state the same complete normalized observation. */
98
+ function sameMetric(metric, otherMetric) {
99
+ return (otherMetric?.measurement === metric.measurement &&
100
+ metric.observed === otherMetric.observed &&
101
+ metric.subjectIds.length === otherMetric.subjectIds.length &&
102
+ metric.subjectIds.every((subjectId, index) => subjectId === otherMetric.subjectIds.at(index)));
103
+ }
104
+ /*** Produces an explicit incomplete result when an adapter supplied no usable metric. */
105
+ function incompleteOutcome(definition, input) {
106
+ return {
107
+ findings: [
108
+ {
109
+ evidence: { scopeId: input.scope.id },
110
+ message: `${definition.summary} No available normalized metric was supplied for this scope.`,
111
+ ruleId: definition.id,
112
+ severity: 'info',
113
+ subjects: [{ id: input.scope.id, kind: input.scope.kind }],
114
+ },
115
+ ],
116
+ status: 'INCOMPLETE',
117
+ };
118
+ }
119
+ /*** Describes an observation that exceeds this rule's trusted acceptance tolerance. */
120
+ function finding(definition, input, metric) {
121
+ return {
122
+ evidence: {
123
+ observed: metric.observed,
124
+ tolerance: definition.tolerance,
125
+ },
126
+ message: `${definition.summary} Observed ${definition.criterion} ${metric.observed} exceeds tolerance ${definition.tolerance}.`,
127
+ ruleId: definition.id,
128
+ severity: definition.assessment === 'objective' ? 'warning' : 'info',
129
+ subjects: metric.subjectIds.map((id) => ({ id, kind: input.scope.kind })),
130
+ };
131
+ }
132
+ /*** Resolves a trusted policy override and rejects invalid acceptance thresholds at the factory boundary. */
133
+ function resolveTolerance(definition, options) {
134
+ const tolerance = options.tolerances?.[definition.id] ?? definition.tolerance;
135
+ if (!Number.isFinite(tolerance) || tolerance < 0) {
136
+ throw new TypeError(`Tolerance for "${definition.id}" must be a finite non-negative number.`);
137
+ }
138
+ return tolerance;
139
+ }
140
+ /*** Builds one objective layout metric rule definition with a zero-deviation semantic default. */
141
+ function metricRule(id, measurement, summary) {
142
+ return {
143
+ assessment: 'objective',
144
+ capability: 'dom.layout',
145
+ criterion: 'layout deviation',
146
+ id,
147
+ measurement,
148
+ summary,
149
+ tolerance: 0,
150
+ };
151
+ }
@@ -0,0 +1,17 @@
1
+ import type { FactEnvelope } from '@ankhorage/contracts/rules';
2
+ import type { Rule } from '@ankhorage/rules';
3
+ declare const repetitionRuleDefinitions: readonly [readonly ["design.repetition.button-variants", "Button variants are consistent."], readonly ["design.repetition.card-variants", "Card variants and templates are consistent."], readonly ["design.repetition.heading-variants", "Heading roles are consistent."], readonly ["design.repetition.form-control-style", "Form controls are consistently styled."], readonly ["design.repetition.link-treatment", "Link treatment is consistent."], readonly ["design.repetition.navigation-treatment", "Navigation treatment is consistent."], readonly ["design.repetition.icons", "Icon size and style are consistent."], readonly ["design.repetition.border-radius", "Border radii follow tokens and variants."], readonly ["design.repetition.border-weight", "Border weights are consistent."], readonly ["design.repetition.elevation", "Shadows and elevation are consistent."], readonly ["design.repetition.motion", "Motion patterns are consistent."], readonly ["design.repetition.local-overrides", "Unwanted local overrides are identified."], readonly ["design.repetition.template-drift", "Instances do not drift from their template."]];
4
+ type RepetitionRuleId = (typeof repetitionRuleDefinitions)[number][0];
5
+ type RepetitionRule = Rule<RepetitionRuleContext> & {
6
+ readonly identity: {
7
+ readonly id: RepetitionRuleId;
8
+ readonly version: '1.0.0';
9
+ };
10
+ };
11
+ /*** Creates the atomic Repetition and Components Rules from normalized inspected facts. */
12
+ export declare function createRepetitionRules(): readonly RepetitionRule[];
13
+ /*** Supplies immutable FactEnvelope observations without coupling Rules to a browser host. */
14
+ export interface RepetitionRuleContext {
15
+ readonly facts: readonly FactEnvelope[];
16
+ }
17
+ export {};
@@ -0,0 +1,172 @@
1
+ import { isSerializableValue } from '@ankhorage/contracts';
2
+ const repetitionRuleDefinitions = [
3
+ ['design.repetition.button-variants', 'Button variants are consistent.'],
4
+ ['design.repetition.card-variants', 'Card variants and templates are consistent.'],
5
+ ['design.repetition.heading-variants', 'Heading roles are consistent.'],
6
+ ['design.repetition.form-control-style', 'Form controls are consistently styled.'],
7
+ ['design.repetition.link-treatment', 'Link treatment is consistent.'],
8
+ ['design.repetition.navigation-treatment', 'Navigation treatment is consistent.'],
9
+ ['design.repetition.icons', 'Icon size and style are consistent.'],
10
+ ['design.repetition.border-radius', 'Border radii follow tokens and variants.'],
11
+ ['design.repetition.border-weight', 'Border weights are consistent.'],
12
+ ['design.repetition.elevation', 'Shadows and elevation are consistent.'],
13
+ ['design.repetition.motion', 'Motion patterns are consistent.'],
14
+ ['design.repetition.local-overrides', 'Unwanted local overrides are identified.'],
15
+ ['design.repetition.template-drift', 'Instances do not drift from their template.'],
16
+ ];
17
+ /*** Creates the atomic Repetition and Components Rules from normalized inspected facts. */
18
+ export function createRepetitionRules() {
19
+ return repetitionRuleDefinitions.map(([id, summary]) => createRepetitionRule(id, summary));
20
+ }
21
+ /*** Constructs one fact-driven Repetition rule with the catalog's component-tree capability. */
22
+ function createRepetitionRule(id, summary) {
23
+ return {
24
+ defaultSeverity: 'warning',
25
+ dependencies: [],
26
+ evaluate: ({ context, scope }) => evaluateRepetitionFacts(id, context.facts, scope),
27
+ facets: [{ id: 'principle', value: 'repetition' }],
28
+ identity: { id, version: '1.0.0' },
29
+ requiredCapabilities: ['ui.component-tree'],
30
+ summary,
31
+ };
32
+ }
33
+ /*** Evaluates inspected facts for one rule without treating absent scope evidence as a pass. */
34
+ function evaluateRepetitionFacts(ruleId, facts, scope) {
35
+ const scopedFacts = facts.filter((fact) => isRepetitionFactForScope(fact, ruleId, scope));
36
+ const normalizedFacts = scopedFacts
37
+ .filter((fact) => fact.status === 'available')
38
+ .map((fact) => ({ fact, observation: normalizeRepetitionObservation(fact) }));
39
+ const observations = normalizedFacts.flatMap(({ fact, observation }) => observation !== null && observation.ruleId === ruleId ? [{ fact, observation }] : []);
40
+ if (scopedFacts.length === 0 || observations.length !== scopedFacts.length) {
41
+ return {
42
+ findings: [
43
+ {
44
+ evidence: { factCount: 0, scopeId: scope.id },
45
+ message: `Rule "${ruleId}" requires an available normalized component observation for scope "${scope.id}".`,
46
+ ruleId,
47
+ severity: 'warning',
48
+ subjects: [{ id: scope.id, kind: scope.kind }],
49
+ },
50
+ ],
51
+ status: 'INCOMPLETE',
52
+ };
53
+ }
54
+ const findings = observations
55
+ .filter(({ observation }) => !isSameJsonValue(observation.actual, observation.expected))
56
+ .map(({ fact, observation }) => ({
57
+ evidence: { actual: observation.actual, expected: observation.expected, factId: fact.id },
58
+ message: `Observed value for "${observation.subject.id}" does not match the expected repeated value.`,
59
+ ruleId,
60
+ severity: 'warning',
61
+ subjects: [observation.subject],
62
+ }));
63
+ return { findings, status: findings.length === 0 ? 'PASS' : 'FAIL' };
64
+ }
65
+ /*** Accepts only the provider's component-observation envelopes for the exact evaluation scope. */
66
+ function isRepetitionFactForScope(fact, ruleId, scope) {
67
+ return (fact.kind === 'design.repetition.observation' &&
68
+ fact.id.startsWith(`${ruleId}:`) &&
69
+ fact.scope.id === scope.id &&
70
+ fact.scope.kind === scope.kind);
71
+ }
72
+ /*** Validates the normalized portable observation payload before repetition policy consumes it. */
73
+ function normalizeRepetitionObservation(fact) {
74
+ if (!isValidFactEnvelope(fact) || fact.status !== 'available' || !isRecord(fact.value)) {
75
+ return null;
76
+ }
77
+ const { actual, expected, ruleId, subject } = fact.value;
78
+ return isRepetitionRuleId(ruleId) &&
79
+ isRuleSubject(subject) &&
80
+ isSerializableValue(actual) &&
81
+ isSerializableValue(expected)
82
+ ? { actual, expected, ruleId, subject }
83
+ : null;
84
+ }
85
+ /*** Verifies that required FactEnvelope identity, scope, provenance, availability, and hash fields are usable. */
86
+ function isValidFactEnvelope(fact) {
87
+ return (hasValidFactIdentity(fact) &&
88
+ hasValidFactScope(fact) &&
89
+ hasValidFactProvenance(fact) &&
90
+ hasValidFactAvailability(fact));
91
+ }
92
+ /*** Verifies stable identity fields and content integrity metadata on one portable fact. */
93
+ function hasValidFactIdentity(fact) {
94
+ return hasText(fact.id) && hasText(fact.kind) && hasText(fact.contentHash);
95
+ }
96
+ /*** Verifies the complete target partition attached to one portable fact scope. */
97
+ function hasValidFactScope(fact) {
98
+ return (hasText(fact.scope.id) &&
99
+ hasText(fact.scope.kind) &&
100
+ hasText(fact.scope.target.tenantId) &&
101
+ hasText(fact.scope.target.projectId) &&
102
+ hasText(fact.scope.target.targetId) &&
103
+ hasText(fact.scope.target.kind));
104
+ }
105
+ /*** Verifies that a portable fact retains a traceable producer and inspected source. */
106
+ function hasValidFactProvenance(fact) {
107
+ return (hasText(fact.provenance.collectedAt) &&
108
+ hasText(fact.provenance.producer.id) &&
109
+ hasText(fact.provenance.producer.version) &&
110
+ hasText(fact.provenance.source.id) &&
111
+ (fact.provenance.source.revision === null || hasText(fact.provenance.source.revision)));
112
+ }
113
+ /*** Verifies that available values and unavailable reasons remain explicitly represented. */
114
+ function hasValidFactAvailability(fact) {
115
+ return fact.status === 'available'
116
+ ? isSerializableValue(fact.value)
117
+ : hasText(fact.missing.code) && hasText(fact.missing.message);
118
+ }
119
+ /*** Narrows a non-empty serializable text field without accepting whitespace-only identities. */
120
+ function hasText(value) {
121
+ return value.trim().length > 0;
122
+ }
123
+ /*** Narrows one observation rule identifier to the frozen Repetition catalog. */
124
+ function isRepetitionRuleId(value) {
125
+ return typeof value === 'string' && repetitionRuleDefinitions.some(([id]) => id === value);
126
+ }
127
+ /*** Narrows an observation subject without admitting anonymous or host-specific values. */
128
+ function isRuleSubject(value) {
129
+ return (isRecord(value) &&
130
+ typeof value.id === 'string' &&
131
+ typeof value.kind === 'string' &&
132
+ hasText(value.id) &&
133
+ hasText(value.kind));
134
+ }
135
+ /*** Narrows an unknown JSON value to a non-array record before reading named fields. */
136
+ function isRecord(value) {
137
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
138
+ }
139
+ /*** Compares normalized JSON facts structurally so host-specific object identity cannot affect results. */
140
+ function isSameJsonValue(left, right) {
141
+ if (left === right)
142
+ return true;
143
+ if (left === null || right === null || typeof left !== 'object' || typeof right !== 'object') {
144
+ return false;
145
+ }
146
+ if (isJsonArray(left)) {
147
+ return isJsonArray(right) && isSameJsonArray(left, right);
148
+ }
149
+ if (isJsonArray(right))
150
+ return false;
151
+ const leftEntries = Object.entries(left).sort(([leftKey], [rightKey]) => leftKey.localeCompare(rightKey));
152
+ const rightEntries = Object.entries(right).sort(([leftKey], [rightKey]) => leftKey.localeCompare(rightKey));
153
+ return (leftEntries.length === rightEntries.length &&
154
+ leftEntries.every(([leftKey, leftValue], index) => {
155
+ const rightEntry = rightEntries.at(index);
156
+ if (rightEntry === undefined)
157
+ return false;
158
+ return leftKey === rightEntry[0] && isSameJsonValue(leftValue, rightEntry[1]);
159
+ }));
160
+ }
161
+ /*** Narrows one serializable JSON value to an ordered JSON array. */
162
+ function isJsonArray(value) {
163
+ return Array.isArray(value);
164
+ }
165
+ /*** Compares JSON arrays in order without relying on host object identity. */
166
+ function isSameJsonArray(left, right) {
167
+ return (left.length === right.length &&
168
+ left.every((value, index) => {
169
+ const rightValue = right.at(index);
170
+ return rightValue !== undefined && isSameJsonValue(value, rightValue);
171
+ }));
172
+ }
@@ -0,0 +1,8 @@
1
+ import type { SpacingProximityObservation } from '../../types/spacingProximity';
2
+ interface Failure {
3
+ readonly message: string;
4
+ readonly values: readonly number[];
5
+ }
6
+ /*** Applies the frozen rule-specific policy to complete normalized adapter evidence. */
7
+ export declare function assessSpacingProximityObservation(observation: SpacingProximityObservation): Failure | null | undefined;
8
+ export {};
@@ -0,0 +1,294 @@
1
+ /*** Applies the frozen rule-specific policy to complete normalized adapter evidence. */
2
+ export function assessSpacingProximityObservation(observation) {
3
+ const { value } = observation;
4
+ switch (observation.kind) {
5
+ case 'design.spacing.token-allowed':
6
+ return tokens(value);
7
+ case 'design.spacing.vertical-rhythm':
8
+ return rhythm(value);
9
+ case 'design.spacing.section-gap':
10
+ return allowed(value, 'Section gaps include a value outside the permitted spacing values.');
11
+ case 'design.spacing.container-padding':
12
+ return padding(value);
13
+ case 'design.proximity.related-grouping':
14
+ return related(value);
15
+ case 'design.proximity.unrelated-separation':
16
+ return unrelated(value);
17
+ case 'design.proximity.label-control':
18
+ return pairs(value, 'Labels are farther from their controls than unrelated content.');
19
+ case 'design.proximity.heading-content':
20
+ return pairs(value, 'Headings are farther from their content than unrelated content.');
21
+ case 'design.proximity.card-internals':
22
+ return card(value);
23
+ case 'design.spacing.double-application':
24
+ return doubled(value);
25
+ case 'design.spacing.unexpected-collapse':
26
+ return collapsed(value);
27
+ }
28
+ }
29
+ /*** Confirms each used token name and value exists in the permitted token inventory. */
30
+ function tokens(value) {
31
+ const source = record(value);
32
+ const permitted = source === undefined ? undefined : tokenList(source.permittedTokens);
33
+ const usages = source === undefined ? undefined : tokenList(source.tokenUsages);
34
+ if (permitted === undefined || usages === undefined)
35
+ return undefined;
36
+ const invalid = usages.find((usage) => !permitted.some((token) => token.name === usage.name && token.value === usage.value));
37
+ return invalid === undefined
38
+ ? null
39
+ : {
40
+ message: `Spacing token "${invalid.name}" is not permitted at its measured value.`,
41
+ values: [invalid.value],
42
+ };
43
+ }
44
+ /*** Confirms measured vertical gaps are whole units of the supplied rhythm. */
45
+ function rhythm(value) {
46
+ const source = record(value);
47
+ const gaps = source === undefined ? undefined : numbers(source.gaps);
48
+ const unit = source?.rhythmUnit;
49
+ if (gaps === undefined || !positive(unit))
50
+ return undefined;
51
+ const invalid = gaps.find((gap) => gap % unit !== 0);
52
+ return invalid === undefined
53
+ ? null
54
+ : {
55
+ message: 'A measured vertical gap is not a whole multiple of the rhythm unit.',
56
+ values: [invalid, unit],
57
+ };
58
+ }
59
+ /*** Confirms each measured gap is a permitted spacing value. */
60
+ function allowed(value, message) {
61
+ const source = record(value);
62
+ const gaps = source === undefined ? undefined : numbers(source.gaps);
63
+ const permitted = source === undefined ? undefined : numbers(source.permittedValues);
64
+ if (gaps === undefined || permitted === undefined)
65
+ return undefined;
66
+ const invalid = gaps.find((gap) => !permitted.includes(gap));
67
+ return invalid === undefined ? null : { message, values: [invalid] };
68
+ }
69
+ /*** Confirms all four measured container edges use permitted padding values. */
70
+ function padding(value) {
71
+ const source = record(value);
72
+ const permitted = source === undefined ? undefined : numbers(source.permittedValues);
73
+ const containers = source?.containers;
74
+ if (permitted === undefined || !Array.isArray(containers) || containers.length === 0)
75
+ return undefined;
76
+ const values = containers.flatMap(edges);
77
+ if (values.length !== containers.length * 4)
78
+ return undefined;
79
+ const invalid = values.find((item) => !permitted.includes(item));
80
+ return invalid === undefined
81
+ ? null
82
+ : {
83
+ message: 'Container padding includes a value outside the permitted spacing values.',
84
+ values: [invalid],
85
+ };
86
+ }
87
+ /*** Confirms related members are no farther apart than their nearest unrelated group. */
88
+ function related(value) {
89
+ const groups = relatedGroups(value);
90
+ if (groups === undefined)
91
+ return undefined;
92
+ const invalid = groups.find((group) => group.distances.some((distance) => distance > group.reference));
93
+ return invalid === undefined
94
+ ? null
95
+ : {
96
+ message: 'A related group has a larger internal distance than its nearest unrelated group.',
97
+ values: [...invalid.distances, invalid.reference],
98
+ };
99
+ }
100
+ /*** Confirms unrelated groups exceed every internal grouping distance. */
101
+ function unrelated(value) {
102
+ const groups = unrelatedGroups(value);
103
+ if (groups === undefined)
104
+ return undefined;
105
+ const invalid = groups.find((group) => group.distances.some((distance) => distance >= group.reference));
106
+ return invalid === undefined
107
+ ? null
108
+ : {
109
+ message: 'An unrelated group is not separated beyond its internal grouping distances.',
110
+ values: [...invalid.distances, invalid.reference],
111
+ };
112
+ }
113
+ /*** Confirms each label-control or heading-content pair beats its unrelated distance. */
114
+ function pairs(value, message) {
115
+ const groups = relatedGroups(value);
116
+ if (groups === undefined || groups.some((group) => group.distances.length !== 1))
117
+ return undefined;
118
+ const invalid = groups.find((group) => (group.distances[0] ?? 0) > group.reference);
119
+ return invalid === undefined
120
+ ? null
121
+ : { message, values: [invalid.distances[0] ?? 0, invalid.reference] };
122
+ }
123
+ /*** Confirms card internals remain closer than outside content. */
124
+ function card(value) {
125
+ const cards = cardGroups(value);
126
+ if (cards === undefined)
127
+ return undefined;
128
+ const invalid = cards.find((item) => item.distances.some((distance) => distance > item.reference));
129
+ return invalid === undefined
130
+ ? null
131
+ : {
132
+ message: 'A card internal distance exceeds the measured distance to outside content.',
133
+ values: [...invalid.distances, invalid.reference],
134
+ };
135
+ }
136
+ /*** Detects cumulative parent and child spacing in a rendered distance. */
137
+ function doubled(value) {
138
+ const triples = spacingTriples(value);
139
+ if (triples === undefined)
140
+ return undefined;
141
+ const invalid = triples.find((item) => item.third > Math.max(item.first, item.second));
142
+ return invalid === undefined
143
+ ? null
144
+ : {
145
+ message: 'Parent and child spacing accumulate into a larger rendered distance.',
146
+ values: [invalid.first, invalid.second, invalid.third],
147
+ };
148
+ }
149
+ /*** Detects a collapsed gap where structure proves margins should remain separated. */
150
+ function collapsed(value) {
151
+ const source = record(value);
152
+ const pairs = source?.pairs;
153
+ if (!Array.isArray(pairs) || pairs.length === 0)
154
+ return undefined;
155
+ const margins = pairs.map(collapse);
156
+ if (margins.some((margin) => margin === undefined))
157
+ return undefined;
158
+ const invalid = margins.find((margin) => margin?.separates && margin.rendered < margin.preceding + margin.following);
159
+ return invalid === undefined
160
+ ? null
161
+ : {
162
+ message: 'A structurally separated margin pair has a collapsed rendered distance.',
163
+ values: [invalid.preceding, invalid.following, invalid.rendered],
164
+ };
165
+ }
166
+ /*** Parses a finite non-negative measurement list. */
167
+ function numbers(value) {
168
+ return Array.isArray(value) && value.length > 0 && value.every(measurement) ? value : undefined;
169
+ }
170
+ /*** Parses named spacing tokens. */
171
+ function tokenList(value) {
172
+ return Array.isArray(value) && value.length > 0 && value.every(token) ? value : undefined;
173
+ }
174
+ /*** Parses a four-edge padding measurement. */
175
+ function edges(value) {
176
+ return isRecord(value) &&
177
+ measurement(value.top) &&
178
+ measurement(value.right) &&
179
+ measurement(value.bottom) &&
180
+ measurement(value.left)
181
+ ? [value.top, value.right, value.bottom, value.left]
182
+ : [];
183
+ }
184
+ /*** Parses groups of related distances and their nearest unrelated distance. */
185
+ function relatedGroups(value) {
186
+ const source = record(value);
187
+ const collection = source?.groups;
188
+ if (!Array.isArray(collection) || collection.length === 0)
189
+ return undefined;
190
+ const groups = collection.map((item) => {
191
+ const itemRecord = record(item);
192
+ const distances = itemRecord === undefined ? undefined : numbers(itemRecord.relatedDistances);
193
+ const reference = itemRecord?.nearestUnrelatedDistance;
194
+ return distances === undefined || !measurement(reference)
195
+ ? undefined
196
+ : { distances, reference };
197
+ });
198
+ return groups.every(group) ? groups : undefined;
199
+ }
200
+ /*** Parses groups of internal distances and their unrelated-group distance. */
201
+ function unrelatedGroups(value) {
202
+ const source = record(value);
203
+ const collection = source?.groups;
204
+ if (!Array.isArray(collection) || collection.length === 0)
205
+ return undefined;
206
+ const groups = collection.map((item) => {
207
+ const itemRecord = record(item);
208
+ const distances = itemRecord === undefined ? undefined : numbers(itemRecord.internalDistances);
209
+ const reference = itemRecord?.unrelatedDistance;
210
+ return distances === undefined || !measurement(reference)
211
+ ? undefined
212
+ : { distances, reference };
213
+ });
214
+ return groups.every(group) ? groups : undefined;
215
+ }
216
+ /*** Parses card-internal distances and their nearest outside-content distance. */
217
+ function cardGroups(value) {
218
+ const source = record(value);
219
+ const collection = source?.cards;
220
+ if (!Array.isArray(collection) || collection.length === 0)
221
+ return undefined;
222
+ const groups = collection.map((item) => {
223
+ const itemRecord = record(item);
224
+ const distances = itemRecord === undefined ? undefined : numbers(itemRecord.internalDistances);
225
+ const reference = itemRecord?.nearestOutsideDistance;
226
+ return distances === undefined || !measurement(reference)
227
+ ? undefined
228
+ : { distances, reference };
229
+ });
230
+ return groups.every(group) ? groups : undefined;
231
+ }
232
+ /*** Parses raw parent, child, and rendered spacing measurements. */
233
+ function spacingTriples(value) {
234
+ const source = record(value);
235
+ const pairs = source?.pairs;
236
+ if (!Array.isArray(pairs) || pairs.length === 0)
237
+ return undefined;
238
+ const triples = pairs.map((item) => {
239
+ const itemRecord = record(item);
240
+ const first = itemRecord?.parentSpacing;
241
+ const second = itemRecord?.childSpacing;
242
+ const third = itemRecord?.renderedDistance;
243
+ return measurement(first) && measurement(second) && measurement(third)
244
+ ? { first, second, third }
245
+ : undefined;
246
+ });
247
+ return triples.every(isTriple) ? triples : undefined;
248
+ }
249
+ /*** Parses one margin pair and its structural relationship. */
250
+ function collapse(value) {
251
+ return isRecord(value) &&
252
+ measurement(value.precedingMargin) &&
253
+ measurement(value.followingMargin) &&
254
+ measurement(value.renderedDistance) &&
255
+ typeof value.separatesMargins === 'boolean'
256
+ ? {
257
+ following: value.followingMargin,
258
+ preceding: value.precedingMargin,
259
+ rendered: value.renderedDistance,
260
+ separates: value.separatesMargins,
261
+ }
262
+ : undefined;
263
+ }
264
+ /*** Narrows a record-shaped serializable value. */
265
+ function record(value) {
266
+ return isRecord(value) ? value : undefined;
267
+ }
268
+ /*** Narrows a token record. */
269
+ function token(value) {
270
+ return (isRecord(value) &&
271
+ typeof value.name === 'string' &&
272
+ value.name.length > 0 &&
273
+ measurement(value.value));
274
+ }
275
+ /*** Narrows a complete parsed group. */
276
+ function group(value) {
277
+ return value !== undefined;
278
+ }
279
+ /*** Narrows a complete parsed spacing triple. */
280
+ function isTriple(value) {
281
+ return value !== undefined;
282
+ }
283
+ /*** Narrows a serializable record. */
284
+ function isRecord(value) {
285
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
286
+ }
287
+ /*** Narrows a finite non-negative layout measurement. */
288
+ function measurement(value) {
289
+ return typeof value === 'number' && Number.isFinite(value) && value >= 0;
290
+ }
291
+ /*** Narrows a finite positive layout measurement. */
292
+ function positive(value) {
293
+ return measurement(value) && value > 0;
294
+ }
@@ -0,0 +1,4 @@
1
+ import type { FactEnvelope } from '@ankhorage/contracts/rules';
2
+ import type { RuleSet } from '@ankhorage/rules';
3
+ /*** Creates the independently owned Spacing and Proximity Rules contribution. */
4
+ export declare function createSpacingProximityRuleSet(): RuleSet<readonly FactEnvelope[]>;
@@ -0,0 +1,86 @@
1
+ import { assessSpacingProximityObservation } from './assessSpacingProximityObservation';
2
+ import { parseSpacingProximityMeasurements } from './parseSpacingProximityMeasurements';
3
+ /*** Creates the independently owned Spacing and Proximity Rules contribution. */
4
+ export function createSpacingProximityRuleSet() {
5
+ return { id: 'ankhorage.rules-design.spacing-proximity', rules: definitions.map(createRule) };
6
+ }
7
+ const factKind = 'design.spacing-proximity.measurements';
8
+ const definitions = [
9
+ ['design.spacing.token-allowed', 'source.style-tokens', 'project', 'error', 'spacing'],
10
+ ['design.spacing.vertical-rhythm', 'dom.layout', 'component', 'error', 'spacing'],
11
+ ['design.spacing.section-gap', 'dom.layout', 'component', 'error', 'spacing'],
12
+ ['design.spacing.container-padding', 'dom.layout', 'component', 'error', 'spacing'],
13
+ ['design.proximity.related-grouping', 'dom.layout', 'component', 'warning', 'proximity'],
14
+ ['design.proximity.unrelated-separation', 'dom.layout', 'component', 'warning', 'proximity'],
15
+ ['design.proximity.label-control', 'dom.layout', 'component', 'error', 'proximity'],
16
+ ['design.proximity.heading-content', 'dom.layout', 'component', 'error', 'proximity'],
17
+ ['design.proximity.card-internals', 'dom.layout', 'component', 'error', 'proximity'],
18
+ ['design.spacing.double-application', 'dom.layout', 'component', 'error', 'spacing'],
19
+ ['design.spacing.unexpected-collapse', 'dom.layout', 'component', 'error', 'spacing'],
20
+ ].map(([id, capability, scopeKind, severity, topic]) => ({
21
+ capability,
22
+ id,
23
+ scopeKind,
24
+ severity,
25
+ topic,
26
+ }));
27
+ /*** Creates one deterministic rule from its frozen catalog definition. */
28
+ function createRule(definition) {
29
+ return {
30
+ defaultSeverity: definition.severity,
31
+ dependencies: [],
32
+ evaluate: ({ context, scope }) => evaluate(context, definition, scope),
33
+ facets: facets(definition),
34
+ identity: { id: definition.id, version: '1.0.0' },
35
+ requiredCapabilities: [definition.capability],
36
+ summary: `Evaluate ${definition.id} from supplied normalized measurements.`,
37
+ };
38
+ }
39
+ /*** Evaluates one rule from normalized evidence, never from an adapter-supplied verdict. */
40
+ function evaluate(facts, definition, scope) {
41
+ const fact = matchingFact(facts, scope);
42
+ if (fact === null || fact.status === 'missing')
43
+ return incomplete();
44
+ const observations = parseSpacingProximityMeasurements(fact.value)?.filter((candidate) => candidate.kind === definition.id);
45
+ if (observations === undefined || observations.length === 0)
46
+ return incomplete();
47
+ const assessments = observations.map(assessSpacingProximityObservation);
48
+ if (assessments.some((assessment) => assessment === undefined))
49
+ return incomplete();
50
+ const failures = assessments.filter((assessment) => assessment !== null);
51
+ if (failures.length === 0)
52
+ return { findings: [], status: 'PASS' };
53
+ return failures.length === assessments.length
54
+ ? failed(definition, fact, scope, failures)
55
+ : incomplete();
56
+ }
57
+ /*** Selects exactly one scope-local fact to prevent ambiguous evidence from passing. */
58
+ function matchingFact(facts, scope) {
59
+ const matches = facts.filter((fact) => fact.kind === factKind && fact.scope.id === scope.id && fact.scope.kind === scope.kind);
60
+ return matches.length === 1 ? (matches[0] ?? null) : null;
61
+ }
62
+ /*** Produces an evidence-backed failure without accepting an adapter-provided pass or fail state. */
63
+ function failed(definition, fact, scope, failures) {
64
+ return {
65
+ findings: failures.map((failure) => ({
66
+ evidence: { factId: fact.id, scopeId: scope.id, values: failure.values },
67
+ message: failure.message,
68
+ ruleId: definition.id,
69
+ severity: definition.severity,
70
+ subjects: [{ id: scope.id, kind: scope.kind }],
71
+ })),
72
+ status: 'FAIL',
73
+ };
74
+ }
75
+ /*** Produces an incomplete result whenever factual measurements cannot be established. */
76
+ function incomplete() {
77
+ return { findings: [], status: 'INCOMPLETE' };
78
+ }
79
+ /*** Creates controlled rule facets for capability consumers and catalog queries. */
80
+ function facets(definition) {
81
+ return [
82
+ { id: 'principle', value: 'proximity' },
83
+ { id: 'scope', value: definition.scopeKind },
84
+ { id: 'topic', value: definition.topic },
85
+ ];
86
+ }
@@ -0,0 +1,3 @@
1
+ import type { SpacingProximityObservation } from '../../types/spacingProximity';
2
+ /*** Parses a complete versioned sequence of raw spacing and proximity observations. */
3
+ export declare function parseSpacingProximityMeasurements(value: unknown): readonly SpacingProximityObservation[] | undefined;
@@ -0,0 +1,38 @@
1
+ /*** Parses a complete versioned sequence of raw spacing and proximity observations. */
2
+ export function parseSpacingProximityMeasurements(value) {
3
+ if (!isRecord(value) || value.schemaVersion !== 2 || !Array.isArray(value.observations))
4
+ return undefined;
5
+ const observations = value.observations.map(parseObservation);
6
+ return observations.every(isObservation) ? observations : undefined;
7
+ }
8
+ /*** Parses one adapter observation containing a frozen rule ID and raw serializable evidence. */
9
+ function parseObservation(value) {
10
+ if (!isRecord(value) || !isRuleId(value.kind) || value.value === undefined)
11
+ return undefined;
12
+ return { kind: value.kind, value: value.value };
13
+ }
14
+ /*** Narrows a parsed value to a complete spacing or proximity observation. */
15
+ function isObservation(value) {
16
+ return value !== undefined;
17
+ }
18
+ /*** Narrows a serializable unknown value to a record without assuming a prototype. */
19
+ function isRecord(value) {
20
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
21
+ }
22
+ /*** Narrows the only frozen rule IDs permitted in this group-local evidence schema. */
23
+ function isRuleId(value) {
24
+ return (typeof value === 'string' &&
25
+ [
26
+ 'design.spacing.token-allowed',
27
+ 'design.spacing.vertical-rhythm',
28
+ 'design.spacing.section-gap',
29
+ 'design.spacing.container-padding',
30
+ 'design.proximity.related-grouping',
31
+ 'design.proximity.unrelated-separation',
32
+ 'design.proximity.label-control',
33
+ 'design.proximity.heading-content',
34
+ 'design.proximity.card-internals',
35
+ 'design.spacing.double-application',
36
+ 'design.spacing.unexpected-collapse',
37
+ ].includes(value));
38
+ }
@@ -0,0 +1,7 @@
1
+ /*** The frozen rule IDs owned by the Spacing and Proximity rule group. */
2
+ export type SpacingProximityRuleId = 'design.proximity.card-internals' | 'design.proximity.heading-content' | 'design.proximity.label-control' | 'design.proximity.related-grouping' | 'design.proximity.unrelated-separation' | 'design.spacing.container-padding' | 'design.spacing.double-application' | 'design.spacing.section-gap' | 'design.spacing.token-allowed' | 'design.spacing.unexpected-collapse' | 'design.spacing.vertical-rhythm';
3
+ /*** One normalized raw observation supplied by a layout or token adapter. */
4
+ export interface SpacingProximityObservation {
5
+ readonly kind: SpacingProximityRuleId;
6
+ readonly value: unknown;
7
+ }
File without changes
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ankhorage/rules-design",
3
- "version": "0.2.1",
3
+ "version": "0.2.2",
4
4
  "description": "Declarative catalog for reusable design rules.",
5
5
  "license": "MIT",
6
6
  "homepage": "https://github.com/ankhorage/rules-design#readme",
@@ -59,6 +59,7 @@
59
59
  },
60
60
  "dependencies": {
61
61
  "@ankhorage/contracts": "^26.4.0",
62
- "@ankhorage/rules": "^0.4.0"
62
+ "@ankhorage/rules": "^0.4.0",
63
+ "@ankhorage/utility": "^1.10.0"
63
64
  }
64
65
  }