@reqvire-org/ads 0.3.46 → 0.3.48

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 (122) 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 +51 -0
  8. package/dist/browser-audit.mjs +147 -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/context.mjs +1 -1
  24. package/dist/mcp/drafts.mjs +3 -0
  25. package/dist/mcp/mutations.mjs +40 -1
  26. package/dist/mcp/preview-widget.bundle.js +36 -36
  27. package/dist/mcp/project-widget.bundle.js +12 -12
  28. package/dist/mcp/server.mjs +23 -11
  29. package/dist/mcp/widget.bundle.js +17 -17
  30. package/dist/palette-generated.mjs +180 -0
  31. package/dist/preview-resources.mjs +12 -3
  32. package/dist/render-color-probe.mjs +148 -0
  33. package/dist/runtime-contracts.mjs +14 -4
  34. package/dist/scenarios.mjs +1 -1
  35. package/dist/showcase/client.bundle.js +28 -28
  36. package/dist/showcase/icons.js +146 -0
  37. package/dist/showcase/index.html +2 -1
  38. package/dist/showcase/style.css +19 -2
  39. package/dist/skills/README.md +2 -1
  40. package/dist/skills/ads-break-ui/SKILL.md +6 -5
  41. package/dist/skills/ads-break-ui/references/atomic-styles.md +12 -12
  42. package/dist/skills/ads-break-ui/references/contracts.md +13 -10
  43. package/dist/skills/ads-break-ui/references/design-data.md +137 -29
  44. package/dist/skills/ads-break-ui/references/drafts.md +3 -1
  45. package/dist/skills/ads-break-ui/references/guarded-editing.md +3 -2
  46. package/dist/skills/ads-break-ui/references/validation.md +13 -4
  47. package/dist/skills/ads-designer/SKILL.md +23 -16
  48. package/dist/skills/ads-designer/references/accessibility.md +41 -5
  49. package/dist/skills/ads-designer/references/atomic-styles.md +12 -12
  50. package/dist/skills/ads-designer/references/branding.md +37 -10
  51. package/dist/skills/ads-designer/references/cli.md +8 -2
  52. package/dist/skills/ads-designer/references/contracts.md +13 -10
  53. package/dist/skills/ads-designer/references/design-data.md +137 -29
  54. package/dist/skills/ads-designer/references/drafts.md +3 -1
  55. package/dist/skills/ads-designer/references/guarded-editing.md +3 -2
  56. package/dist/skills/ads-designer/references/validation.md +13 -4
  57. package/dist/skills/ads-import/SKILL.md +9 -8
  58. package/dist/skills/ads-import/references/atomic-styles.md +12 -12
  59. package/dist/skills/ads-import/references/cli.md +8 -2
  60. package/dist/skills/ads-import/references/contracts.md +13 -10
  61. package/dist/skills/ads-import/references/design-data.md +137 -29
  62. package/dist/skills/ads-import/references/drafts.md +3 -1
  63. package/dist/skills/ads-import/references/guarded-editing.md +3 -2
  64. package/dist/skills/ads-import/references/tokens.md +7 -3
  65. package/dist/skills/ads-import/references/validation.md +13 -4
  66. package/dist/skills/ads-motion/SKILL.md +6 -5
  67. package/dist/skills/ads-motion/references/atomic-styles.md +12 -12
  68. package/dist/skills/ads-motion/references/contracts.md +13 -10
  69. package/dist/skills/ads-motion/references/design-data.md +137 -29
  70. package/dist/skills/ads-motion/references/drafts.md +3 -1
  71. package/dist/skills/ads-motion/references/guarded-editing.md +3 -2
  72. package/dist/skills/ads-motion/references/validation.md +13 -4
  73. package/dist/skills/ads-port/SKILL.md +6 -5
  74. package/dist/skills/ads-port/references/atomic-styles.md +12 -12
  75. package/dist/skills/ads-port/references/cli.md +8 -2
  76. package/dist/skills/ads-port/references/contracts.md +13 -10
  77. package/dist/skills/ads-port/references/design-data.md +137 -29
  78. package/dist/skills/ads-port/references/drafts.md +3 -1
  79. package/dist/skills/ads-port/references/guarded-editing.md +3 -2
  80. package/dist/skills/ads-port/references/validation.md +13 -4
  81. package/dist/starters/preact/design-system/review/token-preview/TokenPreview.tsx +11 -2
  82. package/dist/starters/react/ADS.md +43 -10
  83. package/dist/starters/react/README.md +14 -9
  84. package/dist/starters/react/design-system/assets/brand/README.md +8 -3
  85. package/dist/starters/react/design-system/assets/glyphs/README.md +4 -1
  86. package/dist/starters/react/design-system/components/Content/Icon/Icon.ads.fixture.ts +6 -1
  87. package/dist/starters/react/design-system/components/Content/Icon/Icon.ads.scenario.tsx +3 -2
  88. package/dist/starters/react/design-system/components/Content/Icon/README.md +2 -1
  89. package/dist/starters/react/design-system/components/Content/Logo/Logo.tsx +3 -9
  90. package/dist/starters/react/design-system/components/Content/Logo/README.md +4 -2
  91. package/dist/starters/react/design-system/controllers/Palette/Palette.ts +164 -0
  92. package/dist/starters/react/design-system/index.ts +3 -0
  93. package/dist/starters/react/design-system/review/brand-preview/BrandPreview.tsx +2 -5
  94. package/dist/starters/react/design-system/review/token-preview/TokenPreview.tsx +11 -2
  95. package/dist/starters/react/design-system/styles.css +1 -0
  96. package/dist/starters/react/design-system/tokens/base.css +8 -5
  97. package/dist/starters/react/design-system/tokens/colors.css +167 -175
  98. package/dist/starters/react/design-system/tokens/elevation.css +14 -21
  99. package/dist/starters/react/design-system/tokens/themes.generated.css +142 -0
  100. package/dist/starters/react/design-system/tokens/themes.generated.ts +402 -0
  101. package/dist/style-boundaries.mjs +2 -1
  102. package/dist/themes-generated.mjs +150 -0
  103. package/dist/themes-watch.mjs +42 -0
  104. package/dist/themes.mjs +214 -63
  105. package/dist/token-export.mjs +22 -11
  106. package/dist/token-policy.mjs +2 -1
  107. package/dist/token-quality.mjs +28 -25
  108. package/dist/tokens.mjs +27 -32
  109. package/dist/validation.mjs +17 -1
  110. package/dist/verification/browser.mjs +14 -3
  111. package/dist/verification.mjs +25 -4
  112. package/docs/ADS.md +41 -27
  113. package/docs/ARCHITECTURE.md +49 -22
  114. package/docs/CACHING.md +2 -3
  115. package/docs/CHANGELOG.md +117 -13
  116. package/docs/CONTRACTS.md +13 -10
  117. package/docs/GUIDE.md +94 -22
  118. package/docs/MCP.md +50 -30
  119. package/docs/benchmarks/bun-previews.md +5 -5
  120. package/docs/benchmarks/{gidi-preview-memory.md → preview-memory.md} +14 -12
  121. package/docs/benchmarks/turbo-poc.md +24 -6
  122. package/package.json +2 -1
@@ -0,0 +1,150 @@
1
+ import { existsSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
2
+ import path from "node:path";
3
+ import { classifyScope, referencedTokens, themeDependents } from "./themes.mjs";
4
+ import { generatedPaletteFile, paletteTs } from "./palette-generated.mjs";
5
+
6
+ // themes.generated.css: the theme switches and per-element resolvers ADS writes from the token
7
+ // sheets' per-theme halves and ds.config.json themes/brands. The showcase and MCP server write
8
+ // it at startup and whenever a token sheet or the config changes, `ads assets` writes it on
9
+ // demand (for CI and agents without a running showcase); `ads check` only verifies it.
10
+ //
11
+ // Each theme has a switch, --ads-if-<theme>, inherited from the nearest [data-theme]: the
12
+ // active theme's is `initial` (the guaranteed-invalid value, so var() takes its fallback) and
13
+ // every other theme's is empty (var() substitutes nothing). A themed token concatenates one
14
+ // var(--ads-if-<theme>, var(--token-<theme>)) per theme, so exactly the active half survives.
15
+ // Display switches (--display-<theme>, --display-brand-<brand>) are `initial` where their theme
16
+ // or brand applies and `none` elsewhere, so display: var(--display-dark, block) shows artwork
17
+ // only in the nearest dark section. With followSystemTheme, an @media (prefers-color-scheme)
18
+ // block applies the matching theme's switches to a root without an explicit data-theme.
19
+ // Resolvers sit on :root, [data-theme] and [data-brand], so every themed or branded element
20
+ // re-resolves against its own switches and halves. A re-resolved token's conditional values
21
+ // (an @media or @supports block on :root in a token sheet) are repeated after the resolvers
22
+ // under the same conditions, so the unconditional resolver copy does not override them.
23
+ // Beside it, themes.generated.ts holds the resolved renderer palette (palette-generated.mjs);
24
+ // both files are written and checked together.
25
+
26
+ export const generatedThemesFile = "themes.generated.css";
27
+ export const themesCssPath = ({ dsRoot, config }) => path.join(dsRoot, config.tokenDir, generatedThemesFile);
28
+ export { generatedPaletteFile };
29
+ /** Both generated files, written and checked together: the theme sheet and the renderer palette. */
30
+ export const generatedThemeFiles = [generatedThemesFile, generatedPaletteFile];
31
+ export const paletteTsPath = ({ dsRoot, config }) => path.join(dsRoot, config.tokenDir, generatedPaletteFile);
32
+ const generatedTexts = (options, tokens) => [{ file: themesCssPath(options), text: themesCss(tokens, options.config) }, { file: paletteTsPath(options), text: paletteTs(tokens, options.config) }];
33
+ const header = "/* Generated by ADS from the token sheets' per-theme halves and ds.config.json themes and brands.\n The showcase and MCP server rewrite it when they change; do not edit it. */\n";
34
+
35
+ const declaration = definition => ({ property: definition.property ?? definition.name, value: (definition.authored ?? definition.value).trim() });
36
+ const block = (selector, lines) => lines.length ? [`${selector} {`, ...lines.map(line => ` ${line}`), "}"] : [];
37
+
38
+ /** The at-rule conditions of a default-brand :root definition ("@media … > :root"), or null. */
39
+ function rootConditions(definition, defaultBrand) {
40
+ if (!definition.conditional || definition.old || definition.brand !== null) return null;
41
+ const parts = definition.scope.split(" > "), selector = parts.pop();
42
+ if (!parts.length || parts.some(part => !part.startsWith("@")) || classifyScope(selector, defaultBrand).kind !== "root") return null;
43
+ return parts;
44
+ }
45
+
46
+ /** The display switches the generated sheet defines: --display-<theme> per declared theme and,
47
+ * with brands declared, --display-brand-<brand> per brand. Components read them with a
48
+ * fallback (display: var(--display-dark, block)), so they need no token-sheet definition. */
49
+ export function displaySwitches({ themes, brands = [] }) {
50
+ return [...themes.map(theme => `--display-${theme.name}`), ...brands.map(brand => `--display-brand-${brand.name}`)];
51
+ }
52
+
53
+ // A theme's switch block: its color scheme, --ads-if-<theme> per theme (initial for its own,
54
+ // empty otherwise) and --display-<theme> per theme (initial for its own, none otherwise).
55
+ const themeSwitches = (theme, themes) => [`color-scheme: ${theme.scheme};`,
56
+ ...themes.map(other => `--ads-if-${other.name}: ${other === theme ? "initial" : ""};`),
57
+ ...themes.map(other => `--display-${other.name}: ${other === theme ? "initial" : "none"};`)];
58
+ const brandSwitches = (brand, brands) => brands.map(other => `--display-brand-${other.name}: ${other === brand ? "initial" : "none"};`);
59
+
60
+ /** The theme that follows each OS color scheme when followSystemTheme is set: the first declared
61
+ * theme with that scheme, unless it is the default theme :root already applies. */
62
+ export function systemThemes(themes) {
63
+ return ["light", "dark"].map(scheme => [scheme, themes.find(theme => theme.scheme === scheme)]).filter(([, theme]) => theme && theme !== themes[0]);
64
+ }
65
+
66
+ /** The generated stylesheet for a token inventory's tokens and the declared themes and brands. */
67
+ export function themesCss(tokens, { themes, brands = [], followSystemTheme = false }) {
68
+ const out = [];
69
+ for (const [index, theme] of themes.entries()) {
70
+ out.push(...block(index ? `[data-theme="${theme.name}"]` : `:root, [data-theme="${theme.name}"]`, themeSwitches(theme, themes)));
71
+ }
72
+ // Without an explicit data-theme on the root, the OS color scheme picks the theme.
73
+ if (followSystemTheme) for (const [scheme, theme] of systemThemes(themes)) {
74
+ out.push(...block(`@media (prefers-color-scheme: ${scheme})`, block(":root:not([data-theme])", themeSwitches(theme, themes))));
75
+ }
76
+ const dependent = themeDependents(tokens);
77
+ const plain = definition => !definition.conditional;
78
+ const defaults = [], branded = new Map(brands.slice(1).map(brand => [brand.name, []]));
79
+ for (const token of tokens) for (const definition of token.definitions.filter(plain)) {
80
+ const entry = { ...declaration({ ...definition, name: token.name }), token: token.name, themed: definition.theme !== null };
81
+ if (definition.brand === null) defaults.push(entry);
82
+ else branded.get(definition.brand)?.push(entry);
83
+ }
84
+ // Brand-sensitive declarations re-apply on every [data-brand]: what a brand re-values, and
85
+ // every default value that refers to one of those, so a section inside another brand starts
86
+ // from the defaults and a brand's values resolve against its own halves.
87
+ const sensitive = new Set([...branded.values()].flat().map(entry => entry.property));
88
+ const sensitiveToken = name => sensitive.has(name) || tokens.some(token => token.themed && token.name === name && [...sensitive].some(property => property.startsWith(`${name}-`)));
89
+ for (let changed = true; changed;) {
90
+ changed = false;
91
+ for (const entry of defaults) if (!sensitive.has(entry.property) && referencedTokens(entry.value).some(sensitiveToken)) { sensitive.add(entry.property); changed = true; }
92
+ }
93
+ const sorted = entries => [...new Map(entries.map(entry => [entry.property, entry])).values()].sort((a, b) => a.property.localeCompare(b.property, "en", { numeric: true }));
94
+ const reresolved = entry => !entry.themed && dependent.has(entry.token);
95
+ if (brands.length) {
96
+ // The default brand's display switches hold on :root and reset on every [data-brand], so a
97
+ // default-brand section inside another brand shows its own artwork.
98
+ out.push(...block(":root, [data-brand]", brandSwitches(brands[0], brands)));
99
+ out.push(...block("[data-brand]", sorted(defaults.filter(entry => sensitive.has(entry.property) && !reresolved(entry))).map(entry => `${entry.property}: ${entry.value};`)));
100
+ for (const [name, entries] of branded) out.push(...block(`[data-brand="${name}"]`, [...brandSwitches(brands.find(brand => brand.name === name), brands), ...sorted(entries.filter(entry => !reresolved(entry))).map(entry => `${entry.property}: ${entry.value};`)]));
101
+ }
102
+ const resolvers = [
103
+ ...tokens.filter(token => token.themed).sort((a, b) => a.name.localeCompare(b.name, "en", { numeric: true })).map(token => `${token.name}: ${themes.map(theme => `var(--ads-if-${theme.name}, var(${token.name}-${theme.name}))`).join("")};`),
104
+ ...sorted(defaults.filter(reresolved)).map(entry => `${entry.property}: ${entry.value};`),
105
+ ];
106
+ const resolverSelector = brands.length ? ":root, [data-theme], [data-brand]" : ":root, [data-theme]";
107
+ out.push(...block(resolverSelector, resolvers));
108
+ // Conditional values of re-resolved tokens, in source order per condition, after the resolvers.
109
+ const conditioned = new Map();
110
+ for (const token of tokens) {
111
+ if (token.themed || !dependent.has(token.name)) continue;
112
+ for (const definition of token.definitions) {
113
+ const conditions = rootConditions(definition, brands[0]?.name);
114
+ if (!conditions) continue;
115
+ const key = JSON.stringify(conditions);
116
+ if (!conditioned.has(key)) conditioned.set(key, { conditions, lines: [] });
117
+ const { property, value } = declaration({ ...definition, name: token.name });
118
+ conditioned.get(key).lines.push(`${property}: ${value};`);
119
+ }
120
+ }
121
+ for (const { conditions, lines } of conditioned.values()) out.push(...conditions.reduceRight((inner, condition) => block(condition, inner), block(resolverSelector, lines)));
122
+ return `${header}${out.join("\n")}\n`;
123
+ }
124
+
125
+ /** Errors for a missing or stale generated file; none while the token sheets use the old form. */
126
+ export function themesCssDiagnostics(options, inventory) {
127
+ if (inventory.tokens.some(token => token.definitions.some(definition => definition.old))) return [];
128
+ const diagnostics = [];
129
+ for (const { file, text } of generatedTexts(options, inventory.tokens)) {
130
+ const relative = path.relative(options.root, file).replaceAll("\\", "/");
131
+ const at = { rule: "themes-generated", file: relative, line: 1, column: 1 };
132
+ if (!existsSync(file)) diagnostics.push({ ...at, message: `${relative} is missing. ADS writes it from the token sheets; run \`ads assets\` or start the showcase or MCP server.` });
133
+ else if (readFileSync(file, "utf8") !== text) diagnostics.push({ ...at, message: `${relative} is out of date with the token sheets or ds.config.json themes and brands; run \`ads assets\` or start the showcase or MCP server.` });
134
+ }
135
+ return diagnostics;
136
+ }
137
+
138
+ /** Writes both generated files when their content changed. Skipped while the old theme form
139
+ * remains. The result describes the theme sheet (file, written, text) and lists both in files. */
140
+ export function writeThemesCss(options, inventory) {
141
+ const file = themesCssPath(options);
142
+ if (inventory.tokens.some(token => token.definitions.some(definition => definition.old))) return { file, written: false, skipped: "old theme form", files: [] };
143
+ const files = generatedTexts(options, inventory.tokens).map(({ file, text }) => {
144
+ if (existsSync(file) && readFileSync(file, "utf8") === text) return { file, written: false, text };
145
+ const staged = `${file}.${process.pid}.tmp`;
146
+ try { writeFileSync(staged, text); renameSync(staged, file); } finally { rmSync(staged, { force: true }); }
147
+ return { file, written: true, text };
148
+ });
149
+ return { ...files[0], written: files.some(item => item.written), files };
150
+ }
@@ -0,0 +1,42 @@
1
+ import { watch } from "node:fs";
2
+ import path from "node:path";
3
+ import { loadConfig } from "./config.mjs";
4
+ import { inspectTokens } from "./tokens.mjs";
5
+ import { generatedThemeFiles, generatedThemesFile, writeThemesCss } from "./themes-generated.mjs";
6
+
7
+ /** Rewrites the project's themes.generated.css and themes.generated.ts from its token sheets and config when stale. */
8
+ export function refreshThemesCss(directory) {
9
+ const options = loadConfig(directory);
10
+ return { ...writeThemesCss(options, inspectTokens(directory, options)), root: options.root };
11
+ }
12
+
13
+ /** Keeps themes.generated.css and .ts current: once now, then on every token sheet or config change. */
14
+ export function watchThemesCss(directory, { log = () => {} } = {}) {
15
+ const watchers = [];
16
+ let timer;
17
+ const refresh = () => {
18
+ try {
19
+ const result = refreshThemesCss(directory);
20
+ for (const item of result.files ?? []) if (item.written) log(`ADS wrote ${path.relative(result.root, item.file).replaceAll("\\", "/")}`);
21
+ } catch (error) { log(`ADS could not write ${generatedThemesFile}: ${error.message}`); }
22
+ };
23
+ const changed = file => {
24
+ const name = path.basename(String(file ?? ""));
25
+ if (generatedThemeFiles.some(generated => name === generated || name.startsWith(`${generated}.`))) return;
26
+ clearTimeout(timer);
27
+ timer = setTimeout(refresh, 50);
28
+ timer.unref?.();
29
+ };
30
+ refresh();
31
+ try {
32
+ const { root, dsRoot, config } = loadConfig(directory);
33
+ for (const [folder, filter] of [[path.join(dsRoot, config.tokenDir), file => String(file).endsWith(".css")], [root, file => String(file) === "ds.config.json"]]) {
34
+ try {
35
+ const watcher = watch(folder, { recursive: folder !== root }, (_event, file) => { if (filter(file)) changed(file); });
36
+ watcher.unref(); watcher.on("error", () => watcher.close());
37
+ watchers.push(watcher);
38
+ } catch { /* A missing token folder has nothing to generate from. */ }
39
+ }
40
+ } catch { /* An invalid configuration is reported by the server itself. */ }
41
+ return { refresh, close() { clearTimeout(timer); for (const watcher of watchers) watcher.close(); } };
42
+ }
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) {