@reqvire-org/ads 0.3.46 → 0.3.47

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.
Files changed (110) hide show
  1. package/README.md +21 -11
  2. package/dist/a11y.mjs +4 -2
  3. package/dist/assets.mjs +20 -15
  4. package/dist/atomic-composition.mjs +3 -2
  5. package/dist/brand-assets.mjs +48 -11
  6. package/dist/brands.mjs +82 -0
  7. package/dist/browser-audit/worker.mjs +45 -0
  8. package/dist/browser-audit.mjs +117 -0
  9. package/dist/capture/worker.mjs +1 -0
  10. package/dist/capture-store.mjs +2 -0
  11. package/dist/capture.mjs +7 -4
  12. package/dist/check.mjs +38 -8
  13. package/dist/cli.mjs +45 -10
  14. package/dist/color-values.mjs +325 -0
  15. package/dist/config.mjs +16 -2
  16. package/dist/control-padding.mjs +93 -0
  17. package/dist/design-values.mjs +3 -2
  18. package/dist/finding-rules.mjs +61 -0
  19. package/dist/foundation.mjs +17 -4
  20. package/dist/icons.mjs +107 -0
  21. package/dist/init.mjs +3 -0
  22. package/dist/mcp/apps.mjs +9 -6
  23. package/dist/mcp/drafts.mjs +3 -0
  24. package/dist/mcp/mutations.mjs +17 -1
  25. package/dist/mcp/preview-widget.bundle.js +36 -36
  26. package/dist/mcp/project-widget.bundle.js +12 -12
  27. package/dist/mcp/server.mjs +21 -9
  28. package/dist/mcp/widget.bundle.js +17 -17
  29. package/dist/palette-generated.mjs +180 -0
  30. package/dist/preview-resources.mjs +12 -3
  31. package/dist/render-color-probe.mjs +148 -0
  32. package/dist/runtime-contracts.mjs +14 -4
  33. package/dist/scenarios.mjs +1 -1
  34. package/dist/showcase/client.bundle.js +28 -28
  35. package/dist/showcase/icons.js +146 -0
  36. package/dist/showcase/index.html +2 -1
  37. package/dist/showcase/style.css +19 -2
  38. package/dist/skills/README.md +2 -1
  39. package/dist/skills/ads-break-ui/SKILL.md +6 -5
  40. package/dist/skills/ads-break-ui/references/atomic-styles.md +12 -12
  41. package/dist/skills/ads-break-ui/references/contracts.md +13 -10
  42. package/dist/skills/ads-break-ui/references/design-data.md +137 -29
  43. package/dist/skills/ads-break-ui/references/validation.md +8 -4
  44. package/dist/skills/ads-designer/SKILL.md +23 -16
  45. package/dist/skills/ads-designer/references/accessibility.md +39 -5
  46. package/dist/skills/ads-designer/references/atomic-styles.md +12 -12
  47. package/dist/skills/ads-designer/references/branding.md +37 -10
  48. package/dist/skills/ads-designer/references/cli.md +8 -2
  49. package/dist/skills/ads-designer/references/contracts.md +13 -10
  50. package/dist/skills/ads-designer/references/design-data.md +137 -29
  51. package/dist/skills/ads-designer/references/validation.md +8 -4
  52. package/dist/skills/ads-import/SKILL.md +9 -8
  53. package/dist/skills/ads-import/references/atomic-styles.md +12 -12
  54. package/dist/skills/ads-import/references/cli.md +8 -2
  55. package/dist/skills/ads-import/references/contracts.md +13 -10
  56. package/dist/skills/ads-import/references/design-data.md +137 -29
  57. package/dist/skills/ads-import/references/tokens.md +7 -3
  58. package/dist/skills/ads-import/references/validation.md +8 -4
  59. package/dist/skills/ads-motion/SKILL.md +6 -5
  60. package/dist/skills/ads-motion/references/atomic-styles.md +12 -12
  61. package/dist/skills/ads-motion/references/contracts.md +13 -10
  62. package/dist/skills/ads-motion/references/design-data.md +137 -29
  63. package/dist/skills/ads-motion/references/validation.md +8 -4
  64. package/dist/skills/ads-port/SKILL.md +6 -5
  65. package/dist/skills/ads-port/references/atomic-styles.md +12 -12
  66. package/dist/skills/ads-port/references/cli.md +8 -2
  67. package/dist/skills/ads-port/references/contracts.md +13 -10
  68. package/dist/skills/ads-port/references/design-data.md +137 -29
  69. package/dist/skills/ads-port/references/validation.md +8 -4
  70. package/dist/starters/preact/design-system/review/token-preview/TokenPreview.tsx +11 -2
  71. package/dist/starters/react/ADS.md +43 -10
  72. package/dist/starters/react/README.md +14 -9
  73. package/dist/starters/react/design-system/assets/brand/README.md +8 -3
  74. package/dist/starters/react/design-system/assets/glyphs/README.md +4 -1
  75. package/dist/starters/react/design-system/components/Content/Icon/Icon.ads.fixture.ts +6 -1
  76. package/dist/starters/react/design-system/components/Content/Icon/Icon.ads.scenario.tsx +3 -2
  77. package/dist/starters/react/design-system/components/Content/Icon/README.md +2 -1
  78. package/dist/starters/react/design-system/components/Content/Logo/Logo.tsx +3 -9
  79. package/dist/starters/react/design-system/components/Content/Logo/README.md +4 -2
  80. package/dist/starters/react/design-system/controllers/Palette/Palette.ts +164 -0
  81. package/dist/starters/react/design-system/index.ts +3 -0
  82. package/dist/starters/react/design-system/review/brand-preview/BrandPreview.tsx +2 -5
  83. package/dist/starters/react/design-system/review/token-preview/TokenPreview.tsx +11 -2
  84. package/dist/starters/react/design-system/styles.css +1 -0
  85. package/dist/starters/react/design-system/tokens/base.css +8 -5
  86. package/dist/starters/react/design-system/tokens/colors.css +167 -175
  87. package/dist/starters/react/design-system/tokens/elevation.css +14 -21
  88. package/dist/starters/react/design-system/tokens/themes.generated.css +142 -0
  89. package/dist/starters/react/design-system/tokens/themes.generated.ts +402 -0
  90. package/dist/style-boundaries.mjs +2 -1
  91. package/dist/themes-generated.mjs +150 -0
  92. package/dist/themes-watch.mjs +42 -0
  93. package/dist/themes.mjs +214 -63
  94. package/dist/token-export.mjs +22 -11
  95. package/dist/token-policy.mjs +2 -1
  96. package/dist/token-quality.mjs +28 -25
  97. package/dist/tokens.mjs +27 -32
  98. package/dist/validation.mjs +18 -1
  99. package/dist/verification/browser.mjs +14 -3
  100. package/docs/ADS.md +41 -27
  101. package/docs/ARCHITECTURE.md +49 -22
  102. package/docs/CACHING.md +2 -3
  103. package/docs/CHANGELOG.md +97 -13
  104. package/docs/CONTRACTS.md +13 -10
  105. package/docs/GUIDE.md +89 -21
  106. package/docs/MCP.md +35 -25
  107. package/docs/benchmarks/bun-previews.md +5 -5
  108. package/docs/benchmarks/{gidi-preview-memory.md → preview-memory.md} +14 -12
  109. package/docs/benchmarks/turbo-poc.md +24 -6
  110. package/package.json +2 -1
package/dist/themes.mjs CHANGED
@@ -1,8 +1,13 @@
1
1
  import selectorParser from "postcss-selector-parser";
2
+ import valueParser from "postcss-value-parser";
3
+ import { findingSeverity } from "./finding-rules.mjs";
2
4
 
3
- // A theme is a named set of token values: roles keep their names, values change. The first
4
- // declared theme is the default and lives on :root; every other theme overrides values under
5
- // [data-theme="<name>"], on the document root or on any element (a dark section in a light page).
5
+ // A theme is a named set of token values: roles keep their names, values change. A token that
6
+ // differs per theme is written as one half per declared theme, plain values on :root (and on
7
+ // [data-brand="<name>"] for a brand): --color-accent-9-light, --color-accent-9-dark. ADS
8
+ // generates themes.generated.css from the halves: one switch per theme on [data-theme="<name>"]
9
+ // and a resolver that picks the active theme's half on every themed or branded element, so
10
+ // themes and brands nest at any depth, each following its nearest ancestor.
6
11
 
7
12
  export const defaultThemes = [{ name: "light", scheme: "light" }, { name: "dark", scheme: "dark" }];
8
13
 
@@ -22,85 +27,231 @@ export function validateThemes(themes) {
22
27
  }
23
28
 
24
29
  const cache = new Map();
25
- /** What a token definition's scope applies to: every theme ({ base }), named themes
26
- * ({ themes }), or null for conditions (@media) and selectors that are not themes. */
27
- export function scopeTheme(scope) {
28
- if (cache.has(scope)) return cache.get(scope);
29
- let result = null;
30
- if (!scope.includes("@") && !scope.includes(" > ")) {
30
+ const rootNode = node => node.type === "pseudo" && node.value.toLowerCase() === ":root" || node.type === "tag" && node.value.toLowerCase() === "html";
31
+ const unquote = value => value.replace(/^["']|["']$/g, "");
32
+
33
+ /** Where a token declaration applies: the default brand ({ kind: "root" }: :root or html, or the
34
+ * default brand's [data-brand]), one brand ({ kind: "brand", brand }), the old theme form
35
+ * ({ kind: "old" }: a [data-theme] value block, a prefers-color-scheme block, a valueless or
36
+ * combined [data-brand]), or anything else ({ kind: "conditional" }: @media and other selectors). */
37
+ export function classifyScope(scope, defaultBrand) {
38
+ const key = `${defaultBrand ?? ""}\0${scope}`;
39
+ if (cache.has(key)) return cache.get(key);
40
+ let result;
41
+ if (/data-theme|prefers-color-scheme/i.test(scope)) result = { kind: "old" };
42
+ else if (scope.includes("@") || scope.includes(" > ")) result = { kind: "conditional" };
43
+ else {
31
44
  try {
32
- let base = false, other = false;
33
- const themes = new Set();
45
+ let old = false, other = false;
46
+ const brands = [];
34
47
  selectorParser(root => {
35
48
  for (const selector of root.nodes) {
36
- const nodes = selector.nodes.filter(node => node.type !== "comment");
37
- const rootNode = node => node.type === "pseudo" && node.value.toLowerCase() === ":root" || node.type === "tag" && node.value.toLowerCase() === "html";
38
- const themeNode = node => node.type === "attribute" && node.attribute === "data-theme" && (!node.operator || node.operator === "=");
39
- const rest = nodes.filter(node => !rootNode(node));
40
- if (rest.length === 0 && nodes.length === 1) base = true;
41
- else if (rest.length === 1 && themeNode(rest[0]) && nodes.length <= 2) {
42
- if (rest[0].value === undefined) base = true;
43
- else themes.add(rest[0].value.replace(/^["']|["']$/g, ""));
44
- } else other = true;
49
+ let brand = null;
50
+ for (const node of selector.nodes) {
51
+ if (node.type === "comment" || rootNode(node)) continue;
52
+ if (node.type === "attribute" && node.attribute === "data-brand") {
53
+ if (node.value === undefined || node.operator !== "=" || brand !== null) old = true;
54
+ else brand = unquote(node.value);
55
+ continue;
56
+ }
57
+ if (node.type === "combinator" && /data-brand/.test(scope)) old = true;
58
+ other = true;
59
+ }
60
+ brands.push(brand === defaultBrand ? null : brand);
45
61
  }
46
62
  }).processSync(scope);
47
- if (!other) result = base ? { base: true, themes: [...themes] } : themes.size ? { base: false, themes: [...themes] } : null;
48
- } catch { result = null; }
63
+ result = old ? { kind: "old" } : other ? { kind: "conditional" } : new Set(brands).size > 1 ? { kind: "old" }
64
+ : brands[0] === null ? { kind: "root" } : { kind: "brand", brand: brands[0] };
65
+ } catch { result = { kind: "conditional" }; }
49
66
  }
50
- cache.set(scope, result);
67
+ cache.set(key, result);
51
68
  return result;
52
69
  }
53
70
 
54
- /** Theme names a scope mentions, conditional or not, for the declaration check. */
55
- export const mentionedThemes = scope => [...scope.matchAll(/data-theme\s*=\s*["']?([\w-]+)/g)].map(match => match[1]);
71
+ const plainScope = where => where.kind === "root" || where.kind === "brand";
72
+
73
+ /** Token definitions from the token sheets' custom property declarations ({ prop, value, file,
74
+ * line, column, scope }, in source order). A name ending in a declared theme's name is a half
75
+ * when another theme's half of the same token exists: --x-light and --x-dark form the themed
76
+ * token --x, whose definitions carry their theme. Definitions carry their brand (null for the
77
+ * default brand); a half's value names other halves of its own theme by their token name, and
78
+ * keeps the authored text and property. */
79
+ export function buildTokens(declarations, { themes = defaultThemes, brands = [] } = {}) {
80
+ const names = themes.map(theme => theme.name).sort((a, b) => b.length - a.length);
81
+ const split = prop => {
82
+ if (themes.length < 2) return null;
83
+ for (const name of names) if (prop.endsWith(`-${name}`) && prop.length > name.length + 3) return { base: prop.slice(0, -name.length - 1), theme: name };
84
+ return null;
85
+ };
86
+ const entries = declarations.map(declaration => ({ ...declaration, where: classifyScope(declaration.scope, brands[0]?.name) }));
87
+ const halves = new Map();
88
+ for (const entry of entries) {
89
+ const half = plainScope(entry.where) && split(entry.prop);
90
+ if (!half) continue;
91
+ if (!halves.has(half.base)) halves.set(half.base, new Set());
92
+ halves.get(half.base).add(half.theme);
93
+ }
94
+ const themed = new Set([...halves].filter(([, set]) => set.size > 1).map(([base]) => base));
95
+ const halfOf = prop => { const half = split(prop); return half && themed.has(half.base) ? half : null; };
96
+ const normalize = (value, theme) => {
97
+ const parsed = valueParser(value);
98
+ parsed.walk(node => {
99
+ if (node.type !== "function" || node.value !== "var") return;
100
+ const word = node.nodes.find(child => child.type === "word");
101
+ const half = word && halfOf(word.value);
102
+ if (half?.theme === theme) word.value = half.base;
103
+ });
104
+ return parsed.toString();
105
+ };
106
+ const tokens = new Map();
107
+ for (const entry of entries) {
108
+ const half = halfOf(entry.prop), name = half ? half.base : entry.prop;
109
+ const definition = { file: entry.file, line: entry.line, column: entry.column, scope: entry.scope, value: half ? normalize(entry.value, half.theme) : entry.value,
110
+ theme: half?.theme ?? null, brand: entry.where.kind === "brand" ? entry.where.brand : null,
111
+ ...(half ? { property: entry.prop, authored: entry.value } : {}),
112
+ ...(entry.where.kind === "conditional" ? { conditional: true } : entry.where.kind === "old" ? { conditional: true, old: true } : {}) };
113
+ if (!tokens.has(name)) tokens.set(name, []);
114
+ tokens.get(name).push(definition);
115
+ }
116
+ return [...tokens].sort(([a], [b]) => a.localeCompare(b)).map(([name, definitions]) => ({ name, ...(themed.has(name) ? { themed: true } : {}), definitions }));
117
+ }
118
+
119
+ const applies = definition => !definition.conditional;
120
+
121
+ /** A token's definition where a theme and a brand apply: the brand's own one, else the default
122
+ * brand's; within a brand the theme's half, else the single value. Undefined brand = default. */
123
+ export function contextDefinition(token, { theme, brand } = {}) {
124
+ const matches = definition => applies(definition) && (definition.theme === null || definition.theme === theme);
125
+ return (brand !== undefined && brand !== null ? token.definitions.findLast(definition => definition.brand === brand && matches(definition)) : undefined)
126
+ ?? token.definitions.findLast(definition => definition.brand === null && matches(definition));
127
+ }
128
+
129
+ /** A token's default-brand definition: its single value, else its half for the named theme
130
+ * (the first half when no theme is named). */
131
+ export function baseDefinition(token, theme) {
132
+ const own = token.definitions.filter(definition => applies(definition) && definition.brand === null);
133
+ return own.findLast(definition => definition.theme === null) ?? own.find(definition => theme === undefined || definition.theme === theme);
134
+ }
56
135
 
57
- /** A token's definition for every theme, if any. */
58
- export const baseDefinition = token => token.definitions.findLast(definition => scopeTheme(definition.scope)?.base);
136
+ /** A token's default-brand definition in one theme. */
137
+ export const themeDefinition = (token, theme) => contextDefinition(token, { theme });
59
138
 
60
- /** A token's definition in one theme: its own override, else the base one. */
61
- export function themeDefinition(token, theme) {
62
- return token.definitions.findLast(definition => { const applies = scopeTheme(definition.scope); return applies && !applies.base && applies.themes.includes(theme); })
63
- ?? baseDefinition(token);
139
+ /** Every token and half by name in one theme and brand, each with its authored value, so
140
+ * var() references resolve the way the browser does there. */
141
+ export function contextValues(tokens, { theme, brand, themes }) {
142
+ const values = new Map();
143
+ for (const token of tokens) {
144
+ const own = contextDefinition(token, { theme, brand });
145
+ if (own) values.set(token.name, { ...own, value: own.authored ?? own.value });
146
+ if (!token.themed) continue;
147
+ for (const { name } of themes) {
148
+ const half = contextDefinition(token, { theme: name, brand });
149
+ if (half) values.set(`${token.name}-${name}`, { ...half, value: half.authored ?? half.value });
150
+ }
151
+ }
152
+ return values;
64
153
  }
65
154
 
66
- const colorLiteral = /^(?:#[\da-f]{3,8}|(?:rgba?|hsla?|hwb|lab|lch|oklab|oklch|color)\()/i;
155
+ /** A value with its single var() aliases followed in one context; null when unresolved. */
156
+ export function resolveValue(values, name, seen = new Set()) {
157
+ if (seen.has(name)) return null;
158
+ const value = values.get(name)?.value?.trim();
159
+ const reference = value?.match(/^var\(\s*(--[\w-]+)\s*(?:,([^)]*))?\)$/);
160
+ if (!reference) return value ?? null;
161
+ return values.has(reference[1]) ? resolveValue(values, reference[1], new Set([...seen, name])) : reference[2]?.trim() || null;
162
+ }
67
163
 
68
- /** Themes are declared, add no roles of their own, and override whole color ramps. */
164
+ export const referencedTokens = value => {
165
+ const names = [];
166
+ valueParser(value).walk(node => { if (node.type === "function" && node.value === "var") { const word = node.nodes.find(child => child.type === "word"); if (word?.value.startsWith("--")) names.push(word.value); } });
167
+ return names;
168
+ };
169
+
170
+ /** Tokens that follow the theme: themed tokens and every default single value that refers to
171
+ * one, directly or through other tokens. The generated resolver re-resolves them per element. */
172
+ export function themeDependents(tokens) {
173
+ const dependent = new Set(tokens.filter(token => token.themed).map(token => token.name));
174
+ for (let changed = true; changed;) {
175
+ changed = false;
176
+ for (const token of tokens) {
177
+ if (dependent.has(token.name)) continue;
178
+ const base = baseDefinition(token);
179
+ if (base && base.theme === null && referencedTokens(base.value).some(name => dependent.has(name))) { dependent.add(token.name); changed = true; }
180
+ }
181
+ }
182
+ return dependent;
183
+ }
184
+
185
+ export const nameList = names => names.length === 1 ? names[0] : `${names.length} tokens (${names.slice(0, 3).join(", ")}${names.length > 3 ? ", …" : ""})`;
186
+
187
+ /** The theme form: old [data-theme] value blocks are errors; a themed token has a default half
188
+ * for every declared theme, only halves, and halves that refer to other halves. */
69
189
  export function themeFindings(tokens, themes, { dsDir } = {}) {
70
- const declared = new Set(themes.map(theme => theme.name));
71
190
  const diagnostics = [], advisories = [];
72
- const warn = (rule, at, message, names) => advisories.push({ rule, severity: "warning", file: at.file, line: at.line, column: at.column, ...(names ? { tokens: names } : {}), guidanceUri: "ads://guides/tokens", message });
73
- const reported = new Set();
74
- for (const token of tokens) for (const definition of token.definitions) for (const name of mentionedThemes(definition.scope)) {
75
- if (declared.has(name) || reported.has(`${definition.file}:${definition.line}:${name}`)) continue;
76
- reported.add(`${definition.file}:${definition.line}:${name}`);
77
- diagnostics.push({ rule: "theme-undeclared", file: definition.file, line: definition.line, column: definition.column, message: `${token.name} is set for theme "${name}", which ds.config.json does not declare (themes: ${[...declared].join(", ")}). Declare it or fix the name.` });
191
+ const error = (rule, at, message, names) => diagnostics.push({ rule, file: at.file, line: at.line, column: at.column, ...(names ? { tokens: names } : {}), message });
192
+ const finding = (rule, at, message, names) => (findingSeverity(rule) === "error" ? diagnostics : advisories).push({ rule, severity: findingSeverity(rule), file: at.file, line: at.line, column: at.column, ...(names ? { tokens: names } : {}), guidanceUri: "ads://guides/tokens", message });
193
+ // One finding per old rule, naming what it sets.
194
+ const old = new Map();
195
+ for (const token of tokens) for (const definition of token.definitions.filter(definition => definition.old)) {
196
+ const key = `${definition.file}\0${definition.scope}`;
197
+ if (!old.has(key)) old.set(key, { at: definition, names: [] });
198
+ old.get(key).names.push(token.name);
78
199
  }
79
- for (const token of tokens) {
80
- if (baseDefinition(token)) continue;
81
- const themed = token.definitions.find(definition => scopeTheme(definition.scope)?.themes.length);
82
- if (themed) warn("theme-new-token", themed, `${token.name} exists only in a theme; every theme shares one set of roles, so define it for all themes and change only its value per theme.`, [token.name]);
200
+ for (const { at, names } of [...old.values()].sort((a, b) => a.at.file.localeCompare(b.at.file) || a.at.line - b.at.line)) {
201
+ const theme = at.scope.match(/data-theme\s*=\s*["']?([\w-]+)/)?.[1] ?? (/prefers-color-scheme\s*:\s*dark/.test(at.scope) ? "dark" : themes[1]?.name ?? themes[0].name);
202
+ error("theme-old-form", at, `Old theme form: ${at.scope} sets ${nameList(names)}. Write per-theme halves on :root (or [data-brand="<name>"]) instead, such as ${names[0]}-${theme}; ADS generates the theme switches.`, names);
83
203
  }
84
- // A theme that redefines part of a color ramp mixes two ramps in one theme.
85
- const ramps = new Map();
86
- for (const token of tokens) {
87
- const match = token.name.match(/^(--[\w-]+?)-(\d+)$/), base = baseDefinition(token);
88
- if (!match || !base || !colorLiteral.test(base.value.trim())) continue;
89
- if (!ramps.has(match[1])) ramps.set(match[1], []);
90
- ramps.get(match[1]).push(token);
204
+ if (themes.length < 2) return { diagnostics, advisories };
205
+ const dependent = themeDependents(tokens);
206
+ for (const token of tokens.filter(token => token.themed)) {
207
+ const own = token.definitions.filter(definition => applies(definition) && definition.brand === null);
208
+ const single = own.find(definition => definition.theme === null);
209
+ if (single) error("theme-half-conflict", single, `${token.name} is set both as one value and as per-theme halves (${token.definitions.find(definition => definition.property)?.property}, …); keep only the halves.`, [token.name]);
210
+ const missing = own.length ? themes.filter(theme => !own.some(definition => definition.theme === theme.name)).map(theme => theme.name) : [];
211
+ if (missing.length) error("theme-coverage", own.find(definition => definition.theme !== null) ?? own[0], `${token.name} has no ${missing.map(name => `${token.name}-${name}`).join(", ")} on :root; a themed token needs a half for every declared theme, or it is unset in ${missing.join(", ")}.`, [token.name]);
91
212
  }
92
- for (const theme of themes.slice(1)) {
93
- const own = token => token.definitions.find(definition => { const applies = scopeTheme(definition.scope); return applies && !applies.base && applies.themes.includes(theme.name); });
94
- if (!tokens.some(own)) {
95
- if (dsDir) warn("theme-empty", { file: dsDir, line: 1, column: 1 }, `Theme "${theme.name}" is declared but sets no token values; give it values under [data-theme="${theme.name}"] or remove it from ds.config.json.`);
96
- continue;
97
- }
98
- for (const [ramp, steps] of ramps) {
99
- const set = steps.filter(own);
100
- if (!set.length || set.length === steps.length) continue;
101
- const missing = steps.filter(step => !own(step)).map(step => step.name).sort((a, b) => Number(a.match(/\d+$/)[0]) - Number(b.match(/\d+$/)[0]));
102
- warn("theme-coverage", own(set[0]), `Theme "${theme.name}" sets ${set.length} of ${steps.length} ${ramp}-* steps; it also needs ${missing.join(", ")}, or the ramp mixes two themes.`, missing);
103
- }
213
+ // A half is resolved where it is declared, on :root or a brand: it names halves, not tokens that follow the theme.
214
+ const byName = new Map(tokens.map(token => [token.name, token]));
215
+ // The half a theme-following alias stands for: --accent → --color-accent-9 → --color-accent-9-dark.
216
+ const halfFor = (name, theme, seen = new Set()) => {
217
+ const token = byName.get(name);
218
+ if (token?.themed) return `${name}-${theme}`;
219
+ const alias = !seen.has(name) && baseDefinition(token ?? { definitions: [] })?.value.trim().match(/^var\(\s*(--[\w-]+)\s*\)$/)?.[1];
220
+ return alias ? halfFor(alias, theme, new Set([...seen, name])) : null;
221
+ };
222
+ for (const token of tokens.filter(token => token.themed)) for (const definition of token.definitions.filter(definition => applies(definition) && definition.authored)) {
223
+ const wrong = referencedTokens(definition.authored).filter(name => dependent.has(name));
224
+ if (wrong.length) error("theme-half-reference", definition, `${definition.property} refers to ${wrong.join(", ")}, which follows the theme; a half is resolved where it is declared, so refer to ${wrong.map(name => halfFor(name, definition.theme) ?? `halves of ${name}`).join(", ")}.`, [token.name]);
104
225
  }
226
+ // A lone half-like name: the other themes' halves are missing, so it is a plain token.
227
+ const declared = new Set(tokens.map(token => token.name));
228
+ for (const token of tokens.filter(token => !token.themed)) {
229
+ const theme = themes.slice(1).find(theme => token.name.endsWith(`-${theme.name}`));
230
+ const base = theme && token.name.slice(0, -theme.name.length - 1);
231
+ const at = token.definitions.find(applies);
232
+ if (base && at && !declared.has(base)) finding("theme-new-token", at, `${token.name} reads as the ${theme.name} half of ${base}, but no other theme gives ${base}; add ${themes.filter(item => item !== theme).map(item => `${base}-${item.name}`).join(", ")} on :root, or rename it.`, [token.name]);
233
+ }
234
+ // While the old form remains, theme-old-form already names what to write.
235
+ if (!tokens.some(token => token.themed) && !old.size && dsDir) for (const theme of themes.slice(1)) finding("theme-empty", { file: dsDir, line: 1, column: 1 }, `Theme "${theme.name}" is declared but no token has a ${theme.name} half; give the tokens that change per theme halves such as --color-accent-9-${themes[0].name} and --color-accent-9-${theme.name}, or remove it from ds.config.json.`);
105
236
  return { diagnostics, advisories };
106
237
  }
238
+
239
+ /** Whether a component/pattern selector reads the theme or brand from an ancestor or the root
240
+ * ([data-theme="dark"] &, :root[data-theme="dark"] &, :is([data-brand="acme"]) &): such a
241
+ * selector matches the outermost themed ancestor, not the nearest section, so it is an error. */
242
+ export function themeAncestorSelector(selector) {
243
+ let found = false;
244
+ try {
245
+ selectorParser(root => root.walkAttributes(node => {
246
+ if (!["data-theme", "data-brand"].includes(node.attribute)) return;
247
+ // The selector's own subject compound (&[data-theme="dark"]) is the section itself.
248
+ let top = node;
249
+ while (top.parent && top.parent.type !== "root") top = top.parent;
250
+ const compound = top.nodes, index = compound.indexOf(node);
251
+ const own = index >= 0 && !compound.slice(index).some(part => part.type === "combinator")
252
+ && !compound.some(part => part.type === "pseudo" && part.value.toLowerCase() === ":root");
253
+ if (!own) found = true;
254
+ })).processSync(selector);
255
+ } catch { /* CSS syntax diagnostics are owned by the parser/build. */ }
256
+ return found;
257
+ }
@@ -1,11 +1,12 @@
1
1
  import { inspectTokens } from "./tokens.mjs";
2
2
  import { parseColor } from "./token-quality.mjs";
3
- import { baseDefinition, themeDefinition } from "./themes.mjs";
3
+ import { contextDefinition, contextValues, resolveValue } from "./themes.mjs";
4
4
 
5
5
  // The W3C Design Tokens Community Group format (draft): JSON groups of tokens with $value,
6
6
  // $type and {group.token} references. The format has no themes yet: a document holds one
7
- // theme's values, and the other definitions travel in this tool's $extensions entry, as do
8
- // CSS values the format cannot express.
7
+ // theme's (and one brand's) values, and the other themes' and brands' values travel in this
8
+ // tool's $extensions entry (values, keyed "dark", "acme" or "acme/dark"), as do CSS values the
9
+ // format cannot express.
9
10
  const extension = "org.reqvire.ads";
10
11
 
11
12
  /** A token's path in the export: its family, then the rest of its name. */
@@ -37,19 +38,29 @@ function typed(name, value) {
37
38
  return null;
38
39
  }
39
40
 
40
- /** The project's tokens as one DTCG document, with the values of one theme (default: the first). */
41
- export function exportTokensDtcg(directory, { theme } = {}) {
42
- const { tokens, themes } = inspectTokens(directory);
41
+ /** The project's tokens as one DTCG document, with the values of one theme and one brand
42
+ * (default: the first of each). */
43
+ export function exportTokensDtcg(directory, { theme, brand } = {}) {
44
+ const { tokens, themes, brands = [] } = inspectTokens(directory);
43
45
  if (theme !== undefined && !themes.some(item => item.name === theme)) throw new Error(`Unknown theme "${theme}"; the project declares ${themes.map(item => item.name).join(", ")}.`);
46
+ if (brand !== undefined && !brands.some(item => item.name === brand)) throw new Error(`Unknown brand "${brand}"; ${brands.length ? `the project declares ${brands.map(item => item.name).join(", ")}` : "the project declares no brands"}.`);
47
+ const selected = theme ?? themes[0].name, own = brand === brands[0]?.name ? undefined : brand;
48
+ const names = new Set(tokens.map(token => token.name));
49
+ let values;
44
50
  const document = {};
45
51
  for (const token of tokens) {
46
- const base = theme === undefined ? baseDefinition(token) : themeDefinition(token, theme);
52
+ const base = contextDefinition(token, { theme: selected, brand: own });
47
53
  if (!base) continue;
48
- const entry = typed(token.name, base.value) ?? { $value: base.value.trim() };
49
- if (!("$type" in entry) && !entry.$value.toString().startsWith("{")) entry.$extensions = { [extension]: { css: base.value.trim() } };
54
+ // A half that names another theme's half has no DTCG alias; export its resolved value.
55
+ const alias = base.value.trim().match(/^var\(\s*(--[\w-]+)\s*\)$/)?.[1];
56
+ const value = alias && !names.has(alias) ? resolveValue(values ??= contextValues(tokens, { theme: selected, brand: own, themes }), token.name) ?? base.value : base.value;
57
+ const entry = typed(token.name, value) ?? { $value: value.trim() };
58
+ if (!("$type" in entry) && !entry.$value.toString().startsWith("{")) entry.$extensions = { [extension]: { css: value.trim() } };
50
59
  if (token.meaning) entry.$description = token.meaning;
51
- const themes = Object.fromEntries(token.definitions.filter(definition => definition !== base).map(definition => [definition.scope, (typed(token.name, definition.value) ?? { $value: definition.value.trim() }).$value]));
52
- if (Object.keys(themes).length) entry.$extensions = { ...entry.$extensions, [extension]: { ...entry.$extensions?.[extension], scopes: themes } };
60
+ // The other contexts: a theme ("dark"), a brand ("acme") or both ("acme/dark"), or a condition.
61
+ const label = definition => definition.conditional ? definition.scope : [definition.brand, definition.theme].filter(Boolean).join("/") || "default";
62
+ const others = Object.fromEntries(token.definitions.filter(definition => definition !== base).map(definition => [label(definition), (typed(token.name, definition.value) ?? { $value: definition.value.trim() }).$value]));
63
+ if (Object.keys(others).length) entry.$extensions = { ...entry.$extensions, [extension]: { ...entry.$extensions?.[extension], values: others } };
53
64
  const [group, key] = tokenPath(token.name);
54
65
  document[group] ??= {};
55
66
  document[group][key] = entry;
@@ -9,7 +9,8 @@ export function isSharedToken(name) {
9
9
  || tokenContract.naming.prefixes.some((prefix) => name.startsWith(prefix) && name.length > prefix.length);
10
10
  }
11
11
 
12
- export const foundationFiles = ["fonts.css", "colors.css", "typography.css", "spacing.css", "elevation.css", "base.css"];
12
+ // The foundation sheets in import order; themes.generated.css comes last, after every sheet it re-applies.
13
+ export const foundationFiles = ["fonts.css", "colors.css", "typography.css", "spacing.css", "elevation.css", "base.css", "themes.generated.css"];
13
14
 
14
15
  /** The foundation entry accepts only a single, unconditional local import. */
15
16
  export function foundationImportTarget(node, file) {
@@ -1,7 +1,8 @@
1
- import { defaultThemes, themeDefinition } from "./themes.mjs";
1
+ import { contextValues, defaultThemes, resolveValue } from "./themes.mjs";
2
+ import { findingSeverity } from "./finding-rules.mjs";
2
3
 
3
4
  /** Accessibility and rhythm reviews of token values: WCAG contrast between the roles that
4
- * meet on screen, in every theme, and spacing steps on the 2 px grid. Both are advisories. */
5
+ * meet on screen, in every theme, and spacing steps on the 2 px grid. Both are errors. */
5
6
 
6
7
  const named = { white: [255, 255, 255, 1], black: [0, 0, 0, 1] };
7
8
 
@@ -56,28 +57,30 @@ function contrastPairs(names) {
56
57
  return pairs.filter(([foreground, background]) => names.has(foreground) && names.has(background));
57
58
  }
58
59
 
59
- export function tokenContrastAdvisories(tokens, themes = defaultThemes) {
60
- const byName = new Map(tokens.map(token => [token.name, token]));
61
- const definition = (name, theme) => byName.has(name) ? themeDefinition(byName.get(name), theme) : undefined;
62
- // A theme value follows var() references, each resolved in the same theme.
63
- const resolve = (name, theme, seen = new Set()) => {
64
- if (seen.has(name)) return null;
65
- const value = definition(name, theme)?.value?.trim();
66
- const reference = value?.match(/^var\(\s*(--[\w-]+)\s*(?:,[^)]*)?\)$/);
67
- return reference ? resolve(reference[1], theme, new Set([...seen, name])) : value ?? null;
68
- };
60
+ export function tokenContrastAdvisories(tokens, themes = defaultThemes, brands = []) {
61
+ const names = new Set(tokens.map(token => token.name));
69
62
  const advisories = [];
63
+ const pairs = contrastPairs(names);
64
+ // Every brand in every theme; a brand other than the default reports only the pairs it changes.
70
65
  for (const { name: scope } of themes) {
71
- for (const [foreground, background, minimum] of contrastPairs(new Set(byName.keys()))) {
72
- const front = parseColor(resolve(foreground, scope) ?? ""), back = parseColor(resolve(background, scope) ?? "");
73
- if (!front || !back) continue;
74
- const ratio = contrastRatio(front, back[3] < 1 ? over(back, [255, 255, 255, 1]) : back);
75
- if (ratio + 1e-9 >= minimum) continue;
76
- const at = definition(foreground, scope);
77
- if (!at) continue;
78
- const { file, line, column } = at;
79
- advisories.push({ rule: "token-contrast", severity: "warning", file, line, column, tokens: [foreground, background], guidanceUri: "ads://guides/tokens",
80
- message: `${foreground} on ${background} is ${ratio.toFixed(2)}:1 in the ${scope} theme; ${minimum === 4.5 ? "text needs 4.5:1 (WCAG 1.4.3)" : "focus indicators and control borders need 3:1 (WCAG 1.4.11)"}.` });
66
+ const defaults = contextValues(tokens, { theme: scope, themes });
67
+ for (const brand of brands.length ? brands.map(item => item.name) : [undefined]) {
68
+ const own = brand === undefined || brand === brands[0].name;
69
+ const values = own ? defaults : contextValues(tokens, { theme: scope, brand, themes });
70
+ for (const [foreground, background, minimum] of pairs) {
71
+ const fore = resolveValue(values, foreground), backValue = resolveValue(values, background);
72
+ const front = parseColor(fore ?? ""), back = parseColor(backValue ?? "");
73
+ if (!front || !back) continue;
74
+ if (!own && fore === resolveValue(defaults, foreground) && backValue === resolveValue(defaults, background)) continue;
75
+ const ratio = contrastRatio(front, back[3] < 1 ? over(back, [255, 255, 255, 1]) : back);
76
+ if (ratio + 1e-9 >= minimum) continue;
77
+ const at = values.get(foreground);
78
+ if (!at) continue;
79
+ const { file, line, column } = at;
80
+ const where = own ? `the ${scope} theme` : `the ${scope} theme of brand "${brand}"`;
81
+ advisories.push({ rule: "token-contrast", severity: findingSeverity("token-contrast"), file, line, column, tokens: [foreground, background], guidanceUri: "ads://guides/tokens",
82
+ message: `${foreground} on ${background} is ${ratio.toFixed(2)}:1 in ${where}; ${minimum === 4.5 ? "text needs 4.5:1 (WCAG 1.4.3)" : "focus indicators and control borders need 3:1 (WCAG 1.4.11)"}.` });
83
+ }
81
84
  }
82
85
  }
83
86
  return advisories;
@@ -96,13 +99,13 @@ export function tokenRhythmAdvisories(tokens) {
96
99
  for (const token of tokens) {
97
100
  const step = token.name.match(/^--space-(\d+)$/)?.[1];
98
101
  if (step === undefined) continue;
99
- for (const { file, line, column, value, scope } of token.definitions) {
102
+ for (const { file, line, column, value, scope, property } of token.definitions) {
100
103
  const size = pixels(value);
101
104
  if (size === null) continue;
102
105
  const expected = Number(step) * 2;
103
106
  if (size % 2 === 0 && size === expected) continue;
104
- advisories.push({ rule: "token-rhythm", severity: "warning", file, line, column, tokens: [token.name], guidanceUri: "ads://guides/tokens",
105
- message: `${token.name} is ${size}px${scope === ":root" ? "" : ` in ${scope}`}; the spacing scale is --space-N = N × 2 px (${expected}px), on a 2 px grid.` });
107
+ advisories.push({ rule: "token-rhythm", severity: findingSeverity("token-rhythm"), file, line, column, tokens: [token.name], guidanceUri: "ads://guides/tokens",
108
+ message: `${token.name} is ${size}px${property ? ` as ${property}` : ""}${scope === ":root" ? "" : ` in ${scope}`}; the spacing scale is --space-N = N × 2 px (${expected}px), on a 2 px grid.` });
106
109
  }
107
110
  }
108
111
  return advisories;
package/dist/tokens.mjs CHANGED
@@ -1,7 +1,9 @@
1
1
  import { readFileSync } from "node:fs";
2
2
  import { tokenContrastAdvisories, tokenRhythmAdvisories } from "./token-quality.mjs";
3
3
  import { a11yTokenAdvisories } from "./a11y.mjs";
4
- import { scopeTheme, themeFindings } from "./themes.mjs";
4
+ import { buildTokens, contextValues, themeFindings } from "./themes.mjs";
5
+ import { generatedThemesFile, themesCssDiagnostics } from "./themes-generated.mjs";
6
+ import { brandFindings } from "./brands.mjs";
5
7
  import path from "node:path";
6
8
  import postcss from "postcss";
7
9
  import valueParser from "postcss-value-parser";
@@ -10,6 +12,7 @@ import { foundationFiles, isSharedToken, tokenContract } from "./token-policy.mj
10
12
  import { dimensionValue, numericCssUnit } from "./css-values.mjs";
11
13
  import { checkComponentVariable } from "./boundaries.mjs";
12
14
  import { tokenOverlapAdvisories } from "./design-values.mjs";
15
+ import { routeFindings } from "./finding-rules.mjs";
13
16
 
14
17
  export { tokenContract };
15
18
 
@@ -52,9 +55,9 @@ export function inspectTokens(directory, suppliedOptions) {
52
55
  const options = suppliedOptions ?? loadConfig(directory);
53
56
  if(options.tokenInventory)return options.tokenInventory;
54
57
  const { root, dsRoot, config } = options;
55
- const definitions = new Map();
58
+ const declarations = [];
56
59
  const diagnostics = [];
57
- const files = sourceFiles(path.join(dsRoot, config.tokenDir)).filter((file) => file.endsWith(".css"));
60
+ const files = sourceFiles(path.join(dsRoot, config.tokenDir)).filter((file) => file.endsWith(".css") && path.basename(file) !== generatedThemesFile);
58
61
  files.sort((a, b) => foundationFiles.indexOf(path.basename(a)) - foundationFiles.indexOf(path.basename(b)) || a.localeCompare(b));
59
62
  for (const file of files) {
60
63
  let css;
@@ -67,40 +70,26 @@ export function inspectTokens(directory, suppliedOptions) {
67
70
  if (!decl.prop.startsWith("--")) return;
68
71
  const ownership = checkComponentVariable(decl.prop, file, options);
69
72
  if (ownership) diagnostics.push({ rule: ownership.rule, file: path.relative(root, file), line: decl.source.start.line, column: decl.source.start.column, message: ownership.message });
70
- const definition = {
71
- file: path.relative(root, file).replaceAll("\\", "/"),
72
- line: decl.source.start.line,
73
- column: decl.source.start.column,
74
- scope: context(decl),
75
- value: decl.value,
76
- };
77
- if (!definitions.has(decl.prop)) definitions.set(decl.prop, []);
78
- definitions.get(decl.prop).push(definition);
73
+ declarations.push({ prop: decl.prop, value: decl.value, file: path.relative(root, file).replaceAll("\\", "/"), line: decl.source.start.line, column: decl.source.start.column, scope: context(decl) });
79
74
  });
80
75
  }
81
- const base = new Map();
82
- const scopes = new Map();
83
- for (const [name, entries] of definitions) {
84
- for (const entry of entries) {
85
- if (scopeTheme(entry.scope)?.base) base.set(name, entry);
86
- else {
87
- if (!scopes.has(entry.scope)) scopes.set(entry.scope, new Map());
88
- scopes.get(entry.scope).set(name, entry);
89
- }
90
- }
91
- }
76
+ const tokens = buildTokens(declarations, config).map((token) => ({ ...token, ...tokenContract.tokens[token.name], owner: "tokens" }));
77
+ const defined = new Set(tokens.filter((token) => token.definitions.some((definition) => !definition.conditional && definition.brand === null)).map((token) => token.name));
92
78
  for (const name of Object.keys(tokenContract.tokens)) {
93
- if (!base.has(name)) diagnostics.push({ rule: "missing-token", file: config.dsDir, line: 1, column: 1, message: `Define ${name} in :root using the project's chosen value.` });
79
+ if (!defined.has(name)) diagnostics.push({ rule: "missing-token", file: config.dsDir, line: 1, column: 1, message: `Define ${name} in :root using the project's chosen value.` });
94
80
  }
95
81
  const emitted = new Set();
96
82
  function report(rule, name, entry, message) {
97
83
  const key = `${rule}:${name}:${entry.file}:${entry.line}:${message}`;
98
84
  if (emitted.has(key)) return;
99
85
  emitted.add(key);
100
- diagnostics.push({ rule, ...entry, message });
86
+ const { file, line, column, scope, value } = entry;
87
+ diagnostics.push({ rule, file, line, column, scope, value, message });
101
88
  }
102
- const effectiveScopes = [base, ...[...scopes.values()].map((overrides) => new Map([...base, ...overrides]))];
103
- for (const scope of effectiveScopes) {
89
+ // Every theme in every brand, as the browser resolves it there; halves are names too.
90
+ const contexts = config.themes.flatMap(({ name: theme }) => [undefined, ...config.brands.slice(1).map((brand) => brand.name)].map((brand) => contextValues(tokens, { theme, brand, themes: config.themes })));
91
+ const themedNames = new Set(tokens.filter((token) => token.themed).map((token) => token.name));
92
+ for (const scope of contexts) {
104
93
  const cache = new Map();
105
94
  function resolveAlias(name, chain = []) {
106
95
  if (cache.has(name)) return cache.get(name);
@@ -112,7 +101,8 @@ export function inspectTokens(directory, suppliedOptions) {
112
101
  }
113
102
  const resolvedReferences = new Map();
114
103
  for (const ref of references(entry.value)) {
115
- if (!isSharedToken(ref.name)) report("token-name", name, entry, `${name} references ${ref.name} outside the shared Data token contract.`);
104
+ const half = !themedNames.has(ref.name) && [...themedNames].some((base) => ref.name.startsWith(`${base}-`) && scope.has(ref.name));
105
+ if (!half && !isSharedToken(ref.name)) report("token-name", name, entry, `${name} references ${ref.name} outside the shared Data token contract.`);
116
106
  if (!scope.has(ref.name) && !ref.fallback) report("token-reference", name, entry, `${name} references undefined ${ref.name}.`);
117
107
  else if (scope.has(ref.name)) resolvedReferences.set(ref.name, resolveAlias(ref.name, [...chain, name]));
118
108
  }
@@ -140,15 +130,20 @@ export function inspectTokens(directory, suppliedOptions) {
140
130
  if (type && resolved !== undefined && !matchesType(resolved, type)) report("token-type", name, entry, `${name} expects ${type}; found ${resolved}.`);
141
131
  }
142
132
  }
143
- const tokens = [...definitions].sort(([a], [b]) => a.localeCompare(b)).map(([name, entries]) => ({ name, ...tokenContract.tokens[name], owner:"tokens", definitions: entries }));
144
133
  const themes = themeFindings(tokens, config.themes, { dsDir: config.dsDir });
145
134
  diagnostics.push(...themes.diagnostics);
135
+ const brands = brandFindings(tokens, config.brands, config.themes, { dsDir: config.dsDir });
136
+ diagnostics.push(...brands.diagnostics);
137
+ diagnostics.push(...themesCssDiagnostics(options, { tokens }));
138
+ // Token-value findings are errors or review items by rule; errors join the diagnostics.
139
+ const findings = routeFindings(diagnostics, [...tokenOverlapAdvisories(tokens), ...tokenContrastAdvisories(tokens, config.themes, config.brands), ...tokenRhythmAdvisories(tokens), ...themes.advisories, ...brands.advisories,
140
+ ...a11yTokenAdvisories(tokens, { root, foundationFile: path.join(dsRoot, config.tokenDir, "base.css") })]);
146
141
  return options.tokenInventory = {
147
142
  contractVersion: tokenContract.version,
148
143
  themes: config.themes,
144
+ ...(config.brands.length ? { brands: config.brands } : {}),
149
145
  tokens,
150
- advisories: [...tokenOverlapAdvisories(tokens), ...tokenContrastAdvisories(tokens, config.themes), ...tokenRhythmAdvisories(tokens), ...themes.advisories,
151
- ...a11yTokenAdvisories(tokens, { root, foundationFile: path.join(dsRoot, config.tokenDir, "base.css") })],
152
- diagnostics,
146
+ advisories: findings.advisories,
147
+ diagnostics: findings.diagnostics,
153
148
  };
154
149
  }