@reqvire-org/ads 0.4.2 → 0.4.3

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 (62) hide show
  1. package/README.md +10 -1
  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/check-service.mjs +8 -5
  11. package/dist/check.mjs +8 -3
  12. package/dist/component-contrast.mjs +126 -8
  13. package/dist/contrast-composition.mjs +134 -0
  14. package/dist/finding-rules.mjs +2 -0
  15. package/dist/font-rules.mjs +20 -15
  16. package/dist/fonts-generated.mjs +21 -14
  17. package/dist/foundation-views.mjs +6 -2
  18. package/dist/image-attributes.mjs +96 -92
  19. package/dist/mcp/drafts.mjs +6 -4
  20. package/dist/mcp/mutations.mjs +11 -8
  21. package/dist/mcp/preview-widget.bundle.js +43 -43
  22. package/dist/mcp/server.mjs +9 -2
  23. package/dist/pictogram-model.mjs +59 -0
  24. package/dist/pictograms.mjs +52 -0
  25. package/dist/preview-bun.mjs +1 -0
  26. package/dist/render-audit/image-shape.mjs +13 -3
  27. package/dist/render-audit/pictograms.mjs +88 -0
  28. package/dist/render-audit/worker.mjs +12 -0
  29. package/dist/render-audit.mjs +11 -1
  30. package/dist/render-composition.mjs +164 -0
  31. package/dist/scenario-registry.mjs +2 -2
  32. package/dist/scenarios-compiler.mjs +1 -1
  33. package/dist/showcase/client.bundle.js +23 -23
  34. package/dist/showcase/draft-navigation.js +5 -5
  35. package/dist/showcase/foundation-view.css +3 -0
  36. package/dist/showcase/foundation-view.mjs +3 -0
  37. package/dist/showcase/pictogram-view.mjs +53 -0
  38. package/dist/showcase/ui/ui.js +2 -0
  39. package/dist/skills/ads-designer/SKILL.md +13 -1
  40. package/dist/skills/ads-designer/references/accessibility.md +66 -2
  41. package/dist/skills/ads-designer/references/branding.md +5 -16
  42. package/dist/skills/ads-designer/references/performance.md +3 -2
  43. package/dist/skills/ads-designer/references/pictograms.md +131 -0
  44. package/dist/skills/ads-port/SKILL.md +4 -1
  45. package/dist/source-values.mjs +4 -1
  46. package/dist/starters/react/design-system/assets/pictograms/catalog.ads.json +13 -0
  47. package/dist/starters/react/design-system/assets/pictograms/journey.dark.svg +7 -0
  48. package/dist/starters/react/design-system/assets/pictograms/journey.svg +7 -0
  49. package/dist/starters/react/design-system/components/Content/Pictogram/Pictogram.ads.exports.ts +1 -0
  50. package/dist/starters/react/design-system/components/Content/Pictogram/Pictogram.ads.fixture.ts +1 -0
  51. package/dist/starters/react/design-system/components/Content/Pictogram/Pictogram.ads.scenario.tsx +7 -0
  52. package/dist/starters/react/design-system/components/Content/Pictogram/Pictogram.tsx +26 -0
  53. package/dist/task-cache.mjs +2 -2
  54. package/dist/units.mjs +4 -4
  55. package/dist/validation-inputs.mjs +7 -3
  56. package/docs/ADS.md +6 -1
  57. package/docs/ARCHITECTURE.md +75 -2
  58. package/docs/CACHING.md +25 -0
  59. package/docs/CHANGELOG.md +75 -52
  60. package/docs/GUIDE.md +30 -5
  61. package/docs/MCP.md +6 -0
  62. package/package.json +2 -1
@@ -668,6 +668,11 @@ export async function createAdsMcp(
668
668
  name: "Brand artwork, icons, committed targets and glyph sets",
669
669
  mimeType: "text/markdown",
670
670
  },
671
+ {
672
+ uri: "ads://guides/pictograms",
673
+ name: "Pictogram artwork, theme variants and usage guards",
674
+ mimeType: "text/markdown",
675
+ },
671
676
  {
672
677
  uri: "ads://guides/accessibility",
673
678
  name: "WCAG 2.2 AA guards and accessibility practice",
@@ -938,6 +943,8 @@ export async function createAdsMcp(
938
943
  },
939
944
  ],
940
945
  };
946
+ if (uri === "ads://guides/pictograms")
947
+ return { contents: [{ uri, mimeType: "text/markdown", text: readFileSync(new URL("../skills/ads-designer/references/pictograms.md", import.meta.url), "utf8") }] };
941
948
  if (uri === "ads://guides/tokens")
942
949
  return {
943
950
  contents: [
@@ -1523,9 +1530,9 @@ export async function createAdsMcp(
1523
1530
  {
1524
1531
  name: "ads_scenarios",
1525
1532
  description:
1526
- "Find an independently mountable brand, token, component, pattern or composition preview. IDs derive from source filenames. Optional group labels are derived from folder names and searchable; group is discovery output, never scenario metadata. covers lists rendered public UI, exercises lists behavioral APIs and tokens lists the real token inputs. Use ads_show_scenario with an exact returned id. Showcase and MCP use this same registry.",
1533
+ "Find an independently mountable brand, pictogram, token, component, pattern or composition preview. Authored IDs derive from source filenames; pictogram IDs come from their catalogue. Optional group labels are derived from folder names and searchable; group is discovery output, never scenario metadata. covers lists rendered public UI, exercises lists behavioral APIs and tokens lists the real token inputs. Use ads_show_scenario with an exact returned id. Showcase and MCP use this same registry.",
1527
1534
  schema: query.extend({
1528
- kind: z.enum(["brand", "tokens", "components", "patterns", "composition"]).optional(),
1535
+ kind: z.enum(["brand", "pictograms", "tokens", "components", "patterns", "composition"]).optional(),
1529
1536
  offset: z.number().int().min(0).default(0),
1530
1537
  }),
1531
1538
  call: async ({ query: search = "", limit, kind, offset }) => {
@@ -0,0 +1,59 @@
1
+ import { SaxesParser } from "saxes";
2
+
3
+ const object = value => value !== null && typeof value === "object" && !Array.isArray(value);
4
+ const fail = message => { throw new Error(message); };
5
+ const text = value => typeof value === "string" && value.trim().length > 0;
6
+ const keys = (value, allowed, label) => {
7
+ if (!object(value) || Object.keys(value).some(key => !allowed.includes(key))) fail(`${label} has unsupported fields.`);
8
+ };
9
+ const source = value => {
10
+ if (!text(value) || !/^[\w./-]+\.svg$/.test(value) || value.startsWith("/") || value.split("/").some(part => !part || part === "." || part === ".."))
11
+ fail("Pictogram sources must be relative .svg paths inside assets/pictograms/, without parent traversal.");
12
+ };
13
+
14
+ /** Pure catalogue contract. Theme names and schemes are separate from brands. */
15
+ export function parsePictogramCatalog(contents, themes) {
16
+ const data = JSON.parse(contents);
17
+ keys(data, ["schemaVersion", "pictograms"], "Pictogram catalogue");
18
+ if (data.schemaVersion !== 1 || !Array.isArray(data.pictograms) || data.pictograms.length > 512)
19
+ fail("Expected schemaVersion: 1 and pictograms (at most 512 entries).");
20
+ const ids = new Set(), names = themes.map(theme => theme.name);
21
+ return data.pictograms.map(item => {
22
+ keys(item, ["id", "title", "description", "license", "source", "themes", "schemes", "minHeight"], "Pictogram");
23
+ if (typeof item.id !== "string" || !/^[\w-]+$/.test(item.id) || ids.has(item.id)) fail("Each pictogram needs a unique id containing letters, digits, underscores or hyphens.");
24
+ ids.add(item.id);
25
+ for (const field of ["title", "description", "license"]) if (!text(item[field])) fail(`${item.id}: supply ${field}.`);
26
+ if (item.source !== undefined) source(item.source);
27
+ for (const [field, allowed] of [["themes", names], ["schemes", ["light", "dark"]]]) if (item[field] !== undefined) {
28
+ keys(item[field], allowed, `${item.id}.${field}`);
29
+ for (const file of Object.values(item[field])) source(file);
30
+ }
31
+ const minHeight = item.minHeight === undefined ? 48 : item.minHeight;
32
+ if (!Number.isFinite(minHeight) || minHeight <= 0 || minHeight > 1024) fail(`${item.id}: minHeight must be greater than zero and at most 1024 CSS pixels.`);
33
+ const variants = Object.fromEntries(themes.map(theme => {
34
+ const exact = item.themes && Object.hasOwn(item.themes, theme.name) ? item.themes[theme.name] : undefined;
35
+ const file = exact ?? item.schemes?.[theme.scheme] ?? item.source;
36
+ if (!file) fail(`${item.id}: no artwork for theme ${theme.name}. Declare a theme, scheme or shared source.`);
37
+ return [theme.name, file];
38
+ }));
39
+ const files = [...new Set([item.source, ...Object.values(item.themes ?? {}), ...Object.values(item.schemes ?? {})].filter(Boolean))];
40
+ if (!files.length) fail(`${item.id}: declare at least one artwork source.`);
41
+ return { id: item.id, title: item.title, description: item.description, license: item.license, minHeight, variants, files };
42
+ });
43
+ }
44
+
45
+ /** Parse XML once; geometry is constrained, the artist's palette and shapes are not. */
46
+ export function pictogramGeometry(contents) {
47
+ const parser = new SaxesParser({ xmlns: true });
48
+ let root;
49
+ parser.on("opentag", node => { root ??= node; });
50
+ parser.write(contents).close();
51
+ if (root?.local !== "svg" || root.uri !== "http://www.w3.org/2000/svg") fail("Expected an SVG document with the SVG namespace.");
52
+ const viewBox = root.attributes.viewBox?.value?.trim().split(/[\s,]+/).map(Number);
53
+ if (viewBox?.length !== 4 || !viewBox.every(Number.isFinite) || viewBox[2] <= 0 || viewBox[3] <= 0)
54
+ fail("Supply a finite viewBox with positive width and height; non-square artwork is welcome.");
55
+ const preserveAspectRatio = root.attributes.preserveAspectRatio?.value ?? "xMidYMid meet";
56
+ if (!/^(?:defer\s+)?x(?:Min|Mid|Max)Y(?:Min|Mid|Max)(?:\s+meet)?$/.test(preserveAspectRatio.trim()))
57
+ fail("Preserve the artwork's proportions with a meet alignment; none stretches it and slice crops it.");
58
+ return { x: viewBox[0], y: viewBox[1], width: viewBox[2], height: viewBox[3], preserveAspectRatio };
59
+ }
@@ -0,0 +1,52 @@
1
+ import path from "node:path";
2
+ import { createHash } from "node:crypto";
3
+ import { currentAnalysis } from "./analysis/context.mjs";
4
+ import { memoFact, memoProgram, optionalSourceText } from "./analysis/helpers.mjs";
5
+ import { parsePictogramCatalog, pictogramGeometry } from "./pictogram-model.mjs";
6
+
7
+ export const pictogramCatalog = "assets/pictograms/catalog.ads.json";
8
+ const freeze = value => {
9
+ if (value && typeof value === "object" && !Object.isFrozen(value)) { Object.values(value).forEach(freeze); Object.freeze(value); }
10
+ return value;
11
+ };
12
+
13
+ /** Shared check/discovery adapter. Only captured inputs, with weak revision ownership. */
14
+ export function inspectPictograms(options) {
15
+ const directory = path.join(options.dsRoot, "assets/pictograms"), catalog = path.join(options.dsRoot, pictogramCatalog);
16
+ const relative = file => path.relative(options.root, file).replaceAll("\\", "/");
17
+ const capture = () => {
18
+ const contents = optionalSourceText(catalog), diagnostics = [], pictograms = [];
19
+ const report = (rule, file, message) => diagnostics.push({ rule, file: relative(file), line: 1, column: 1, message, guidanceUri: "ads://guides/pictograms" });
20
+ if (contents === null) return freeze({ pictograms, diagnostics });
21
+ let entries;
22
+ try { entries = parsePictogramCatalog(contents, options.config.themes); }
23
+ catch (error) { report("pictogram-catalog", catalog, error.message); return freeze({ pictograms, diagnostics }); }
24
+ const assets = new Map();
25
+ for (const entry of entries) {
26
+ for (const name of entry.files) if (!assets.has(name)) {
27
+ const file = path.join(directory, name), svg = optionalSourceText(file);
28
+ assets.set(name, null);
29
+ if (svg === null) { report("pictogram-source", catalog, `${entry.id}: missing ${name}.`); continue; }
30
+ if (Buffer.byteLength(svg) > 1024 * 1024) { report("pictogram-source", file, "A pictogram must fit within 1 MiB; simplify or optimize the SVG."); continue; }
31
+ try {
32
+ const geometry = pictogramGeometry(svg);
33
+ assets.set(name, { file: relative(file), geometry, digest: createHash("sha256").update(svg).digest("hex"), src: `data:image/svg+xml;base64,${Buffer.from(svg).toString("base64")}` });
34
+ } catch (error) { report("pictogram-source", file, error.message); }
35
+ }
36
+ if (entry.files.some(name => !assets.get(name))) continue;
37
+ pictograms.push({ ...entry, file: relative(catalog), assets: Object.fromEntries(entry.files.map(name => [name, assets.get(name)])) });
38
+ }
39
+ return freeze({ pictograms, diagnostics });
40
+ };
41
+ const context = currentAnalysis(), key = `pictograms:${directory}:${JSON.stringify(options.config.themes)}`;
42
+ return context ? memoFact(context, key, () => context.revision ? memoProgram(context.revision, key, capture) : capture()) : capture();
43
+ }
44
+
45
+ export function pictogramViews(options) {
46
+ const { pictograms, diagnostics } = inspectPictograms(options);
47
+ return { diagnostics, views: pictograms.map(item => ({
48
+ id: `pictograms/${item.id}`, kind: "pictograms", unit: "assets/pictograms", title: item.title,
49
+ covers: [], tokens: [], file: item.file,
50
+ foundation: { schemaVersion: 1, kind: "pictograms", title: item.title, pictogram: item },
51
+ })) };
52
+ }
@@ -23,6 +23,7 @@ export const previewFrameFiles = [
23
23
  ...["mjs", "css", "d.mts"].map((extension) => `preview-frame.ads.review.${extension}`),
24
24
  "foundation-view.mjs",
25
25
  "foundation-view.css",
26
+ "pictogram-view.mjs",
26
27
  "ui/ui.js",
27
28
  "ui/ui.css",
28
29
  ].map((file) => fileURLToPath(new URL(`${previewFrameDirectory}${file}`, import.meta.url)));
@@ -27,10 +27,20 @@ export function imageShape({ nodeLimit }) {
27
27
  const width = Number(image.getAttribute("width")), height = Number(image.getAttribute("height"));
28
28
  const attributes = width > 0 && height > 0 ? width / height : undefined;
29
29
  if (explicit === undefined &&( attributes === undefined || style.objectFit !== "fill")) continue;
30
- const declared = explicit ?? attributes, rendered = box.width / box.height;
30
+ // CSS's used dimensions are untransformed: a rotated image's axis-aligned
31
+ // bounding rectangle has a different ratio even when the image is correct.
32
+ // An explicit CSS ratio applies to the box chosen by box-sizing. Attribute
33
+ // ratios describe the image content, never its decorative frame.
34
+ const insetX = [style.borderLeftWidth, style.borderRightWidth, style.paddingLeft, style.paddingRight].reduce((sum, value) => sum + parseFloat(value), 0);
35
+ const insetY = [style.borderTopWidth, style.borderBottomWidth, style.paddingTop, style.paddingBottom].reduce((sum, value) => sum + parseFloat(value), 0);
36
+ const borderBox = style.boxSizing === "border-box";
37
+ const measuredWidth = parseFloat(style.width) - (borderBox && explicit === undefined ? insetX : 0);
38
+ const measuredHeight = parseFloat(style.height) - (borderBox && explicit === undefined ? insetY : 0);
39
+ if (!Number.isFinite(measuredWidth) || !Number.isFinite(measuredHeight) || measuredWidth <= 0 || measuredHeight <= 0) continue;
40
+ const declared = explicit ?? attributes, rendered = measuredWidth / measuredHeight;
31
41
  // Rounding moves a small box by a pixel or so; 3% and 2 px of height is not rounding.
32
- if (Math.abs(rendered / declared - 1) <= 0.03 || Math.abs(box.width / declared - box.height) <= 2) continue;
33
- if (counts.shape++ < nodeLimit) issues.push({ kind: "shape", selector: selector(image), html: image.outerHTML.replace(/\s+/g, " ").slice(0, 200), rendered: `${Math.round(box.width)}x${Math.round(box.height)}`, declared: explicit !== undefined ? `aspect-ratio ${style.aspectRatio}` : `width and height ${width}x${height}` });
42
+ if (Math.abs(rendered / declared - 1) <= 0.03 || Math.abs(measuredWidth / declared - measuredHeight) <= 2) continue;
43
+ if (counts.shape++ < nodeLimit) issues.push({ kind: "shape", selector: selector(image), html: image.outerHTML.replace(/\s+/g, " ").slice(0, 200), rendered: `${Math.round(measuredWidth)}x${Math.round(measuredHeight)}`, declared: explicit !== undefined ? `aspect-ratio ${style.aspectRatio}` : `width and height ${width}x${height}` });
34
44
  }
35
45
  return { issues, counts };
36
46
  }
@@ -0,0 +1,88 @@
1
+ /** Serialized into the preview frame. Identify artwork by bytes, including unmarked
2
+ * imports; a data-ads-pictogram id disambiguates reuse and catches wrong sources.
3
+ * The audit owns/reuses sourceDigests across its viewport samples. */
4
+ export async function pictogramAudit({ pictograms, theme, nodeLimit, sourceDigests = {} }) {
5
+ const root = document.querySelector("#root"), issues = [], counts = {};
6
+ if (!root) return { issues, counts, sourceDigests };
7
+ const byId = new Map(pictograms.map(item => [item.id, item]));
8
+ const byDigest = new Map();
9
+ for (const item of pictograms) for (const asset of Object.values(item.assets)) {
10
+ const entries = byDigest.get(asset.digest) ?? [];
11
+ if (!entries.some(entry => entry.item.id === item.id)) entries.push({ item, asset });
12
+ byDigest.set(asset.digest, entries);
13
+ }
14
+ const selector = element => {
15
+ const parts = [];
16
+ for (let node = element; node && node !== root; node = node.parentElement) {
17
+ const siblings = [...node.parentElement.children].filter(child => child.localName === node.localName);
18
+ parts.unshift(`${node.localName}:nth-of-type(${siblings.indexOf(node) + 1})`);
19
+ }
20
+ return ["#root", ...parts].join(" > ");
21
+ };
22
+ const report = (image, id, reason, message, rule = "pictogram-render") => {
23
+ counts[reason] = (counts[reason] ?? 0) + 1;
24
+ if (counts[reason] <= nodeLimit) issues.push({ rule, selector: image ? selector(image) : "#root", id, reason, message });
25
+ };
26
+ const images = [...root.querySelectorAll(pictograms.length ? "img" : "img[data-ads-pictogram]")];
27
+ if (images.length > 1000) report(null, null, "limit", "Pictogram audit exceeds 1000 images; split the scenario to obtain complete evidence.");
28
+ for (const image of images.slice(0, 1000)) {
29
+ if (!image.checkVisibility({ checkOpacity: true, checkVisibilityCSS: true })) continue;
30
+ const declared = image.getAttribute("data-ads-pictogram"), src = image.currentSrc || image.src;
31
+ if (declared !== null && !byId.has(declared)) { report(image, declared, "unknown", `Unknown pictogram ${declared}. Use an id from assets/pictograms/catalog.ads.json.`); continue; }
32
+ // Ordinary imports are blob URLs. Do not issue extra network requests for
33
+ // unrelated remote images; explicit declarations opt into source checking.
34
+ if (declared === null && !/^(?:blob:|data:image\/svg\+xml[;,])/i.test(src)) continue;
35
+ if (!Object.hasOwn(sourceDigests, src)) {
36
+ try {
37
+ const response = await fetch(src);
38
+ if (!response.ok) throw new Error("Image could not be read");
39
+ if (!/image\/svg\+xml/i.test(response.headers.get("content-type") ?? "") || Number(response.headers.get("content-length")) > 1024 * 1024)
40
+ throw new Error("Not a supported SVG image");
41
+ const bytes = await response.arrayBuffer();
42
+ if (bytes.byteLength > 1024 * 1024) throw new Error("Image exceeds pictogram budget");
43
+ const digest = await crypto.subtle.digest("SHA-256", bytes);
44
+ sourceDigests[src] = [...new Uint8Array(digest)].map(byte => byte.toString(16).padStart(2, "0")).join("");
45
+ } catch { sourceDigests[src] = null; }
46
+ }
47
+ const digest = sourceDigests[src], matches = byDigest.get(digest) ?? [];
48
+ if (declared !== null && !digest) {
49
+ report(image, declared, "source", `${declared}: the SVG source could not be identified. Use a readable SVG import from the catalogue.`);
50
+ continue;
51
+ }
52
+ if (declared === null && !matches.length) continue;
53
+ if (declared === null && matches.length > 1) {
54
+ report(image, null, "ambiguous", "Artwork is shared by multiple pictogram ids. Add data-ads-pictogram to select its usage contract.", "pictogram-unresolved");
55
+ continue;
56
+ }
57
+ const activeTheme = image.closest("[data-theme]")?.getAttribute("data-theme") ?? theme;
58
+ const item = declared === null ? matches[0].item : byId.get(declared), expected = item.assets[item.variants[activeTheme]];
59
+ if (!expected || digest !== expected.digest) {
60
+ report(image, item.id, "theme", `${item.id}: use the declared artwork for theme ${activeTheme}; the displayed source does not match it.`);
61
+ continue;
62
+ }
63
+ if (!image.hasAttribute("alt")) report(image, item.id, "alt", `${item.id}: supply meaningful alt text, or alt="" when decorative.`);
64
+ if (!image.complete || !image.naturalWidth) { report(image, item.id, "load", `${item.id}: the artwork did not load.`); continue; }
65
+ const style = getComputedStyle(image), width = image.clientWidth - parseFloat(style.paddingLeft) - parseFloat(style.paddingRight), height = image.clientHeight - parseFloat(style.paddingTop) - parseFloat(style.paddingBottom);
66
+ const ratio = expected.geometry.width / expected.geometry.height;
67
+ const mismatch = Math.abs(width / height / ratio - 1) > 0.03 && Math.abs(width / ratio - height) > 2;
68
+ if (mismatch && ["fill", "cover"].includes(style.objectFit) || style.objectFit === "none" && (width < image.naturalWidth || height < image.naturalHeight))
69
+ report(image, item.id, "shape", `${item.id}: ${Math.round(width)}×${Math.round(height)}px crops or stretches the artwork. Preserve its proportions with height: auto or object-fit: contain.`);
70
+ const drawnHeight = ["contain", "scale-down"].includes(style.objectFit) ? Math.min(height, width / ratio, ...(style.objectFit === "scale-down" ? [image.naturalHeight] : [])) : height;
71
+ if (drawnHeight + 1 < item.minHeight)
72
+ report(image, item.id, "size", `${item.id}: artwork is ${Math.round(drawnHeight)}px high; its catalogue declares a minimum of ${item.minHeight}px.`);
73
+ }
74
+ return { issues, counts, sourceDigests };
75
+ }
76
+
77
+ export function pictogramFindings(runs, scenarios) {
78
+ const files = new Map(scenarios.map(scenario => [scenario.id, scenario.file])), groups = new Map();
79
+ for (const run of runs) for (const issue of run.pictograms ?? []) {
80
+ const key = JSON.stringify([run.scenario, issue.selector, issue.reason, issue.id]);
81
+ let item = groups.get(key);
82
+ if (!item) groups.set(key, item = { rule: issue.rule, severity: issue.rule === "pictogram-unresolved" ? "review" : "error", file: files.get(run.scenario) ?? run.scenario, line: 1, column: 1, source: "ads", scenario: run.scenario, themes: [], brands: [], nodes: [], guidanceUri: "ads://guides/pictograms", message: issue.message });
83
+ if (!item.themes.includes(run.theme)) item.themes.push(run.theme);
84
+ if (run.brand && !item.brands.includes(run.brand)) item.brands.push(run.brand);
85
+ item.nodes.push(issue);
86
+ }
87
+ return [...groups.values()];
88
+ }
@@ -8,6 +8,7 @@ import { nonTextContrast } from "./non-text-contrast.mjs";
8
8
  import { layoutOverflow } from "./layout-overflow.mjs";
9
9
  import { layoutShift } from "./layout-shift.mjs";
10
10
  import { imageShape } from "./image-shape.mjs";
11
+ import { pictogramAudit } from "./pictograms.mjs";
11
12
  import { auditRenderStates, listTargets } from "./render-states.mjs";
12
13
 
13
14
  // Runs only as an owned child, using the receiving project's browser dependency.
@@ -69,6 +70,9 @@ try {
69
70
  }));
70
71
  });
71
72
  try {
73
+ // Set before any App mounts, including nested/replaced frames. Only this
74
+ // worker disables decorative subject staging; captures keep showcase chrome.
75
+ await context.addInitScript(() => { globalThis.__ADS_RENDER_AUDIT__ = true; });
72
76
  // A bounded number of pages render at once; results keep request order.
73
77
  const results = [];
74
78
  let next = 0;
@@ -140,17 +144,25 @@ try {
140
144
  // The same page is resized: one evaluate per width, no new render.
141
145
  result.layout = [];
142
146
  result.imageShape = new Map();
147
+ result.pictograms = new Map();
148
+ let sourceDigests = {};
143
149
  for (const width of request.overflowWidths) {
144
150
  await page.setViewportSize({ width, height: request.viewport.height });
145
151
  result.layout.push({ width, ...(await frame.evaluate(layoutOverflow, { nodeLimit: request.nodeLimit, width })) });
146
152
  for (const issue of (await frame.evaluate(imageShape, { nodeLimit: request.nodeLimit })).issues)
147
153
  result.imageShape.set(issue.selector, { ...issue, width });
154
+ {
155
+ const audit = await frame.evaluate(pictogramAudit, { pictograms: request.pictograms, theme: app.theme, nodeLimit: request.nodeLimit, sourceDigests });
156
+ sourceDigests = audit.sourceDigests;
157
+ for (const issue of audit.issues) result.pictograms.set(`${issue.selector}:${issue.reason}`, { ...issue, width });
158
+ }
148
159
  }
149
160
  const assigned = await turns[index];
150
161
  await auditRenderStates({ page, frame, result, request, phoneWidth: request.overflowWidths[0], assigned });
151
162
  if (!contentSettled) result.coverage.skipped.push({ reason: "content-still-changing", name: "the page" });
152
163
  result.coverage.claimed = [...assigned.triggers, ...assigned.controls].map((item) => item.claim);
153
164
  result.imageShape = [...result.imageShape.values()];
165
+ result.pictograms = [...result.pictograms.values()];
154
166
  // Last: it narrows #root for good, at the widest viewport, as a pane in a window would be.
155
167
  // A scenario with the main landmark is a whole page, which no pane hosts.
156
168
  if (app.container && !(await frame.evaluate(() => !!document.querySelector('main, [role="main"]')))) {
@@ -12,6 +12,7 @@ import { inspectScenarios } from "./scenarios.mjs";
12
12
  import { inspectUnits } from "./units.mjs";
13
13
  import { globMatcher } from "./layout-widths.mjs";
14
14
  import { affectedScenarios } from "./verification.mjs";
15
+ import { pictogramFindings } from "./render-audit/pictograms.mjs";
15
16
 
16
17
  // Render audit: axe-core (Deque, MPL-2.0, an unmodified ADS dependency
17
18
  // injected at run time, never bundled) runs inside each rendered scenario document, once per
@@ -555,7 +556,7 @@ async function warmScenariosApart(host, ids, signal) {
555
556
 
556
557
  /** One browser process over the given renders. Its report grows as they finish, so a worker that
557
558
  * dies keeps what it finished. A browser that is not installed stops the audit. */
558
- async function runAuditWorker({ root, temporary, playwright, settings, apps, signal, claimed, pages }) {
559
+ async function runAuditWorker({ root, temporary, playwright, settings, apps, signal, claimed, pages, pictograms }) {
559
560
  const request = path.join(temporary, "request.json"),
560
561
  report = path.join(temporary, "report.json"),
561
562
  runId = randomUUID();
@@ -580,6 +581,7 @@ async function runAuditWorker({ root, temporary, playwright, settings, apps, sig
580
581
  nodeLimit: limits.nodes,
581
582
  concurrency: pages,
582
583
  apps,
584
+ pictograms,
583
585
  output: temporary,
584
586
  }),
585
587
  );
@@ -664,6 +666,12 @@ export async function runRenderAudit(
664
666
  { code: "ADS_AUDIT_UNAVAILABLE" },
665
667
  );
666
668
  const registry = await analyze(root, "registry", [], signal);
669
+ // Registry discovery already checked the captured SVGs. Send only their
670
+ // identity/geometry, not another copy of the artwork or a live filesystem read.
671
+ const pictograms = registry.scenarios.filter(item => item.foundation?.pictogram).map(({ foundation: { pictogram } }) => ({
672
+ id: pictogram.id, minHeight: pictogram.minHeight, variants: pictogram.variants,
673
+ assets: Object.fromEntries(Object.entries(pictogram.assets).map(([name, asset]) => [name, { digest: asset.digest, geometry: asset.geometry }])),
674
+ }));
667
675
  if (registry.diagnostics.length) throw new Error(`Scenario registration failed: ${registry.diagnostics[0].message}`);
668
676
  const unknown = (selected ?? []).filter((id) => !registry.scenarios.some((scenario) => scenario.id === id));
669
677
  if (unknown.length) throw new Error(`Unknown scenario ${unknown[0]}. Discover exact IDs with ads_scenarios.`);
@@ -755,6 +763,7 @@ export async function runRenderAudit(
755
763
  apps,
756
764
  signal,
757
765
  pages: options.config.mcp.auditPages,
766
+ pictograms,
758
767
  claimed: [...renders.values()].flatMap((render) => render.result?.coverage?.claimed ?? []),
759
768
  })
760
769
  : { runs: [], capped: [] };
@@ -794,6 +803,7 @@ export async function runRenderAudit(
794
803
  ...layoutOverflowFindings(runs, scenarios),
795
804
  ...layoutShiftFindings(runs, scenarios),
796
805
  ...imageShapeFindings(runs, scenarios),
806
+ ...pictogramFindings(runs, scenarios),
797
807
  ...unauditedFindings(
798
808
  all.filter((render) => !render.result),
799
809
  scenarios,
@@ -0,0 +1,164 @@
1
+ import ts from "./analysis/syntax.mjs";
2
+ import { memoProgram, walk, symbolAt, valueSymbolAt } from "./analysis/helpers.mjs";
3
+ import { isInside, isDevelopmentFile, isTestFile } from "./config.mjs";
4
+ import { createSourceValues, reference, isFunction } from "./source-values.mjs";
5
+
6
+ /** Source-only DOM relationships. Owned by the immutable program, not live paths.
7
+ * Rules consume these facts without constructing another compiler or executing UI.
8
+ * Uncertain branches stay uncertain: a sampled render is never proof of a cascade. */
9
+ export function renderComposition(program, options) {
10
+ return memoProgram(program, `render-composition:${options.dsRoot}`, () => build(program, options));
11
+ }
12
+
13
+ async function build(program, options) {
14
+ const checker = program.getTypeChecker(), bindings = new Map();
15
+ async function linaria(node, seen = new Set()) {
16
+ if (!node || seen.has(node)) return null;
17
+ if (bindings.has(node)) return bindings.get(node);
18
+ seen.add(node);
19
+ const base = ts.isPropertyAccessExpression(node) ? node.expression : node;
20
+ // Preserve import declarations here; unaliasing would lose the package name.
21
+ const symbol = await symbolAt(checker, base);
22
+ for (const decl of symbol?.declarations ?? []) {
23
+ if (ts.isImportSpecifier(decl) && ["@linaria/atomic", "@linaria/core"].includes(decl.parent.parent.parent.moduleSpecifier.text)) {
24
+ const result = (decl.propertyName ?? decl.name).text;
25
+ bindings.set(node, result);
26
+ return result;
27
+ }
28
+ if (ts.isNamespaceImport(decl) && ts.isPropertyAccessExpression(node) && ["@linaria/atomic", "@linaria/core"].includes(decl.parent.parent.moduleSpecifier.text)) {
29
+ bindings.set(node, node.name.text);
30
+ return node.name.text;
31
+ }
32
+ if (ts.isVariableDeclaration(decl) && decl.initializer && decl.parent.flags & ts.NodeFlags.Const) return linaria(decl.initializer, seen);
33
+ }
34
+ bindings.set(node, null);
35
+ return null;
36
+ }
37
+ const isCx = async node => await linaria(node) === "cx";
38
+ const values = createSourceValues(program, options, { preserveCall: isCx, strict: true });
39
+ const roots = [], nodes = [], limits = new Map();
40
+ const limit = (node, reason) => { if (!limits.has(reason)) limits.set(reason, { node, reason }); };
41
+
42
+ async function classes(input, context) {
43
+ const value = await values.resolve(input, values.next(context));
44
+ context = value.context ?? input.context ?? context;
45
+ if (value.kind === "literal") return !value.value || typeof value.value === "string"
46
+ ? { templates: [], names: typeof value.value === "string" ? value.value.split(/\s+/).filter(Boolean) : [] }
47
+ : { templates: [], names: [], reason: "A class value is not a string." };
48
+ if (value.kind === "union") {
49
+ const alternatives = [];
50
+ if (value.values.length > 64) return { templates: [], names: [], reason: "Class composition exceeds 64 alternatives." };
51
+ for (const item of value.values) alternatives.push(await classes(item, values.next(context)));
52
+ const first = alternatives[0];
53
+ if (first && alternatives.every(item => !item.reason && item.templates.length === first.templates.length && item.templates.every((template, i) => template === first.templates[i]) && item.names.join(" ") === first.names.join(" "))) return first;
54
+ return { templates: [], names: [], reason: "Class alternatives do not establish one definite style composition." };
55
+ }
56
+ if (value.kind === "node") {
57
+ if (ts.isTaggedTemplateExpression(value.node) && await linaria(value.node.tag) === "css") return { templates: [value.node], names: [] };
58
+ if (ts.isCallExpression(value.node) && await isCx(value.node.expression)) {
59
+ const result = { templates: [], names: [] };
60
+ for (const argument of value.node.arguments) {
61
+ const items = ts.isSpreadElement(argument)
62
+ ? await values.arrays(reference(argument.expression, value.env, value.via), values.next(context))
63
+ : [reference(argument, value.env, value.via)];
64
+ if (!items) { result.reason = "A class argument spread cannot be resolved."; continue; }
65
+ for (const item of items) {
66
+ const part = await classes(item, values.next(context));
67
+ result.templates.push(...part.templates); result.names.push(...part.names);
68
+ result.reason ??= part.reason;
69
+ }
70
+ }
71
+ return result;
72
+ }
73
+ }
74
+ return { templates: [], names: [], reason: value.reason ?? "A class or later prop spread cannot be resolved." };
75
+ }
76
+
77
+ async function render(input, parent, context, sites = new Set(), uncertain = false) {
78
+ if (nodes.length >= 20000 || context.depth > 48 || context.budget.steps > 16000) {
79
+ limit(input.node ?? parent?.node, "Render composition reached its depth or work limit.");
80
+ return;
81
+ }
82
+ const value = await values.resolve(input, values.next(context));
83
+ context = value.context ?? input.context ?? context;
84
+ if (value.kind === "union") {
85
+ if (value.values.length > 64) { limit(input.node ?? parent?.node, "Render composition exceeds 64 alternatives."); return; }
86
+ for (const branch of value.values) await render(branch, parent, values.next(context), sites, true);
87
+ return;
88
+ }
89
+ if (value.kind === "array") {
90
+ for (const child of value.values) await render(child, parent, values.next(context), sites, uncertain);
91
+ return;
92
+ }
93
+ if (value.kind === "literal") {
94
+ if (parent && (typeof value.value === "number" || typeof value.value === "string" && value.value.trim())) parent.text = true;
95
+ return;
96
+ }
97
+ if (value.kind !== "node") {
98
+ if (parent) parent.unknownText = value.reason ?? "Dynamic children cannot be established as text.";
99
+ return;
100
+ }
101
+ const { node, env, via } = value;
102
+ if (ts.isJsxText(node)) { if (parent && node.text.trim()) parent.text = true; return; }
103
+ if (ts.isJsxExpression(node)) return render(reference(node.expression, env, via), parent, values.next(context), sites, uncertain);
104
+ if (ts.isJsxFragment(node) || ts.isArrayLiteralExpression(node)) {
105
+ for (const child of node.children ?? node.elements) {
106
+ if (ts.isSpreadElement(child)) {
107
+ const items = await values.arrays(reference(child.expression, env, via), values.next(context));
108
+ if (!items) { if (parent) parent.unknownText = "Dynamic render array cannot be resolved."; continue; }
109
+ for (const item of items) await render(item, parent, values.next(context), sites, uncertain);
110
+ } else await render(reference(child, env, via), parent, values.next(context), sites, uncertain);
111
+ }
112
+ return;
113
+ }
114
+ if (!ts.isJsxElement(node) && !ts.isJsxSelfClosingElement(node)) {
115
+ if (parent) parent.unknownText = "The rendered child is outside source-resolvable JSX.";
116
+ return;
117
+ }
118
+ const opening = ts.isJsxElement(node) ? node.openingElement : node;
119
+ const props = values.props(opening, env, via);
120
+ if (ts.isJsxElement(node) && node.children.length) props.layers.push(new Map([["children", { kind: "array", values: node.children.map(child => reference(child, env, via)) }]]));
121
+ const property = async name => values.resolve(await values.get(props, name, values.next(context)), values.next(context));
122
+ const tag = opening.tagName.getText();
123
+ if (/^[a-z][\w-]*$/.test(tag)) {
124
+ // SVG paint, metadata and raw HTML have different text/render semantics.
125
+ // Their accessibility remains with the existing asset and browser guards.
126
+ if (["svg", "script", "style", "template", "title", "progress", "meter"].includes(tag)) return;
127
+ let classValue = await values.get(props, "className", values.next(context));
128
+ if (classValue.kind === "literal" && classValue.value === undefined) classValue = await values.get(props, "class", values.next(context));
129
+ const item = { node: opening, parent, tag, classes: await classes(classValue, context), children: [], text: false, uncertain, via, attributes: {} };
130
+ for (const name of ["style", "disabled", "aria-disabled", "hidden", "dangerouslySetInnerHTML"]) item.attributes[name] = await property(name);
131
+ nodes.push(item);
132
+ if (parent) parent.children.push(item); else roots.push(item);
133
+ await render(await values.get(props, "children", values.next(context)), item, values.next(context), sites, uncertain);
134
+ return;
135
+ }
136
+ // Fragments do not introduce a backdrop. Other external components (including
137
+ // portals) are boundaries, not transparent wrappers guessed from their names.
138
+ const symbol = await valueSymbolAt(checker, opening.tagName);
139
+ if (symbol?.name === "Fragment" && symbol.declarations?.every(decl => decl.getSourceFile().fileName.includes("/node_modules/")))
140
+ return render(await values.get(props, "children", values.next(context)), parent, values.next(context), sites, uncertain);
141
+ const target = await values.resolve(reference(opening.tagName, env, via), values.next(context));
142
+ if (target.kind !== "node" || !isFunction(target.node) || sites.has(node) || isDevelopmentFile(target.node.getSourceFile().fileName, options)) {
143
+ if (parent) parent.unknownText = `Component ${tag} cannot be traced to owned DOM here.`;
144
+ return;
145
+ }
146
+ const nested = new Set([...sites, node]);
147
+ const outputs = await values.returns(target, [props], values.next(context), "component");
148
+ for (const output of outputs) await render(output, parent, values.next(context), nested, uncertain || outputs.length > 1);
149
+ }
150
+
151
+ for (const source of await program.getSourceFiles()) {
152
+ if (!isInside(options.dsRoot, source.fileName) || source.isDeclarationFile || isDevelopmentFile(source.fileName, options) || isTestFile(source.fileName)) continue;
153
+ const sites = [];
154
+ walk(source, node => {
155
+ if (ts.isJsxElement(node) || ts.isJsxSelfClosingElement(node) || ts.isJsxFragment(node)) { sites.push(node); return false; }
156
+ });
157
+ for (const node of sites) await render(reference(node), null, { ...values.state(), maxSteps: 16000 });
158
+ }
159
+ for (const item of nodes) {
160
+ Object.freeze(item.classes.templates); Object.freeze(item.classes.names);
161
+ Object.freeze(item.classes); Object.freeze(item.children); Object.freeze(item.attributes); Object.freeze(item);
162
+ }
163
+ return Object.freeze({ roots: Object.freeze(roots), nodes: Object.freeze(nodes), limits: Object.freeze([...limits.values()]) });
164
+ }
@@ -51,10 +51,10 @@ function validRegistry(value, options) {
51
51
  value.scenarios.every(
52
52
  (item) =>
53
53
  typeof item?.id === "string" &&
54
- /^(?:brand|tokens|components|patterns|composition)\/[\w./-]+$/.test(item.id) &&
54
+ /^(?:brand|pictograms|tokens|components|patterns|composition)\/[\w./-]+$/.test(item.id) &&
55
55
  path.posix.normalize(item.id) === item.id &&
56
56
  typeof item.title === "string" &&
57
- ["brand", "tokens", "components", "patterns", "composition"].includes(item.kind) &&
57
+ ["brand", "pictograms", "tokens", "components", "patterns", "composition"].includes(item.kind) &&
58
58
  typeof item.file === "string" &&
59
59
  isInside(options.dsRoot, path.resolve(options.root, item.file)) &&
60
60
  item.artifact === `.ds/scenarios/${item.id}/index.html` &&
@@ -257,7 +257,7 @@ export function createPreviewCache(options, compilerFiles = []) {
257
257
  const valid = value.registry.every(
258
258
  (entry) =>
259
259
  typeof entry?.id === "string" &&
260
- /^(?:brand|tokens|components|patterns|composition)\/[\w./-]+$/.test(entry.id) &&
260
+ /^(?:brand|pictograms|tokens|components|patterns|composition)\/[\w./-]+$/.test(entry.id) &&
261
261
  path.posix.normalize(entry.id) === entry.id &&
262
262
  typeof entry.file === "string" &&
263
263
  isInside(options.dsRoot, path.resolve(root, entry.file)) &&