@reqvire-org/ads 0.4.2 → 0.4.4

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 (78) hide show
  1. package/README.md +11 -2
  2. package/dist/a11y.mjs +71 -65
  3. package/dist/analysis/helpers.mjs +5 -3
  4. package/dist/analysis/inputs.mjs +13 -6
  5. package/dist/analysis/module-resolvers.mjs +46 -0
  6. package/dist/analysis/service.mjs +7 -0
  7. package/dist/analysis/syntax.mjs +20 -5
  8. package/dist/assets.mjs +1 -1
  9. package/dist/boundaries.mjs +6 -4
  10. package/dist/bun-compiler.mjs +6 -5
  11. package/dist/check-service.mjs +8 -5
  12. package/dist/check.mjs +11 -46
  13. package/dist/component-contrast.mjs +126 -8
  14. package/dist/contrast-composition.mjs +80 -0
  15. package/dist/contrast-styles.mjs +88 -0
  16. package/dist/finding-rules.mjs +2 -0
  17. package/dist/font-rules.mjs +20 -15
  18. package/dist/fonts-generated.mjs +21 -14
  19. package/dist/foundation-views.mjs +6 -2
  20. package/dist/image-attributes.mjs +96 -92
  21. package/dist/mcp/build-status.mjs +8 -3
  22. package/dist/mcp/drafts.mjs +12 -5
  23. package/dist/mcp/mutations.mjs +11 -8
  24. package/dist/mcp/preview-widget.bundle.js +45 -45
  25. package/dist/mcp/resource-loader.js +1 -201
  26. package/dist/mcp/server.mjs +19 -5
  27. package/dist/pictogram-model.mjs +59 -0
  28. package/dist/pictograms.mjs +52 -0
  29. package/dist/preview-bun.mjs +76 -60
  30. package/dist/preview-incremental.mjs +358 -0
  31. package/dist/preview-manifest-update.mjs +70 -0
  32. package/dist/preview-resources.mjs +33 -1
  33. package/dist/render-audit/image-shape.mjs +13 -3
  34. package/dist/render-audit/pictograms.mjs +88 -0
  35. package/dist/render-audit/worker.mjs +12 -0
  36. package/dist/render-audit.mjs +11 -1
  37. package/dist/render-composition.mjs +186 -0
  38. package/dist/scenario-registry.mjs +2 -2
  39. package/dist/scenarios-compiler.mjs +1 -1
  40. package/dist/showcase/client.bundle.js +23 -23
  41. package/dist/showcase/draft-navigation.js +5 -5
  42. package/dist/showcase/foundation-view.css +3 -0
  43. package/dist/showcase/foundation-view.mjs +3 -0
  44. package/dist/showcase/pictogram-view.mjs +53 -0
  45. package/dist/showcase/ui/ui.js +2 -0
  46. package/dist/skills/README.md +1 -1
  47. package/dist/skills/ads-designer/SKILL.md +18 -2
  48. package/dist/skills/ads-designer/references/accessibility.md +70 -2
  49. package/dist/skills/ads-designer/references/branding.md +5 -16
  50. package/dist/skills/ads-designer/references/performance.md +3 -2
  51. package/dist/skills/ads-designer/references/pictograms.md +131 -0
  52. package/dist/skills/ads-designer/references/runtimes.md +15 -0
  53. package/dist/skills/ads-import/references/runtimes.md +15 -0
  54. package/dist/skills/ads-migrate/SKILL.md +2 -1
  55. package/dist/skills/ads-migrate/references/0.4.1-to-0.4.2.md +2 -3
  56. package/dist/skills/ads-migrate/references/0.4.3-to-0.4.4.md +80 -0
  57. package/dist/skills/ads-port/SKILL.md +4 -1
  58. package/dist/skills/ads-port/references/runtimes.md +15 -0
  59. package/dist/source-values.mjs +4 -1
  60. package/dist/starters/react/design-system/assets/pictograms/catalog.ads.json +13 -0
  61. package/dist/starters/react/design-system/assets/pictograms/journey.dark.svg +7 -0
  62. package/dist/starters/react/design-system/assets/pictograms/journey.svg +7 -0
  63. package/dist/starters/react/design-system/components/Content/Pictogram/Pictogram.ads.exports.ts +1 -0
  64. package/dist/starters/react/design-system/components/Content/Pictogram/Pictogram.ads.fixture.ts +1 -0
  65. package/dist/starters/react/design-system/components/Content/Pictogram/Pictogram.ads.scenario.tsx +7 -0
  66. package/dist/starters/react/design-system/components/Content/Pictogram/Pictogram.tsx +26 -0
  67. package/dist/style-token-rules.mjs +51 -0
  68. package/dist/task-cache.mjs +2 -2
  69. package/dist/units.mjs +4 -4
  70. package/dist/validation-inputs.mjs +7 -3
  71. package/docs/ADS.md +6 -1
  72. package/docs/ARCHITECTURE.md +144 -16
  73. package/docs/CACHING.md +65 -1
  74. package/docs/CHANGELOG.md +86 -50
  75. package/docs/GUIDE.md +52 -7
  76. package/docs/MCP.md +47 -16
  77. package/docs/benchmarks/README.md +1 -1
  78. package/package.json +7 -4
@@ -1,13 +1,18 @@
1
1
  import valueParser from "postcss-value-parser";
2
- import { contrastContexts, contrastPairs, contrastRatio } from "./token-quality.mjs";
2
+ import { contrastContexts, contrastPairs, contrastRatio, over } from "./token-quality.mjs";
3
3
  import { findingSeverity } from "./finding-rules.mjs";
4
+ import { resolveValue } from "./themes.mjs";
4
5
 
5
6
  /** Text contrast of the color and background a component or pattern style block pairs itself.
6
7
  * token-contrast checks the role pairs the token contract names; components can pair any two
7
8
  * tokens, such as a status color as text on its own tint. Where one block (the template's top
8
9
  * level, a nested selector such as &:hover or &[aria-selected="true"], or an at-rule) declares
9
10
  * both `color: var(--a)` and `background(-color): var(--b)`, the pair needs 4.5:1 (WCAG 1.4.3)
10
- * in every theme and brand, resolved and composited as token-contrast resolves them. Local
11
+ * in every theme and brand, resolved and composited as token-contrast resolves them. Large text
12
+ * needs 3:1: where the block or an enclosing block declares `font-size` of at least 24px (18pt),
13
+ * or at least 18.66px (14pt) with `font-weight` 700 or more, in px, pt or rem (16px root), as
14
+ * a literal or a token resolved per theme and brand. Any other size (em, %, calc(), a keyword,
15
+ * the `font` shorthand) is not known to be large, so it keeps 4.5:1. Local
11
16
  * custom properties declared in the block or an enclosing block resolve one level, and an
12
17
  * undeclared one reads its var() fallback, the default it renders with. Disabled states are
13
18
  * exempt (WCAG exempts inactive components). A block that sets one token on both sides, or that
@@ -49,6 +54,46 @@ function selectorChain(container) {
49
54
  return parts;
50
55
  }
51
56
 
57
+ const LARGE = 24, LARGE_BOLD = 18.66, BOLD = 700;
58
+
59
+ /** The nearest declaration of a property in the block or an enclosing block of the same sheet. */
60
+ function inherited(container, prop) {
61
+ for (let node = container; node; node = node.parent) {
62
+ const decl = own(node).get(prop);
63
+ if (decl) return decl;
64
+ }
65
+ return null;
66
+ }
67
+
68
+ /** A declaration's value in one theme/brand context: a literal, or a token followed through its aliases. */
69
+ function contextValue(decl, values) {
70
+ if (!decl) return null;
71
+ const value = single(decl.value);
72
+ if (value?.name) return resolveValue(values, value.name) ?? value.fallback?.trim() ?? null;
73
+ return value?.keyword ? value.keyword : decl.value.trim();
74
+ }
75
+
76
+ function pixels(value) {
77
+ const match = value?.match(/^(\d*\.?\d+)(px|pt|rem)$/i);
78
+ if (!match) return null;
79
+ const amount = Number(match[1]), unit = match[2].toLowerCase();
80
+ return unit === "px" ? amount : unit === "pt" ? amount * 4 / 3 : amount * 16;
81
+ }
82
+
83
+ function weight(value) {
84
+ if (!value) return 400;
85
+ if (/^bold$/i.test(value)) return 700;
86
+ const number = Number(value);
87
+ return Number.isFinite(number) ? number : 400;
88
+ }
89
+
90
+ /** Whether the block paints large text (WCAG: 18pt, or 14pt bold) in a context. */
91
+ function largeText(container, values) {
92
+ const size = pixels(contextValue(inherited(container, "font-size"), values));
93
+ if (size === null) return false;
94
+ return size >= LARGE || size >= LARGE_BOLD && weight(contextValue(inherited(container, "font-weight"), values)) >= BOLD;
95
+ }
96
+
52
97
  /** A role-contract suggestion for a pair: --x-text on --x-bg, --x-fg on --x. */
53
98
  function suggestion(background, names) {
54
99
  const tint = background.match(/^--(.+)-bg$/);
@@ -62,17 +107,84 @@ export function createComponentContrast(tokens, themes, brands) {
62
107
  const checked = new Set(contrastPairs(names).filter(([, , minimum]) => minimum === 4.5).map(([foreground, background]) => `${foreground} ${background}`));
63
108
  let contexts;
64
109
  const findings = new Map(), unresolved = new Map();
110
+ const composedPairs = new Map();
65
111
 
66
112
  /** The token a declaration paints with, following one level of local custom properties. */
67
- function paint(decl, container) {
113
+ function paint(decl, container, locals) {
68
114
  const value = single(decl.value);
69
115
  if (!value?.name || names.has(value.name)) return value;
116
+ if (locals) {
117
+ const local = locals.get(value.name);
118
+ if (local) { const target = single(local.value); return target?.name && names.has(target.name) ? target : target?.keyword ? target : { unresolved: value.name }; }
119
+ return value.fallback ? fallbackPaint(value) : { unresolved: value.name };
120
+ }
70
121
  for (let node = container; node; node = node.parent) {
71
122
  const local = own(node).get(value.name);
72
123
  if (local) { const target = single(local.value); return target?.name && names.has(target.name) ? target : target?.keyword ? target : { unresolved: value.name }; }
73
124
  }
74
125
  return value.fallback ? fallbackPaint(value) : { unresolved: value.name };
75
126
  }
127
+
128
+ function incomplete(at, reason) {
129
+ const key = JSON.stringify([at.file, at.line, at.column, reason]);
130
+ if (!unresolved.has(key)) unresolved.set(key, {
131
+ rule: "component-contrast-unresolved", severity: findingSeverity("component-contrast-unresolved"), ...at, guidanceUri: guidance,
132
+ message: `${at.file}:${at.line} has unverified composed text contrast: ${reason} Check the affected rendered scenario with ads audit.`,
133
+ });
134
+ }
135
+
136
+ /** A proved text node and its source-resolved ancestor backdrop. No canvas is
137
+ * guessed here: translucent layers need a known opaque background behind them. */
138
+ function composed({ foreground, backgrounds, size, weight: fontWeight, at, related, uncertain }) {
139
+ const front = foreground?.paint;
140
+ if (!front?.name) { incomplete(at, "The text color cannot be resolved to a token."); return; }
141
+ if (!backgrounds.length) { incomplete(at, "No owned opaque background is established for this text."); return; }
142
+ const signature = JSON.stringify([front, backgrounds.map(item => item.paint), size?.value, fontWeight?.value]);
143
+ let result = composedPairs.get(signature);
144
+ if (!result) {
145
+ const failing = [], reasons = new Set();
146
+ contexts ??= contrastContexts(tokens, themes, brands);
147
+ for (const context of contexts) {
148
+ const color = context.color(front.name);
149
+ if (!color?.color) { reasons.add(`${front.name} cannot be resolved in ${context.label}.`); continue; }
150
+ const layers = [];
151
+ let background, backName;
152
+ for (const item of backgrounds) {
153
+ if (item.paint?.keyword === "transparent" || item.paint?.keyword === "none") continue;
154
+ const name = item.paint?.name, back = name && context.color(name);
155
+ if (!back?.color) { reasons.add(`The background cannot be resolved in ${context.label}.`); break; }
156
+ if (back.color[3] === 0) continue;
157
+ backName ??= name;
158
+ if (back.color[3] === 1) { background = back.color; break; }
159
+ layers.push(back.color);
160
+ }
161
+ if (!background) { reasons.add(`No opaque ancestor backdrop is established in ${context.label}.`); continue; }
162
+ for (const layer of layers.reverse()) background = over(layer, background);
163
+ // Standard opaque role pairs already have token-level evidence.
164
+ if (!layers.length && checked.has(`${front.name} ${backName}`)) continue;
165
+ if (![front.name, ...backgrounds.map(item => item.paint?.name).filter(Boolean)].some(context.changed)) continue;
166
+ const px = pixels(contextValue(size, context.values)), bold = weight(contextValue(fontWeight, context.values));
167
+ const minimum = px >= LARGE || px >= LARGE_BOLD && bold >= BOLD ? 3 : 4.5;
168
+ const ratio = contrastRatio(color.color, background);
169
+ if (ratio + 1e-9 < minimum) failing.push({ theme: context.context.theme.name, ...(context.context.brand === undefined ? {} : { brand: context.context.brand }), ratio: Number(ratio.toFixed(2)), minimum, label: context.label, background: backName });
170
+ }
171
+ result = { failing, reasons: [...reasons] };
172
+ composedPairs.set(signature, result);
173
+ }
174
+ for (const reason of result.reasons) incomplete(at, reason);
175
+ if (uncertain) { incomplete(at, "Render alternatives do not establish a single composition."); return; }
176
+ if (!result.failing.length) return;
177
+ const backNames = [...new Set(result.failing.map(item => item.background))];
178
+ const key = JSON.stringify([at.file, at.line, front.name, backNames.join(" ")]);
179
+ if (findings.has(key)) return;
180
+ findings.set(key, {
181
+ rule: "component-contrast", severity: findingSeverity("component-contrast"), ...at,
182
+ tokens: [front.name, ...backNames], ratio: Math.min(...result.failing.map(item => item.ratio)),
183
+ contexts: result.failing.map(({ label: _label, background: _background, ...item }) => item), related,
184
+ guidanceUri: guidance,
185
+ message: `${at.file}:${at.line} renders ${front.name} over ${backNames.join(" / ")} through owned component composition; ${result.failing.map(item => `${item.ratio.toFixed(2)}:1 in ${item.label} (needs ${item.minimum}:1)`).join(", ")}. Use an accessible text token for the actual background.`,
186
+ });
187
+ }
76
188
  function fallbackPaint({ name, fallback }) {
77
189
  const value = single(fallback);
78
190
  if (value?.keyword || value?.name && names.has(value.name)) return value;
@@ -115,19 +227,25 @@ export function createComponentContrast(tokens, themes, brands) {
115
227
  message: `${file}:${line} pairs ${foreground} on the translucent ${background}, and ${foreground} matches the canvas in ${context.label}, so the block sits on another backdrop and the pair's contrast is not checked. Check the rendered component with ads audit.` });
116
228
  continue;
117
229
  }
118
- const ratio = contrastRatio(a.color, context.opaque(b, background));
119
- if (ratio + 1e-9 < 4.5) failing.push({ ratio, label: context.label, theme: context.context.theme.name, ...(context.context.brand === undefined ? {} : { brand: context.context.brand }) });
230
+ const ratio = contrastRatio(a.color, context.opaque(b, background)), minimum = largeText(container, context.values) ? 3 : 4.5;
231
+ if (ratio + 1e-9 < minimum) failing.push({ ratio, minimum, label: context.label, theme: context.context.theme.name, ...(context.context.brand === undefined ? {} : { brand: context.context.brand }) });
120
232
  }
121
233
  if (!failing.length) return;
122
234
  const key = JSON.stringify([file, line, foreground, background]);
123
235
  if (findings.has(key)) return;
124
- const worst = Math.min(...failing.map(item => item.ratio));
236
+ const worst = Math.min(...failing.map(item => item.ratio)), large = failing.every(item => item.minimum === 3);
237
+ const need = large ? "large text needs 3:1 (WCAG 1.4.3)" : failing.some(item => item.minimum === 3)
238
+ ? "text needs 4.5:1, or 3:1 where it is large (WCAG 1.4.3)"
239
+ : "text needs 4.5:1 (WCAG 1.4.3)";
125
240
  findings.set(key, { rule: "component-contrast", severity: findingSeverity("component-contrast"), file, line, column, tokens: [foreground, background], ratio: Number(worst.toFixed(2)),
126
- contexts: failing.map(({ theme, brand, ratio }) =>( { theme, ...(brand === undefined ? {} : { brand }), ratio: Number(ratio.toFixed(2)) })), selector: selectorChain(container).join(" ") || "&", guidanceUri: guidance,
127
- message: `${file}:${line} sets color: var(${foreground}) on ${fill.prop}: var(${background}), ${failing.map(item => `${item.ratio.toFixed(2)}:1 in ${item.label}`).join(", ")}; text needs 4.5:1 (WCAG 1.4.3). ${suggestion(background, names)}` });
241
+ contexts: failing.map(({ theme, brand, ratio, minimum }) =>( { theme, ...(brand === undefined ? {} : { brand }), ratio: Number(ratio.toFixed(2)), minimum })), selector: selectorChain(container).join(" ") || "&", guidanceUri: guidance,
242
+ message: `${file}:${line} sets color: var(${foreground}) on ${fill.prop}: var(${background}), ${failing.map(item => `${item.ratio.toFixed(2)}:1 in ${item.label}`).join(", ")}; ${need}. ${suggestion(background, names)}` });
128
243
  }
129
244
 
130
245
  return {
246
+ paint: (decl, locals) => paint(decl, null, locals),
247
+ composed,
248
+ incomplete,
131
249
  /** Check one parsed component or pattern style sheet or Linaria template. */
132
250
  collect(file, css, offset = { line: 1, column: 1 }) {
133
251
  block(css, file, offset);
@@ -0,0 +1,80 @@
1
+ import path from "node:path";
2
+ import { location } from "./analysis/helpers.mjs";
3
+ import { createContrastStyles } from "./contrast-styles.mjs";
4
+ import { renderComposition } from "./render-composition.mjs";
5
+
6
+ const initialText = new Set(["a", "button", "input", "select", "textarea", "option"]);
7
+ const initialFont = new Set(["button", "input", "select", "textarea", "option"]);
8
+ const nativeFill = new Set(["button", "input", "select", "textarea", "option", "progress", "meter"]);
9
+ const transparent = value => /^(?:transparent|none|initial|unset)$/i.test(value);
10
+ const inherited = value => /^(?:inherit|unset|currentcolor)$/i.test(value);
11
+ const isTrue = value => value?.kind === "literal" && (value.value === true || value.value === "true");
12
+ const booleanAttribute = value => value?.kind === "literal" && (value.value === true || typeof value.value === "string");
13
+ const isAbsent = value => value?.kind === "literal" && value.value == null;
14
+
15
+ /** Bind already-parsed CSS to captured render facts. This is deliberately a
16
+ * proof of simple owned cascades, not a replacement for browser CSS evaluation. */
17
+ export function createContrastComposition(program, options, contrast) {
18
+ const styles = createContrastStyles();
19
+ const relative = node => ({ ...location(node), file: path.relative(options.root, node.getSourceFile().fileName).replaceAll("\\", "/") });
20
+ async function check() {
21
+ if (!styles.hasColor) return;
22
+ const graph = await renderComposition(program, options);
23
+ const memo = new Map();
24
+ function effective(item) {
25
+ if (memo.has(item)) return memo.get(item);
26
+ const parent = item.parent && effective(item.parent);
27
+ const own = styles.get(item.classes), entries = own.entries;
28
+ const state = {
29
+ foreground: initialText.has(item.tag) ? undefined : parent?.foreground,
30
+ backgrounds: [...(parent?.backgrounds ?? [])],
31
+ size: initialFont.has(item.tag) ? undefined : parent?.size,
32
+ weight: initialFont.has(item.tag) ? undefined : parent?.weight,
33
+ locals: new Map(parent?.locals),
34
+ reason: parent?.reason ?? own.reason,
35
+ hidden: parent?.hidden || booleanAttribute(item.attributes.hidden) || booleanAttribute(item.attributes.disabled) || isTrue(item.attributes["aria-disabled"]),
36
+ visibility: parent?.visibility,
37
+ };
38
+ memo.set(item, state);
39
+ for (const [name, entry] of entries) if (name.startsWith("--")) state.locals.set(name, entry);
40
+ const color = entries.get("color");
41
+ if (color) state.foreground = inherited(color.value) ? parent?.foreground : { ...color, paint: contrast.paint(color.decl, state.locals) };
42
+ for (const [property, field] of [["font-size", "size"], ["font-weight", "weight"]]) {
43
+ const entry = entries.get(property);
44
+ if (entry) state[field] = inherited(entry.value) ? parent?.[field] : entry;
45
+ }
46
+ if (entries.has("font")) state.reason ??= "A font shorthand prevents establishing the composed text size.";
47
+ const display = entries.get("display")?.value.toLowerCase(), visibility = entries.get("visibility")?.value.toLowerCase();
48
+ state.hidden ||= display === "none";
49
+ state.visibility = visibility && visibility !== "inherit" ? visibility : parent?.visibility;
50
+ if (/^h[1-6]$/.test(item.tag) && !entries.has("font-size")) state.reason ??= "The heading's browser font size needs a rendered check.";
51
+ const background = entries.get("background-color") ?? entries.get("background");
52
+ if (display !== "contents") {
53
+ if (background && !transparent(background.value)) state.backgrounds.unshift({ ...background, paint: contrast.paint(background.decl, state.locals) });
54
+ else if (!background && nativeFill.has(item.tag)) state.backgrounds.unshift({ paint: null });
55
+ }
56
+ if (entries.has("background-image") && entries.get("background-image").value.toLowerCase() !== "none") state.reason ??= "A background image or gradient needs a rendered contrast check.";
57
+ for (const [name, ordinary] of [["opacity", "1"], ["filter", "none"], ["backdrop-filter", "none"], ["mix-blend-mode", "normal"], ["transform", "none"], ["text-shadow", "none"]])
58
+ if (entries.has(name) && entries.get(name).value.toLowerCase() !== ordinary) state.reason ??= "Opacity, filters, transforms, shadows or blending need the rendered backdrop.";
59
+ if (entries.has("all") || ["absolute", "fixed"].includes(entries.get("position")?.value.toLowerCase())) state.reason ??= "A reset or out-of-flow position prevents establishing the backdrop.";
60
+ if (["hidden", "disabled", "aria-disabled"].some(name => item.attributes[name]?.kind !== "literal")) state.reason ??= "Dynamic visibility or disabled state needs a rendered check.";
61
+ if (!isAbsent(item.attributes.style)) state.reason ??= "Inline styles may override the composed paint.";
62
+ if (styles.externalStyles) state.reason ??= "Additional authored CSS needs the rendered selector cascade.";
63
+ return state;
64
+ }
65
+ for (const item of graph.nodes) {
66
+ if (!item.text && !item.unknownText && isAbsent(item.attributes.dangerouslySetInnerHTML)) continue;
67
+ const state = effective(item);
68
+ if (state.hidden || ["hidden", "collapse"].includes(state.visibility)) continue;
69
+ // Without either side there is no source contrast evidence to extend.
70
+ if (!state.foreground && !state.backgrounds.length && !state.reason) continue;
71
+ const at = state.foreground?.at ?? relative(item.node);
72
+ if (state.reason) { contrast.incomplete(at, state.reason); continue; }
73
+ if (item.unknownText && item.text) contrast.incomplete(at, item.unknownText);
74
+ if (!item.text) { contrast.incomplete(at, item.unknownText ?? "Injected HTML needs a rendered contrast check."); continue; }
75
+ contrast.composed({ ...state, at, uncertain: item.uncertain, related: state.backgrounds.filter(entry => entry.at).map(entry => ({ ...entry.at, message: "Ancestor or element background" })) });
76
+ }
77
+ for (const item of graph.limits) if (item.node) contrast.incomplete(relative(item.node), item.reason);
78
+ }
79
+ return { record: styles.record, check };
80
+ }
@@ -0,0 +1,88 @@
1
+ import selectorParser from "postcss-selector-parser";
2
+
3
+ const properties = new Set(["color", "background", "background-color", "background-image", "font", "font-size", "font-weight", "opacity", "filter", "backdrop-filter", "mix-blend-mode", "transform", "text-shadow", "position", "display", "visibility", "all"]);
4
+ const signature = fact => JSON.stringify([[...fact.entries].map(([name, entry]) => [name, entry.value, entry.important]).sort(([a], [b]) => a.localeCompare(b)), fact.reason]);
5
+
6
+ /** Check-owned paint facts from the already captured/parsed CSS. Class choices
7
+ * stay factored: comparing each choice avoids exponential class combinations. */
8
+ export function createContrastStyles() {
9
+ const templates = new Map(), targetedHooks = new Set(), selectors = new WeakSet(), memo = new WeakMap();
10
+ let hasColor = false, externalStyles = false, unknownTargets = false;
11
+ function targets(rule) {
12
+ if (selectors.has(rule)) return;
13
+ selectors.add(rule);
14
+ try {
15
+ if (rule.selector.length > 4096) { unknownTargets = true; return; }
16
+ const ast = selectorParser().astSync(rule.selector);
17
+ for (const branch of ast.nodes) {
18
+ const subject = branch.nodes.slice(branch.nodes.findLastIndex(node => node.type === "combinator") + 1);
19
+ // `.card:hover &` styles the attached template, not the card hook.
20
+ // Its uncertainty is already retained on that template's own fact.
21
+ if (subject.some(node => node.type === "nesting")) continue;
22
+ branch.walkClasses(node => targetedHooks.add(node.value));
23
+ }
24
+ } catch { unknownTargets = true; }
25
+ }
26
+ function record(template, css, file, offset) {
27
+ const entries = new Map();
28
+ let reason;
29
+ css.walkDecls(decl => {
30
+ const prop = decl.prop.startsWith("--") ? decl.prop : decl.prop.toLowerCase();
31
+ if (!properties.has(prop) && !prop.startsWith("--")) return;
32
+ const parents = [];
33
+ for (let parent = decl.parent; parent && parent.type !== "root"; parent = parent.parent) parents.push(parent);
34
+ if (parents.some(parent => parent.type === "atrule" && /^(?:property|(?:-\w+-)?keyframes)$/.test(parent.name))) return;
35
+ if (prop === "color") hasColor = true;
36
+ let conditional = false;
37
+ for (const parent of parents) {
38
+ if (parent.type === "rule" && parent.selector.trim() !== "&") { targets(parent); conditional = true; }
39
+ if (parent.type === "atrule") conditional = true;
40
+ }
41
+ if (conditional) { reason = `Conditional or descendant ${prop} at ${file}:${offset.line + decl.source.start.line - 1} needs the rendered cascade.`; return; }
42
+ const at = { file, line: offset.line + decl.source.start.line - 1, column: decl.source.start.column + (decl.source.start.line === 1 ? offset.column - 1 : 0) };
43
+ const entry = { value: decl.value, prop, important: !!decl.important, at, decl, template };
44
+ const old = entries.get(prop);
45
+ if (!old?.important || entry.important) entries.set(prop, entry);
46
+ if (prop === "background" && (!entries.get("background-color")?.important || entry.important)) entries.delete("background-color");
47
+ if (prop === "background-color" && entries.get("background")?.important && !entry.important) entries.delete("background-color");
48
+ });
49
+ if (!template) { externalStyles ||= !!entries.size || !!reason; return; }
50
+ const fact = { entries, reason }, variants = templates.get(template) ?? new Map();
51
+ variants.set(signature(fact), fact);
52
+ templates.set(template, variants);
53
+ }
54
+ function get(classes) {
55
+ if (memo.has(classes)) return memo.get(classes);
56
+ const entries = new Map();
57
+ let reason = classes.reason ?? (classes.names.some(name => unknownTargets || targetedHooks.has(name)) ? "A named class may be targeted by captured paint selectors." : undefined);
58
+ function merge(fact) {
59
+ reason ??= fact.reason;
60
+ for (const [name, entry] of fact.entries) {
61
+ const old = entries.get(name);
62
+ // Class order does not establish stylesheet order, even across choices.
63
+ if (old && old.value !== entry.value) reason ??= "Composed classes set competing paint declarations.";
64
+ if (name === "background" && entries.has("background-color") || name === "background-color" && entries.has("background"))
65
+ reason ??= "Composed background shorthand and longhand declarations need the rendered cascade.";
66
+ entries.set(name, entry);
67
+ }
68
+ }
69
+ for (const template of classes.templates) {
70
+ const variants = templates.get(template);
71
+ if (!variants) { reason ??= "A style template has no complete captured paint facts."; continue; }
72
+ if (variants.size !== 1) { reason ??= "Interpolated paint alternatives do not establish one definite cascade."; continue; }
73
+ merge(variants.values().next().value);
74
+ }
75
+ for (const choice of classes.choices ?? []) {
76
+ const alternatives = choice.map(get), first = alternatives[0];
77
+ if (!first || alternatives.some(fact => fact.reason || signature(fact) !== signature(first))) {
78
+ reason ??= "Class alternatives do not establish identical paint and visibility.";
79
+ continue;
80
+ }
81
+ merge(first);
82
+ }
83
+ const fact = { entries, reason };
84
+ memo.set(classes, fact);
85
+ return fact;
86
+ }
87
+ return { record, get, get hasColor() { return hasColor; }, get externalStyles() { return externalStyles; } };
88
+ }
@@ -21,6 +21,8 @@ export const findingRules = Object.freeze({
21
21
  "brand-coverage": "error", "brand-empty": "error", "brand-license": "error", "brand-new-token": "error", "brand-readme": "error",
22
22
  // Artwork may be used by code ADS cannot trace (a CMS, a server template).
23
23
  "brand-unused": "review",
24
+ "pictogram-catalog": "error", "pictogram-source": "error", "pictogram-render": "error",
25
+ "pictogram-unresolved": "review",
24
26
  "control-padding": "error",
25
27
  // Explicit artwork/text relationships, not universal artwork geometry.
26
28
  "lockup-construction": "error",
@@ -1,10 +1,9 @@
1
- import { existsSync, readFileSync } from "node:fs";
2
1
  import path from "node:path";
3
- import postcss from "postcss";
4
2
  import valueParser from "postcss-value-parser";
5
3
  import { contextValues } from "./themes.mjs";
6
4
  import { findingSeverity } from "./finding-rules.mjs";
7
- import { fontFaces, preloadFace } from "./fonts-generated.mjs";
5
+ import { fontFacesFromCss, preloadFace } from "./fonts-generated.mjs";
6
+ import { optionalSourceText, sourceCss, memoProgram } from "./analysis/helpers.mjs";
8
7
 
9
8
  /** Fonts a project declares in tokens/fonts.css, against the weights its CSS uses. Without a declared
10
9
  * face it finds nothing: a system font stack has no files and no faces to fake.
@@ -14,26 +13,32 @@ const unquote = value => value.trim().replace(/^["']|["']$/g, "");
14
13
  const keyword = { normal: 400, bold: 700 };
15
14
  const weightOf = value => { const number = Number(value); return Number.isFinite(number) && number >= 1 && number <= 1000 ? number : keyword[value?.toLowerCase()]; };
16
15
 
17
- function declaredFaces(file) {
18
- const faces = [];
19
- postcss.parse(readFileSync(file, "utf8")).walkAtRules(/^font-face$/i, rule => {
20
- const read = name => rule.nodes.find(node => node.type === "decl" && node.prop.toLowerCase() === name)?.value;
21
- const url = /url\(\s*["']?([^"')]+)["']?\s*\)/i.exec(read("src") ?? "")?.[1], weight = read("font-weight")?.trim().toLowerCase();
22
- const parts = weight && weight !== "auto" ? weight.split(/\s+/).map(weightOf) : null;
23
- faces.push({ family: unquote(read("font-family") ?? ""), url, low: parts?.[0], high: parts?.[1] ?? parts?.[0], auto: !parts, display: read("font-display")?.trim().toLowerCase(), italic: /italic|oblique/i.test(read("font-style") ?? ""), ranged: !!read("unicode-range"), line: rule.source.start.line });
16
+ function declaredFaces(css) {
17
+ return memoProgram(css, "font-declared-faces", () => {
18
+ const faces = [];
19
+ css.walkAtRules(/^font-face$/i, rule => {
20
+ const read = name => rule.nodes.find(node => node.type === "decl" && node.prop.toLowerCase() === name)?.value;
21
+ const url = /url\(\s*["']?([^"')]+)["']?\s*\)/i.exec(read("src") ?? "")?.[1], weight = read("font-weight")?.trim().toLowerCase();
22
+ const parts = weight && weight !== "auto" ? weight.split(/\s+/).map(weightOf) : null;
23
+ faces.push({ family: unquote(read("font-family") ?? ""), url, low: parts?.[0], high: parts?.[1] ?? parts?.[0], auto: !parts, display: read("font-display")?.trim().toLowerCase(), italic: /italic|oblique/i.test(read("font-style") ?? ""), ranged: !!read("unicode-range"), line: rule.source.start.line });
24
+ });
25
+ return Object.freeze(faces.map(Object.freeze));
24
26
  });
25
- return faces;
26
27
  }
27
28
 
28
29
  export function createFontRules({ root, dsRoot, config }, tokens) {
29
30
  const file = path.join(dsRoot, config.tokenDir, "fonts.css");
30
- let faces = [];
31
- try { if (existsSync(file)) faces = declaredFaces(file); } catch { /* The core CSS syntax diagnostic owns a malformed sheet. */ }
31
+ let faces = [], sheet = [];
32
+ try {
33
+ if (optionalSourceText(file) !== null) {
34
+ const css = sourceCss(file);
35
+ faces = declaredFaces(css);
36
+ sheet = fontFacesFromCss(css);
37
+ }
38
+ } catch { /* The core CSS syntax diagnostic owns a malformed sheet. */ }
32
39
  const relative = target => path.relative(root, target).replaceAll("\\", "/");
33
40
  // A named preload that fonts.css cannot satisfy is an error, so a typo cannot silently lose it.
34
41
  const preloadFindings = () => (config.assets.preloadFonts ?? []).flatMap(entry => {
35
- let sheet = [];
36
- try { if (existsSync(file)) sheet = fontFaces(readFileSync(file, "utf8")); } catch { /* The core CSS syntax diagnostic owns a malformed sheet. */ }
37
42
  if (preloadFace(sheet, entry)) return [];
38
43
  const known = sheet.some(face => face.family === entry.family);
39
44
  return [{ rule: "font-preload-config", severity: findingSeverity("font-preload-config"), file: "ds.config.json", line: 1, column: 1, guidanceUri: "ads://guides/performance",
@@ -1,7 +1,7 @@
1
- import { existsSync, readFileSync } from "node:fs";
2
1
  import path from "node:path";
3
2
  import postcss from "postcss";
4
3
  import { resolveValue } from "./themes.mjs";
4
+ import { optionalSourceText, sourceCss, memoProgram } from "./analysis/helpers.mjs";
5
5
 
6
6
  /** fonts.preload.generated.ts names the font files the first text uses: assets.preloadFonts when the
7
7
  * project lists them, otherwise read from the sheets: the first family in base.css's body font-family
@@ -16,16 +16,23 @@ const unquote = value => value.trim().replace(/^["']|["']$/g, "");
16
16
  const formats = { woff2: "font/woff2", woff: "font/woff", ttf: "font/ttf", otf: "font/otf" };
17
17
 
18
18
  export function fontFaces(text) {
19
- const faces = [];
20
- postcss.parse(text).walkAtRules(/^font-face$/i, rule => {
21
- const value = name => rule.nodes.find(node => node.type === "decl" && node.prop.toLowerCase() === name)?.value;
22
- const url = /url\(\s*["']?([^"')]+)["']?\s*\)/i.exec(value("src") ?? "")?.[1];
23
- if (!url || /^data:/i.test(url)) return;
24
- const auto = !value("font-weight") || /^auto$/i.test(value("font-weight").trim());
25
- const [low, high = low] = (auto ? "400" : value("font-weight")).replace(/\bnormal\b/, "400").replace(/\bbold\b/, "700").trim().split(/\s+/).map(Number);
26
- faces.push({ family: unquote(value("font-family") ?? ""), url, auto, low, high, slant: (value("font-style") ?? "normal").trim().toLowerCase(), range: value("unicode-range") });
19
+ return fontFacesFromCss(postcss.parse(text));
20
+ }
21
+
22
+ /** Share read-only CSS facts with validation; selection still depends on current config/tokens. */
23
+ export function fontFacesFromCss(css) {
24
+ return memoProgram(css, "font-preload-faces", () => {
25
+ const faces = [];
26
+ css.walkAtRules(/^font-face$/i, rule => {
27
+ const value = name => rule.nodes.find(node => node.type === "decl" && node.prop.toLowerCase() === name)?.value;
28
+ const url = /url\(\s*["']?([^"')]+)["']?\s*\)/i.exec(value("src") ?? "")?.[1];
29
+ if (!url || /^data:/i.test(url)) return;
30
+ const auto = !value("font-weight") || /^auto$/i.test(value("font-weight").trim());
31
+ const [low, high = low] = (auto ? "400" : value("font-weight")).replace(/\bnormal\b/, "400").replace(/\bbold\b/, "700").trim().split(/\s+/).map(Number);
32
+ faces.push({ family: unquote(value("font-family") ?? ""), url, auto, low, high, slant: (value("font-style") ?? "normal").trim().toLowerCase(), range: value("unicode-range") });
33
+ });
34
+ return Object.freeze(faces.map(Object.freeze));
27
35
  });
28
- return faces;
29
36
  }
30
37
 
31
38
  /** Whether a unicode-range covers Latin capital A, the subset first text needs. */
@@ -35,10 +42,10 @@ const coversLatin = range => !range || range.split(",").some(part => { const [fi
35
42
  export const preloadFace = (faces, { family, weight }) => faces.find(face => face.family === family && face.slant === "normal" && coversLatin(face.range) &&( face.auto || face.low <= weight && weight <= face.high));
36
43
 
37
44
  /** The font and weight of the body and of headings, as base.css sets them. */
38
- function firstTextFonts(text, values) {
45
+ function firstTextFonts(css, values) {
39
46
  const read = pattern => {
40
47
  const found = {};
41
- postcss.parse(text).walkRules(rule => {
48
+ css.walkRules(rule => {
42
49
  if (!rule.selector.split(",").some(item => pattern.test(item.trim()))) return;
43
50
  for (const node of rule.nodes) if (node.type === "decl" && ["font-family", "font-weight"].includes(node.prop.toLowerCase())) found[node.prop.toLowerCase()] = node.value;
44
51
  });
@@ -55,9 +62,9 @@ function firstTextFonts(text, values) {
55
62
  export function fontPreloadText({ dsRoot, config }, values) {
56
63
  const directory = path.join(dsRoot, config.tokenDir), fontsFile = path.join(directory, "fonts.css"), baseFile = path.join(directory, "base.css");
57
64
  const named = config.assets.preloadFonts;
58
- if (!existsSync(fontsFile) || !named && !existsSync(baseFile)) return null;
65
+ if (optionalSourceText(fontsFile) === null || !named && optionalSourceText(baseFile) === null) return null;
59
66
  let faces, uses;
60
- try { faces = fontFaces(readFileSync(fontsFile, "utf8")); uses = named ? [] : firstTextFonts(readFileSync(baseFile, "utf8"), values); }
67
+ try { faces = fontFacesFromCss(sourceCss(fontsFile)); uses = named ? [] : firstTextFonts(sourceCss(baseFile), values); }
61
68
  catch { return null; /* The core CSS syntax diagnostic owns malformed sheets. */ }
62
69
  const urls = new Set();
63
70
  // Named in the config: exactly these, and font-preload-config reports one fonts.css does not have.
@@ -4,6 +4,7 @@ import { validTokenSamples } from "./token-samples.mjs";
4
4
  import postcss from "postcss";
5
5
  import spatial from "./spatial-model.cjs";
6
6
  import { inspectSpatial } from "./spatial.mjs";
7
+ import { pictogramViews } from "./pictograms.mjs";
7
8
 
8
9
  // Definition metadata is project data. Markup, layout and interaction belong to
9
10
  // the tool template, shared by the native showcase and MCP preview resource graph.
@@ -198,8 +199,8 @@ export function foundationViews(options, inventory) {
198
199
  report(error.message);
199
200
  }
200
201
  const directory = path.join(dsRoot, "assets/brand");
201
- // Subfolders such as pictograms/ are brand artwork too: the brand checks
202
- // walk them, so the view shows them under their relative names.
202
+ // Brand subfolders remain visible under their relative names. Catalogued
203
+ // pictograms have their own owner and gallery, outside assets/brand/.
203
204
  const brandFiles = (folder, prefix = "") => {
204
205
  const stat = lstatSync(folder, { throwIfNoEntry: false });
205
206
  if (!stat || stat.isSymbolicLink() || !stat.isDirectory()) return [];
@@ -234,5 +235,8 @@ export function foundationViews(options, inventory) {
234
235
  file: artwork[0].file,
235
236
  foundation: { schemaVersion: 1, kind: "brand", title: "Brand assets", artwork },
236
237
  });
238
+ const pictograms = pictogramViews(options);
239
+ views.push(...pictograms.views);
240
+ diagnostics.push(...pictograms.diagnostics);
237
241
  return { views: views.map((view) => ({ ...view, artifact: `.ds/scenarios/${view.id}/index.html` })), diagnostics };
238
242
  }