@ankhorage/rules-design 0.7.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,11 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.8.0
4
+
5
+ ### Minor Changes
6
+
7
+ - cd12383: Add the deterministic `recognizeWebsiteDocument` public recognition assembly API.
8
+
3
9
  ## 0.7.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.7.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.8.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)
7
7
 
8
8
  Declarative catalog for reusable design rules.
9
9
 
@@ -38,4 +38,5 @@ import { createRuleRegistry, evaluateRules } from '@ankhorage/rules';
38
38
  - [Module relationships](././paradox/diagrams/module-relationships.mmd)
39
39
  - [Export graph](././paradox/diagrams/export-graph.mmd)
40
40
  - [recognizeWebsiteDesignProperties sequence](././paradox/diagrams/sequences/recognize-website-design-properties.mmd)
41
+ - [recognizeWebsiteDocument sequence](././paradox/diagrams/sequences/recognize-website-document.mmd)
41
42
  - [selectDesignRuleProfile sequence](././paradox/diagrams/sequences/select-design-rule-profile.mmd)
@@ -0,0 +1,3 @@
1
+ import type { WebsiteAsset, WebsiteObservationDocument } from '@ankhorage/contracts/website';
2
+ /*** Indexes globally named assets only after rejecting incompatible duplicate identities. */
3
+ export declare function createWebsiteAssetIndex(document: WebsiteObservationDocument): ReadonlyMap<string, WebsiteAsset>;
@@ -0,0 +1,13 @@
1
+ /*** Indexes globally named assets only after rejecting incompatible duplicate identities. */
2
+ export function createWebsiteAssetIndex(document) {
3
+ return new Map([
4
+ ...Map.groupBy(document.pages.flatMap((page) => page.assets), (asset) => asset.id),
5
+ ].map(([id, assets]) => {
6
+ const [asset] = assets;
7
+ if (assets.some((candidate) => candidate.url !== asset.url ||
8
+ candidate.kind !== asset.kind ||
9
+ candidate.contentType !== asset.contentType))
10
+ throw new TypeError(`Conflicting asset identity ${id}.`);
11
+ return [id, asset];
12
+ }));
13
+ }
@@ -0,0 +1,3 @@
1
+ import type { WebsiteRecognizedProp } from '@ankhorage/contracts/website';
2
+ /*** Qualifies nested structural source evidence so equal DOM paths remain page-unique. */
3
+ export declare function qualifyWebsiteRecognitionProps(property: WebsiteRecognizedProp, pageId: string): WebsiteRecognizedProp;
@@ -0,0 +1,28 @@
1
+ /*** Qualifies nested structural source evidence so equal DOM paths remain page-unique. */
2
+ export function qualifyWebsiteRecognitionProps(property, pageId) {
3
+ return {
4
+ ...property,
5
+ originalValues: property.originalValues.map((value) => qualifySourceReferences(value, pageId)),
6
+ value: qualifySourceReferences(property.value, pageId),
7
+ };
8
+ }
9
+ /*** Qualifies the source references in a structural property list without altering observed literals. */
10
+ function qualifySourceReferences(value, pageId) {
11
+ if (!isSerializableArray(value))
12
+ return value;
13
+ return value.map((item) => isSourceReference(item)
14
+ ? { ...item, sourceRef: JSON.stringify([pageId, item.sourceRef]) }
15
+ : item);
16
+ }
17
+ /*** Narrows a serializable value to its immutable list representation. */
18
+ function isSerializableArray(value) {
19
+ return Array.isArray(value);
20
+ }
21
+ /*** Narrows the portable source-linked records used by structural text, link, and media props. */
22
+ function isSourceReference(value) {
23
+ return (value !== null &&
24
+ typeof value === 'object' &&
25
+ !Array.isArray(value) &&
26
+ 'sourceRef' in value &&
27
+ typeof value.sourceRef === 'string');
28
+ }
@@ -0,0 +1,3 @@
1
+ import type { WebsiteObservationDocument, WebsiteRecognitionDocument } from '@ankhorage/contracts/website';
2
+ /*** Assembles the public website recognition contract from structural and factual design recognition. */
3
+ export declare function recognizeWebsiteDocument(document: WebsiteObservationDocument): WebsiteRecognitionDocument;
@@ -0,0 +1,203 @@
1
+ import { recognizeWebsiteStructure } from '../website-recognition/recognizeWebsiteStructure';
2
+ import { createWebsiteAssetIndex } from './createWebsiteAssetIndex';
3
+ import { qualifyWebsiteRecognitionProps } from './qualifyWebsiteRecognitionProps';
4
+ import { recognizeWebsiteDesignProperties } from './recognizeWebsiteDesignProperties';
5
+ import { validateWebsiteObservationDocument } from './validateWebsiteObservationDocument';
6
+ /*** Assembles the public website recognition contract from structural and factual design recognition. */
7
+ export function recognizeWebsiteDocument(document) {
8
+ validateWebsiteObservationDocument(document);
9
+ const design = recognizeWebsiteDesignProperties(document);
10
+ const pages = recognizeWebsiteStructure(document).map((page) => assemblePage(page, observedPageFor(document, page.id), design.nodes));
11
+ return {
12
+ designTokens: design.tokenCandidates.map(assembleDesignToken),
13
+ documentId: `recognition:${document.documentId}`,
14
+ media: assembleMedia(document),
15
+ navigation: document.pages.flatMap((page) => page.navigation.map((item) => ({
16
+ ...item,
17
+ sourceRef: sourceIdentity(page.id, item.sourceRef),
18
+ }))),
19
+ observedDocumentId: document.documentId,
20
+ pages,
21
+ recognizedAt: document.collectedAt,
22
+ schemaVersion: 1,
23
+ site: document.site,
24
+ source: document.source,
25
+ };
26
+ }
27
+ /*** Finds the validated observed page required to join a structural recognition. */
28
+ function observedPageFor(document, pageId) {
29
+ const page = document.pages.find((candidate) => candidate.id === pageId);
30
+ if (page === undefined)
31
+ throw new TypeError(`Missing observed page ${pageId}.`);
32
+ return page;
33
+ }
34
+ /*** Joins factual design observations with the structural page tree by page-local source identity. */
35
+ function assemblePage(page, observedPage, designNodes) {
36
+ const designBySourceRef = new Map(designNodes
37
+ .filter((node) => node.pageId === page.id)
38
+ .map((node) => [node.sourceRef, node]));
39
+ const nodes = page.nodes.map((node) => assembleNode(node, observedPage, designBySourceRef));
40
+ const nodesById = new Map(nodes.map((node) => [node.id, node]));
41
+ return {
42
+ ...page,
43
+ nodes,
44
+ root: assembleUiNode(page.root, page.id, nodesById),
45
+ };
46
+ }
47
+ /*** Adds exact base, responsive, and unresolved design evidence to one structural recognition. */
48
+ function assembleNode(node, page, designBySourceRef) {
49
+ const design = node.sourceRefs.flatMap((sourceRef) => {
50
+ const candidate = designBySourceRef.get(sourceRef);
51
+ return candidate === undefined ? [] : [candidate];
52
+ });
53
+ const ownerDesign = design.filter((candidate) => candidate.sourceRef === node.id);
54
+ const inheritedDesign = design.filter((candidate) => candidate.sourceRef !== node.id);
55
+ const baseViewportId = page.viewports[0]?.id;
56
+ const baseStateId = page.states[0]?.id;
57
+ const designProperties = [...ownerDesign, ...inheritedDesign].flatMap((candidate) => [
58
+ ...candidate.colors,
59
+ ...candidate.typography,
60
+ ...candidate.layout,
61
+ ...candidate.responsive,
62
+ ]);
63
+ return {
64
+ ...node,
65
+ id: sourceIdentity(page.id, node.id),
66
+ props: mergeProperties([
67
+ ...node.props.map((property) => qualifyWebsiteRecognitionProps(property, page.id)),
68
+ ...baseProperties(designProperties, baseViewportId, baseStateId),
69
+ ...unresolvedProperties(design),
70
+ ]),
71
+ responsive: responsiveVariants(designProperties, baseViewportId, baseStateId),
72
+ sourceRefs: node.sourceRefs.map((sourceRef) => sourceIdentity(page.id, sourceRef)),
73
+ unresolved: node.unresolved === null
74
+ ? null
75
+ : {
76
+ ...node.unresolved,
77
+ sourceRefs: node.unresolved.sourceRefs.map((sourceRef) => sourceIdentity(page.id, sourceRef)),
78
+ },
79
+ };
80
+ }
81
+ /*** Selects the first declared viewport and state as the stable non-responsive property baseline. */
82
+ function baseProperties(observations, viewportId, stateId) {
83
+ return observations
84
+ .filter((observation) => observation.viewportId === viewportId && observation.stateId === stateId)
85
+ .map((observation) => propertyFromObservation(observation, stateId));
86
+ }
87
+ /*** Groups every non-baseline measured property by viewport without fabricating breakpoints. */
88
+ function responsiveVariants(observations, baseViewportId, baseStateId) {
89
+ return [
90
+ ...Map.groupBy(observations.filter((observation) => observation.viewportId !== baseViewportId || observation.stateId !== baseStateId), (observation) => observation.viewportId),
91
+ ]
92
+ .map(([viewportId, properties]) => ({
93
+ props: mergeProperties(properties.map((observation) => propertyFromObservation(observation, baseStateId))),
94
+ viewportId,
95
+ }))
96
+ .toSorted((left, right) => left.viewportId.localeCompare(right.viewportId));
97
+ }
98
+ /*** Represents unavailable source evidence explicitly inside the DTO's extensible property channel. */
99
+ function unresolvedProperties(design) {
100
+ return design.flatMap((node) => node.unresolved.map((unresolved) => ({
101
+ name: `unresolved:${unresolved.stateId}:${unresolved.viewportId}:${unresolved.kind}`,
102
+ originalValues: [unresolvedValue(unresolved.missing)],
103
+ value: unresolvedValue(unresolved.missing),
104
+ })));
105
+ }
106
+ /*** Converts the portable missing-value DTO to the serializable map shape required by property values. */
107
+ function unresolvedValue(missing) {
108
+ return { code: missing.code, message: missing.message };
109
+ }
110
+ /*** Converts factual style samples to property names that retain state identity when it is not baseline. */
111
+ function propertyFromObservation(observation, baselineStateId) {
112
+ return {
113
+ name: observation.stateId === baselineStateId
114
+ ? observation.name
115
+ : `state:${observation.stateId}:${observation.name}`,
116
+ originalValues: [observation.value],
117
+ value: observation.value,
118
+ };
119
+ }
120
+ /*** Merges duplicate property samples while retaining every original value in stable JSON order. */
121
+ function mergeProperties(properties) {
122
+ return [...Map.groupBy(properties, (property) => property.name)]
123
+ .map(([name, values]) => ({
124
+ name,
125
+ originalValues: uniqueSerializableValues(values.flatMap((value) => value.originalValues)),
126
+ value: first(values).value,
127
+ }))
128
+ .toSorted((left, right) => left.name.localeCompare(right.name));
129
+ }
130
+ /*** Reads a non-empty collected group after the grouping operation that created it. */
131
+ function first(values) {
132
+ const [value] = values;
133
+ if (value === undefined)
134
+ throw new TypeError('Expected a non-empty collection.');
135
+ return value;
136
+ }
137
+ /*** Deduplicates serializable literals by their exact JSON representation without coercion. */
138
+ function uniqueSerializableValues(values) {
139
+ return [...new Map(values.map((value) => [JSON.stringify(value), value])).values()];
140
+ }
141
+ /*** Rebuilds the canonical tree so node IDs and props agree with the assembled node mapping. */
142
+ function assembleUiNode(node, pageId, nodesById) {
143
+ const recognized = nodesById.get(sourceIdentity(pageId, node.id));
144
+ return {
145
+ ...(node.children === undefined
146
+ ? {}
147
+ : { children: node.children.map((child) => assembleUiNode(child, pageId, nodesById)) }),
148
+ id: sourceIdentity(pageId, node.id),
149
+ ...(recognized === undefined || recognized.props.length === 0
150
+ ? {}
151
+ : {
152
+ props: Object.fromEntries(recognized.props.map((property) => [property.name, property.value])),
153
+ }),
154
+ type: node.type,
155
+ };
156
+ }
157
+ /*** Converts role-free factual token candidates to the published, source-qualified token contract. */
158
+ function assembleDesignToken(candidate) {
159
+ return {
160
+ id: JSON.stringify([candidate.kind, candidate.property, candidate.value]),
161
+ kind: candidate.kind,
162
+ originalValues: candidate.originalValues,
163
+ sourceRefs: candidate.sourceRefs.map((reference) => sourceIdentity(reference.pageId, reference.sourceRef)),
164
+ value: candidate.value,
165
+ };
166
+ }
167
+ /*** Deduplicates media by known asset identity or exact anonymous media identity while retaining sources. */
168
+ function assembleMedia(document) {
169
+ const assetIndex = createWebsiteAssetIndex(document);
170
+ const references = [
171
+ ...document.pages.flatMap((page) => page.nodes.flatMap((node) => node.media.map((media) => ({ media, pageId: page.id })))),
172
+ ...document.pages.flatMap((page) => page.assets.flatMap((asset) => (asset.sourceRefs.length === 0 ? [undefined] : asset.sourceRefs).map((sourceRef) => ({
173
+ media: { assetId: asset.id, kind: asset.kind, sourceRef, url: asset.url },
174
+ pageId: page.id,
175
+ })))),
176
+ ];
177
+ return [
178
+ ...Map.groupBy(references, ({ media }) => media.assetId === null ? `${media.kind}\u0000${media.url}` : `asset\u0000${media.assetId}`),
179
+ ]
180
+ .map(([identity, entries]) => assembleMediaGroup(identity, entries, assetIndex))
181
+ .toSorted((left, right) => left.id.localeCompare(right.id));
182
+ }
183
+ /*** Assembles one deduplicated media record and rejects incompatible observations sharing an asset ID. */
184
+ function assembleMediaGroup(identity, entries, assetsById) {
185
+ const firstEntry = first(entries);
186
+ if (entries.some((entry) => entry.media.url !== firstEntry.media.url))
187
+ throw new TypeError(`Conflicting URLs for media ${identity}.`);
188
+ const asset = firstEntry.media.assetId === null ? undefined : assetsById.get(firstEntry.media.assetId);
189
+ return {
190
+ asset: asset === undefined ? null : { mediaId: asset.id },
191
+ id: identity,
192
+ originalUrl: firstEntry.media.url,
193
+ sourceRefs: [
194
+ ...new Set(entries.flatMap((entry) => entry.media.sourceRef === undefined
195
+ ? []
196
+ : [sourceIdentity(entry.pageId, entry.media.sourceRef)])),
197
+ ],
198
+ };
199
+ }
200
+ /*** Serializes a two-part source identity without delimiters that could collide with source content. */
201
+ function sourceIdentity(pageId, sourceRef) {
202
+ return JSON.stringify([pageId, sourceRef]);
203
+ }
@@ -0,0 +1,3 @@
1
+ import type { WebsiteObservationDocument } from '@ankhorage/contracts/website';
2
+ /*** Validates the identity and reference invariants required for deterministic recognition assembly. */
3
+ export declare function validateWebsiteObservationDocument(document: WebsiteObservationDocument): void;
@@ -0,0 +1,29 @@
1
+ /*** Validates the identity and reference invariants required for deterministic recognition assembly. */
2
+ export function validateWebsiteObservationDocument(document) {
3
+ const schemaVersion = document.schemaVersion;
4
+ if (schemaVersion !== 1)
5
+ throw new TypeError('Unsupported website observation schema.');
6
+ if (document.documentId.length === 0)
7
+ throw new TypeError('Website observation documentId is required.');
8
+ unique(document.pages.map((page) => page.id), 'page id');
9
+ document.pages.forEach(validatePage);
10
+ }
11
+ /*** Validates page-local references without rejecting malformed hierarchy evidence that recognition must retain. */
12
+ function validatePage(page) {
13
+ unique(page.nodes.map((node) => node.sourceRef), `source reference on page ${page.id}`);
14
+ unique(page.viewports.map((viewport) => viewport.id), `viewport id on page ${page.id}`);
15
+ unique(page.states.map((state) => state.id), `state id on page ${page.id}`);
16
+ const viewportIds = new Set(page.viewports.map((viewport) => viewport.id));
17
+ const stateIds = new Set(page.states.map((state) => state.id));
18
+ page.nodes.forEach((node) => node.observations.forEach((observation) => {
19
+ if (!viewportIds.has(observation.viewportId))
20
+ throw new TypeError(`Unknown viewport ${observation.viewportId} on page ${page.id}.`);
21
+ if (!stateIds.has(observation.stateId))
22
+ throw new TypeError(`Unknown state ${observation.stateId} on page ${page.id}.`);
23
+ }));
24
+ }
25
+ /*** Rejects ambiguous identities before a Map could silently overwrite an observation. */
26
+ function unique(values, label) {
27
+ if (new Set(values).size !== values.length)
28
+ throw new TypeError(`Duplicate ${label}.`);
29
+ }
package/dist/index.d.ts CHANGED
@@ -5,6 +5,7 @@ export { filterDesignRuleCatalog } from './features/catalog/filterDesignRuleCata
5
5
  export { createDesignRuleProvider } from './features/provider/designRuleProvider';
6
6
  export { selectDesignRuleProfile } from './features/provider/selectDesignRuleProfile';
7
7
  export { recognizeWebsiteDesignProperties } from './features/recognition/recognizeWebsiteDesignProperties';
8
+ export { recognizeWebsiteDocument } from './features/recognition/recognizeWebsiteDocument';
8
9
  export { createWebsiteAssessmentRuleSet } from './features/website-assessment/createWebsiteAssessmentRuleSet';
9
10
  export { recognizeWebsiteStructure } from './features/website-recognition/recognizeWebsiteStructure';
10
11
  export type { DesignAssessmentKind, DesignRuleCatalogEntry, DesignRuleCatalogFilter, DesignRuleEvidence, DesignRulePlanningManifest, DesignRuleProfile, DesignRuleProviderManifest, DesignRuleScope, DesignRuleStatus, } from './types/designRuleCatalog';
package/dist/index.js CHANGED
@@ -5,5 +5,6 @@ export { filterDesignRuleCatalog } from './features/catalog/filterDesignRuleCata
5
5
  export { createDesignRuleProvider } from './features/provider/designRuleProvider';
6
6
  export { selectDesignRuleProfile } from './features/provider/selectDesignRuleProfile';
7
7
  export { recognizeWebsiteDesignProperties } from './features/recognition/recognizeWebsiteDesignProperties';
8
+ export { recognizeWebsiteDocument } from './features/recognition/recognizeWebsiteDocument';
8
9
  export { createWebsiteAssessmentRuleSet } from './features/website-assessment/createWebsiteAssessmentRuleSet';
9
10
  export { recognizeWebsiteStructure } from './features/website-recognition/recognizeWebsiteStructure';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ankhorage/rules-design",
3
- "version": "0.7.0",
3
+ "version": "0.8.0",
4
4
  "description": "Declarative catalog for reusable design rules.",
5
5
  "license": "MIT",
6
6
  "homepage": "https://github.com/ankhorage/rules-design#readme",
@@ -42,6 +42,8 @@
42
42
  "test": "bun test",
43
43
  "lint": "ankhorage-eslint . --max-warnings=0",
44
44
  "knip:check": "ankhorage-knip",
45
+ "test:packed-consumer": "bun test/packed-consumer.ts",
46
+ "test:php-consumer": "bun test/php-consumer.ts",
45
47
  "format": "ankhorage-prettier --write .",
46
48
  "format:check": "ankhorage-prettier --check .",
47
49
  "lint:fix": "ankhorage-eslint . --fix --max-warnings=0",