An open source design system that's fully customizable and agent ready
TypeScript
build: validate theming anatomy metadata (#5718)
Cindy Zhang039852fc059d
diff --git a/docs/architecture/component-theming-surface.md b/docs/architecture/component-theming-surface.mdindex 1d7fcf3dcc..667b99b022 100644--- a/docs/architecture/component-theming-surface.md+++ b/docs/architecture/component-theming-surface.md@@ -19,9 +19,12 @@ applies_to:packages/core/src/theme/themingTargets.test.ts,packages/core/src/theme/extensibleAxes.test.ts,packages/core/src/theme/derivedVarRegistry.test.ts,+ docs/templates/knowledge/component-spec.md,+ scripts/check-knowledge.mjs,]verified_by:[+ scripts/check-knowledge.mjs,packages/core/src/theme/themingTargets.test.ts,packages/core/src/theme/extensibleAxes.test.ts,packages/core/src/theme/derivedVarRegistry.test.ts,@@ -64,8 +67,9 @@ and explain only non-obvious rationale or exceptions.Visual props, states, and public CSS properties are capabilities of a target.They are not separate anatomy parts or separate targets. Runtime `themeProps()`-reflection, `.doc.mjs` metadata, generated types, and CLI validation describe one-public surface.+reflection, public `.doc.mjs` theming metadata, and checked component-spec+metadata describe one public surface without exposing maintainer dispositions to+consumers.## Boundaries and invariants@@ -120,15 +124,18 @@ how themes become output, or the design rationale for a component's appearance.## Owning code-- Component `.doc.mjs` `usage.anatomy[]` owns consumer-facing parts.+- Component `.doc.mjs` `usage.anatomy[]` owns the consumer-facing semantic part+ inventory and contains no theming disposition or maintainer rationale.- Component `.doc.mjs` `theming.targets[]` owns discoverable public targets andtheir public properties/states.-- Colocated component `.spec.md` files own the exact anatomy-to-target map and- any non-obvious rationale. CI validates that map against both consumer doc- sections. The map is excluded from generated consumer docs.+- A colocated component `.spec.md` `### Theming anatomy` block owns the exact,+ machine-readable anatomy-to-target dispositions. It is optional during+ migration and excluded from generated consumer docs. Nearby prose records only+ non-obvious rationale, exceptions, and links—not the exact mapping.- Runtime `themeProps()` calls emit the target and state contract.-- `themingTargets.test.ts`, `extensibleAxes.test.ts`, and- `derivedVarRegistry.test.ts` enforce the source/metadata/generated relationship.+- `scripts/check-knowledge.mjs`, `themingTargets.test.ts`,+ `extensibleAxes.test.ts`, and `derivedVarRegistry.test.ts` enforce the+ source/metadata/generated relationship.- Family contracts own shared target semantics when multiple components adoptone part contract.@@ -142,7 +149,7 @@ scope were selected by the system owner.| Invariant | Evidence | Failure signal || ---------- | ----------------------------------------------------- | ---------------------------------------------------------------------------------------------------- || INV1 | Cross-package target/documentation inventory | An exported target in a participating package is invisible to metadata or CLI validation |-| INV2, INV3 | Bidirectional anatomy-disposition/target check | A current target has no semantic part owner, or anatomy mechanically creates unnecessary targets |+| INV2, INV3 | `scripts/check-knowledge.mjs` | A current target has no semantic part owner, or anatomy mechanically creates unnecessary targets || INV4, INV5 | Component review plus rendered DOM inspection | Public target lands on non-painting plumbing or aliases a child primitive without distinct semantics || INV6 | `themingTargets.test.ts` and `extensibleAxes.test.ts` | State/variant is invisible to the owner target or becomes an unnecessary parallel target || INV7 | Metadata plus compiler registry tests | A public property lacks semantics or private expansion is duplicated in component prose/code |diff --git a/docs/templates/knowledge/component-spec.md b/docs/templates/knowledge/component-spec.mdindex 209c5ae985..9f7008acb6 100644--- a/docs/templates/knowledge/component-spec.md+++ b/docs/templates/knowledge/component-spec.md@@ -95,6 +95,29 @@ The component implements design requirements without copying their rationale.An `unsettled` representation remains a human decision; principles do not let anagent invent the answer.+### Theming anatomy++<!--+Optional during migration. When present, this block must map every exact English+anatomy name from <Name>.doc.mjs to one disposition. It is maintainer metadata:+do not copy it into ComponentDoc, generated docsite data, CLI/MCP output, or+consumer prose. Target names omit the `astryx-` prefix. Put only non-obvious+rationale or exceptions in prose below the block.+-->++<!-- anatomy-theming:v1 -->++```json+{+ "<root part>": {"target": "<target>"},+ "<inherited part>": {"inherits": "<parent-or-root-target>"},+ "<delegated part>": {+ "delegatesTo": {"owner": "component:<Owner>", "target": "<target>"}+ },+ "<unthemed part>": {"none": {"reason": "<required reason>"}}+}+```+## Family and system relationshipsFrontmatter lists only `current` family, design, architecture, and systemdiff --git a/scripts/check-knowledge.mjs b/scripts/check-knowledge.mjsindex 96efb66366..dfd2f659cc 100644--- a/scripts/check-knowledge.mjs+++ b/scripts/check-knowledge.mjs@@ -147,6 +147,244 @@ export function discoverKnowledgeRecords(root = DEFAULT_ROOT) {return records.sort();}+export function parseAnatomyThemingBlock(+ content,+ filePath = '<component spec>',+) {+ const heading = /^### Theming anatomy\s*$/gm;+ const headings = [...content.matchAll(heading)];+ if (headings.length === 0) return {mapping: null, problems: []};+ if (headings.length > 1) {+ return {+ mapping: null,+ problems: [`${filePath}: duplicate "Theming anatomy" subsection.`],+ };+ }++ const precedingSections = [+ ...content.slice(0, headings[0].index).matchAll(/^## (.+?)\s*$/gm),+ ];+ if (precedingSections.at(-1)?.[1] !== 'Design relationships') {+ return {+ mapping: null,+ problems: [+ `${filePath}: "Theming anatomy" must be a level-three subsection of "Design relationships".`,+ ],+ };+ }++ const start = headings[0].index + headings[0][0].length;+ const remainder = content.slice(start);+ const nextHeading = /^#{2,3} .+$/m.exec(remainder);+ const section =+ nextHeading == null ? remainder : remainder.slice(0, nextHeading.index);+ const blocks = [+ ...section.matchAll(+ /<!--\s*anatomy-theming:v1\s*-->\s*```json\s*\n([\s\S]*?)\n```/g,+ ),+ ];+ if (blocks.length !== 1) {+ return {+ mapping: null,+ problems: [+ `${filePath}: "Theming anatomy" must contain exactly one <!-- anatomy-theming:v1 --> JSON block.`,+ ],+ };+ }++ try {+ return {mapping: JSON.parse(blocks[0][1]), problems: []};+ } catch (error) {+ return {+ mapping: null,+ problems: [+ `${filePath}: anatomy-theming:v1 is not valid JSON (${error.message}).`,+ ],+ };+ }+}++const THEME_TARGET_NAME = /^(?!astryx-)[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;+const THEMING_DISPOSITIONS = ['target', 'inherits', 'delegatesTo', 'none'];++function exactObjectKeys(value, expected) {+ return (+ value != null &&+ typeof value === 'object' &&+ !Array.isArray(value) &&+ Object.keys(value).sort().join('\0') === [...expected].sort().join('\0')+ );+}++function isNonEmptyString(value) {+ return typeof value === 'string' && value.trim().length > 0;+}++function validateTargetName(target, where, problems) {+ if (!isNonEmptyString(target)) {+ problems.push(`${where}: target is required.`);+ } else if (!THEME_TARGET_NAME.test(target)) {+ problems.push(+ `${where}: target must omit the "astryx-" prefix and use kebab-case.`,+ );+ }+}++/**+ * Validate one parsed anatomy-theming:v1 map against the component's public+ * anatomy and target inventory.+ */+export function validateAnatomyThemingMap(+ mapping,+ contract,+ filePath = '<component spec>',+) {+ const problems = [];+ if (+ mapping == null ||+ typeof mapping !== 'object' ||+ Array.isArray(mapping)+ ) {+ return [`${filePath}: anatomy-theming:v1 must be a JSON object.`];+ }++ const declaredParts = Object.keys(mapping).sort();+ const anatomyParts = [...contract.anatomy].sort();+ const missing = anatomyParts.filter(part => !declaredParts.includes(part));+ const extra = declaredParts.filter(part => !anatomyParts.includes(part));+ if (missing.length > 0) {+ problems.push(+ `${filePath}: theming anatomy is missing ${missing.join(', ')}.`,+ );+ }+ if (extra.length > 0) {+ problems.push(+ `${filePath}: theming anatomy has unknown ${extra.join(', ')}.`,+ );+ }++ const ownedTargets = new Set();+ for (const [part, disposition] of Object.entries(mapping)) {+ const where = `${filePath}: theming anatomy ${JSON.stringify(part)}`;+ if (+ disposition == null ||+ typeof disposition !== 'object' ||+ Array.isArray(disposition)+ ) {+ problems.push(`${where} must be an object.`);+ continue;+ }++ const keys = Object.keys(disposition);+ const selected = THEMING_DISPOSITIONS.filter(key => key in disposition);+ if (selected.length !== 1 || keys.length !== 1) {+ problems.push(+ `${where} must declare exactly one of target, inherits, delegatesTo, or none.`,+ );+ continue;+ }++ const kind = selected[0];+ if (kind === 'target' || kind === 'inherits') {+ const target = disposition[kind];+ validateTargetName(target, `${where}.${kind}`, problems);+ if (+ isNonEmptyString(target) &&+ THEME_TARGET_NAME.test(target) &&+ !contract.targets.includes(target)+ ) {+ problems.push(+ `${where}.${kind}: ${JSON.stringify(target)} is not a current target in the component doc.`,+ );+ }+ if (kind === 'target') ownedTargets.add(target);+ continue;+ }++ if (kind === 'delegatesTo') {+ const delegation = disposition.delegatesTo;+ if (!exactObjectKeys(delegation, ['owner', 'target'])) {+ problems.push(+ `${where}.delegatesTo requires exactly owner and target.`,+ );+ continue;+ }+ if (+ !isNonEmptyString(delegation.owner) ||+ !/^(component:[A-Z][A-Za-z0-9]*|family:[a-z0-9]+(?:-[a-z0-9]+)*)$/.test(+ delegation.owner,+ )+ ) {+ problems.push(+ `${where}.delegatesTo.owner must be component:<Name> or family:<id>.`,+ );+ }+ validateTargetName(+ delegation.target,+ `${where}.delegatesTo.target`,+ problems,+ );+ continue;+ }++ const none = disposition.none;+ if (!exactObjectKeys(none, ['reason']) || !isNonEmptyString(none.reason)) {+ problems.push(`${where}.none requires a non-empty reason.`);+ }+ }++ for (const target of contract.targets) {+ if (!ownedTargets.has(target)) {+ problems.push(+ `${filePath}: current target ${JSON.stringify(target)} has no anatomy entry with a target disposition.`,+ );+ }+ }++ return problems;+}++function loadComponentContract(root, specPath, componentName) {+ const directory = path.dirname(specPath);+ for (const docPath of matchingFiles(directory, name =>+ name.endsWith('.doc.mjs'),+ )) {+ let mod;+ try {+ mod = require(docPath);+ } catch (error) {+ return {+ problem: `${path.relative(root, docPath)}: could not load component doc (${error.message}).`,+ };+ }+ const doc = mod.docs ?? mod.default;+ if (!doc) continue;+ const candidates = [doc, ...(doc.components ?? [])];+ const candidate = candidates.find(+ entry => entry?.name?.replace(/^XDS/, '') === componentName,+ );+ if (!candidate) continue;+ const anatomy = candidate.usage?.anatomy ?? doc.usage?.anatomy;+ if (!Array.isArray(anatomy)) {+ return {+ problem: `${path.relative(root, docPath)}: ${componentName} has no canonical English usage.anatomy.`,+ };+ }+ const targets = (candidate.theming?.targets ?? doc.theming?.targets ?? [])+ .filter(target => target.deprecatedFor == null)+ .map(target => target.className.replace(/^astryx-/, ''));+ return {+ contract: {+ anatomy: anatomy.map(part => part.name),+ targets,+ },+ };+ }+ return {+ problem: `${path.relative(root, specPath)}: no component doc for ${componentName}.`,+ };+}+function validateAgainstSchema(document,schema,@@ -424,10 +662,8 @@ export function validateKnowledgeRoot(root = DEFAULT_ROOT) {for (const absolutePath of discoverKnowledgeRecords(root)) {const filePath = path.relative(root, absolutePath);- const document = parseKnowledgeDocument(- fs.readFileSync(absolutePath, 'utf8'),- filePath,- );+ const content = fs.readFileSync(absolutePath, 'utf8');+ const document = parseKnowledgeDocument(content, filePath);const recordVersion = document.frontmatter.get('schema_version');const versionedSchema = schemas.get(recordVersion);if (!versionedSchema) {@@ -457,6 +693,27 @@ export function validateKnowledgeRoot(root = DEFAULT_ROOT) {`${filePath}: active records must use latest schema_version ${latestVersion}.`,);}+ if (document.frontmatter.get('kind') === 'component') {+ const parsed = parseAnatomyThemingBlock(content, filePath);+ problems.push(...parsed.problems);+ if (parsed.mapping != null) {+ const componentName = String(document.frontmatter.get('id') ?? '')+ .replace(/^component:/, '')+ .replace(/\/.*$/, '');+ const loaded = loadComponentContract(root, absolutePath, componentName);+ if (loaded.problem) {+ problems.push(loaded.problem);+ } else {+ problems.push(+ ...validateAnatomyThemingMap(+ parsed.mapping,+ loaded.contract,+ filePath,+ ),+ );+ }+ }+ }const id = document.frontmatter.get('id');if (id) {if (ids.has(id))diff --git a/scripts/check-knowledge.test.mjs b/scripts/check-knowledge.test.mjsindex bba323ff55..f486206eae 100644--- a/scripts/check-knowledge.test.mjs+++ b/scripts/check-knowledge.test.mjs@@ -5,7 +5,9 @@ import os from 'node:os';import path from 'node:path';import {afterEach, describe, expect, it} from 'vitest';import {+ parseAnatomyThemingBlock,parseKnowledgeDocument,+ validateAnatomyThemingMap,validateKnowledgeRoot,validateSchemaEvolution,} from './check-knowledge.mjs';@@ -98,6 +100,36 @@ function componentRecord(overrides = {}) {return `---\n${frontmatter}\n---\n\n# Button component contract\n\n${sections}\n`;}+function anatomyThemingBlock(mapping) {+ return `### Theming anatomy\n\n<!-- anatomy-theming:v1 -->\n\`\`\`json\n${JSON.stringify(mapping, null, 2)}\n\`\`\``;+}++function withAnatomyTheming(record, mapping) {+ return record.replace(+ '## Design relationships\n\nBody.',+ `## Design relationships\n\nBody.\n\n${anatomyThemingBlock(mapping)}`,+ );+}++function writeButtonDoc(directory) {+ const content = `export const docs = {+ name: 'Button',+ usage: {+ anatomy: [+ {name: 'Root', required: true, description: 'Painted surface.'},+ {name: 'Label', required: true, description: 'Visible label.'},+ {name: 'Icon', required: false, description: 'Shared icon.'},+ {name: 'Content', required: false, description: 'Consumer content.'},+ ],+ },+ theming: {+ targets: [{className: 'astryx-button'}],+ },+};\n`;+ fs.writeFileSync(path.join(directory, 'Button.doc.mjs'), content);+ return content;+}+afterEach(() => {for (const root of roots.splice(0))fs.rmSync(root, {recursive: true, force: true});@@ -129,6 +161,118 @@ describe('schema evolution', () => {});});+describe('component theming anatomy metadata', () => {+ const contract = {+ anatomy: ['Root', 'Label', 'Icon', 'Content'],+ targets: ['button'],+ };+ const valid = {+ Root: {target: 'button'},+ Label: {inherits: 'button'},+ Icon: {delegatesTo: {owner: 'component:Icon', target: 'icon'}},+ Content: {none: {reason: 'The consumer owns this content.'}},+ };++ it('parses the optional versioned JSON block under Design relationships', () => {+ expect(+ parseAnatomyThemingBlock(+ `## Design relationships\n\n${anatomyThemingBlock(valid)}`,+ ).mapping,+ ).toEqual(valid);+ expect(parseAnatomyThemingBlock('## Design relationships\n').mapping).toBe(+ null,+ );+ });++ it('rejects the structured block outside its existing level-two section', () => {+ expect(+ parseAnatomyThemingBlock(+ `## Public concepts\n\n${anatomyThemingBlock(valid)}`,+ ).problems.join('\n'),+ ).toMatch(/subsection of "Design relationships"/);+ });++ it('accepts exactly one complete disposition per documented anatomy part', () => {+ expect(validateAnatomyThemingMap(valid, contract)).toEqual([]);+ });++ it.each([+ [+ 'multiple dispositions',+ {...valid, Root: {target: 'button', inherits: 'button'}},+ /exactly one/,+ ],+ [+ 'missing delegated owner',+ {...valid, Icon: {delegatesTo: {target: 'icon'}}},+ /requires exactly owner and target/,+ ],+ [+ 'missing delegated target',+ {...valid, Icon: {delegatesTo: {owner: 'component:Icon'}}},+ /requires exactly owner and target/,+ ],+ [+ 'missing none reason',+ {...valid, Content: {none: {}}},+ /requires a non-empty reason/,+ ],+ [+ 'prefixed target',+ {...valid, Root: {target: 'astryx-button'}},+ /omit the "astryx-" prefix/,+ ],+ [+ 'non-kebab target',+ {...valid, Root: {target: 'Button_Root'}},+ /use kebab-case/,+ ],+ ])('rejects %s', (_name, mapping, expected) => {+ expect(validateAnatomyThemingMap(mapping, contract).join('\n')).toMatch(+ expected,+ );+ });++ it('requires exact anatomy names and coverage of current local targets', () => {+ const result = validateAnatomyThemingMap(+ {+ Label: {inherits: 'button'},+ Icon: {delegatesTo: {owner: 'component:Icon', target: 'icon'}},+ Content: {none: {reason: 'Consumer owned.'}},+ Unknown: {none: {reason: 'Not real.'}},+ },+ contract,+ ).join('\n');+ expect(result).toMatch(/missing Root/);+ expect(result).toMatch(/unknown Unknown/);+ expect(result).toMatch(/current target "button" has no anatomy entry/);+ });++ it('validates an opted-in spec without changing consumer doc bytes', () => {+ const root = fixtureRoot();+ const directory = path.join(root, 'packages/core/src/Button');+ fs.mkdirSync(directory);+ const consumerDoc = writeButtonDoc(directory);+ fs.writeFileSync(+ path.join(directory, 'Button.spec.md'),+ withAnatomyTheming(componentRecord(), valid),+ );++ expect(validateKnowledgeRoot(root)).toEqual([]);+ expect(+ fs.readFileSync(path.join(directory, 'Button.doc.mjs'), 'utf8'),+ ).toBe(consumerDoc);+ });++ it('keeps the block optional while existing specs migrate', () => {+ const root = fixtureRoot();+ const directory = path.join(root, 'packages/core/src/Button');+ fs.mkdirSync(directory);+ fs.writeFileSync(path.join(directory, 'Button.spec.md'), componentRecord());+ expect(validateKnowledgeRoot(root)).toEqual([]);+ });+});+describe('knowledge validation', () => {it('parses only top-level frontmatter and level-two sections', () => {const document = parseKnowledgeDocument(