@reqvire-org/ads 0.3.49 → 0.3.50
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.
- package/README.md +36 -6
- package/dist/active-clock.mjs +34 -0
- package/dist/assets.mjs +20 -2
- package/dist/boundaries.mjs +2 -0
- package/dist/browser-audit/layout-overflow.mjs +57 -0
- package/dist/browser-audit/layout-shift.mjs +32 -0
- package/dist/browser-audit/non-text-contrast.mjs +87 -0
- package/dist/browser-audit/worker.mjs +36 -7
- package/dist/browser-audit.mjs +198 -22
- package/dist/check.mjs +14 -1
- package/dist/cli.mjs +7 -4
- package/dist/component-contrast.mjs +138 -0
- package/dist/config.mjs +12 -6
- package/dist/finding-rules.mjs +11 -1
- package/dist/fonts-generated.mjs +85 -0
- package/dist/image-attributes.mjs +110 -0
- package/dist/init.mjs +2 -0
- package/dist/layout-widths.mjs +184 -0
- package/dist/mcp/context.mjs +1 -1
- package/dist/mcp/mutations.mjs +7 -5
- package/dist/mcp/preview-watch.mjs +9 -8
- package/dist/mcp/server.mjs +6 -4
- package/dist/preview-files.mjs +3 -0
- package/dist/project-boundary.mjs +23 -0
- package/dist/project-documents.mjs +2 -1
- package/dist/scenarios-compiler.mjs +23 -3
- package/dist/showcase/client.bundle.js +11 -11
- package/dist/showcase/icons.js +5 -5
- package/dist/showcase/style.css +1 -1
- package/dist/skills/ads-break-ui/SKILL.md +8 -0
- package/dist/skills/ads-break-ui/references/atomic-styles.md +2 -0
- package/dist/skills/ads-break-ui/references/design-data.md +39 -0
- package/dist/skills/ads-break-ui/references/drafts.md +1 -1
- package/dist/skills/ads-break-ui/references/guarded-editing.md +1 -1
- package/dist/skills/ads-break-ui/references/validation.md +9 -5
- package/dist/skills/ads-designer/SKILL.md +24 -4
- package/dist/skills/ads-designer/references/accessibility.md +30 -13
- package/dist/skills/ads-designer/references/atomic-styles.md +2 -0
- package/dist/skills/ads-designer/references/branding.md +10 -5
- package/dist/skills/ads-designer/references/cli.md +2 -1
- package/dist/skills/ads-designer/references/design-data.md +39 -0
- package/dist/skills/ads-designer/references/drafts.md +1 -1
- package/dist/skills/ads-designer/references/guarded-editing.md +1 -1
- package/dist/skills/ads-designer/references/mobile.md +3 -0
- package/dist/skills/ads-designer/references/performance.md +89 -0
- package/dist/skills/ads-designer/references/validation.md +9 -5
- package/dist/skills/ads-import/references/atomic-styles.md +2 -0
- package/dist/skills/ads-import/references/cli.md +2 -1
- package/dist/skills/ads-import/references/design-data.md +39 -0
- package/dist/skills/ads-import/references/drafts.md +1 -1
- package/dist/skills/ads-import/references/guarded-editing.md +1 -1
- package/dist/skills/ads-import/references/validation.md +9 -5
- package/dist/skills/ads-motion/references/atomic-styles.md +2 -0
- package/dist/skills/ads-motion/references/design-data.md +39 -0
- package/dist/skills/ads-motion/references/drafts.md +1 -1
- package/dist/skills/ads-motion/references/guarded-editing.md +1 -1
- package/dist/skills/ads-motion/references/validation.md +9 -5
- package/dist/skills/ads-port/references/atomic-styles.md +2 -0
- package/dist/skills/ads-port/references/cli.md +2 -1
- package/dist/skills/ads-port/references/design-data.md +39 -0
- package/dist/skills/ads-port/references/drafts.md +1 -1
- package/dist/skills/ads-port/references/guarded-editing.md +1 -1
- package/dist/skills/ads-port/references/validation.md +9 -5
- package/dist/starters/preact/ds.config.json +1 -0
- package/dist/starters/preact/package.json +1 -0
- package/dist/starters/react/ADS.md +1 -1
- package/dist/starters/react/README.md +14 -2
- package/dist/starters/react/design-system/components/Actions/Button/Button.tsx +1 -1
- package/dist/starters/react/design-system/components/Content/Image/Image.ads.fixture.ts +2 -0
- package/dist/starters/react/design-system/components/Content/Image/Image.ads.scenario.tsx +13 -0
- package/dist/starters/react/design-system/components/Content/Image/Image.tsx +48 -0
- package/dist/starters/react/design-system/components/Content/Image/README.md +20 -0
- package/dist/starters/react/design-system/components/Content/Logo/Logo.tsx +2 -2
- package/dist/starters/react/design-system/index.ts +1 -0
- package/dist/starters/react/design-system/tokens/Layout.ads.fixture.ts +16 -0
- package/dist/starters/react/design-system/tokens/spacing.css +18 -0
- package/dist/starters/react/ds.config.json +1 -0
- package/dist/starters/react/package-lock.json +47 -0
- package/dist/starters/react/package.json +2 -1
- package/dist/test-boundaries.mjs +30 -1
- package/dist/themes-generated.mjs +15 -4
- package/dist/token-quality.mjs +27 -17
- package/dist/units.mjs +2 -1
- package/dist/validation-checks.mjs +5 -4
- package/dist/validation.mjs +1 -1
- package/dist/verification/browser.mjs +28 -2
- package/dist/verification.mjs +5 -4
- package/docs/ADS.md +4 -1
- package/docs/ARCHITECTURE.md +13 -3
- package/docs/CHANGELOG.md +92 -12
- package/docs/GUIDE.md +208 -14
- package/docs/MCP.md +14 -10
- package/package.json +1 -1
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import postcss from "postcss";
|
|
4
|
+
import { resolveValue } from "./themes.mjs";
|
|
5
|
+
|
|
6
|
+
/** fonts.preload.generated.ts names the font files the first text uses, read from the sheets: the
|
|
7
|
+
* first family in base.css's body font-family and heading font-family that fonts.css declares, at
|
|
8
|
+
* the body and heading font-weight. Preloading more than that delays what matters. It imports each
|
|
9
|
+
* file through the bundler, the way the stylesheet's url() does, so both ask for one URL: a page
|
|
10
|
+
* that preloads another URL downloads the font twice. Without such a font nothing is generated. */
|
|
11
|
+
export const generatedFontsFile = "fonts.preload.generated.ts";
|
|
12
|
+
const unquote = value => value.trim().replace(/^["']|["']$/g, "");
|
|
13
|
+
const formats = { woff2: "font/woff2", woff: "font/woff", ttf: "font/ttf", otf: "font/otf" };
|
|
14
|
+
|
|
15
|
+
function fontFaces(text) {
|
|
16
|
+
const faces = [];
|
|
17
|
+
postcss.parse(text).walkAtRules(/^font-face$/i, rule => {
|
|
18
|
+
const value = name => rule.nodes.find(node => node.type === "decl" && node.prop.toLowerCase() === name)?.value;
|
|
19
|
+
const url = /url\(\s*["']?([^"')]+)["']?\s*\)/i.exec(value("src") ?? "")?.[1];
|
|
20
|
+
if (!url || /^data:/i.test(url)) return;
|
|
21
|
+
const [low, high = low] = (value("font-weight") ?? "400").replace(/\bnormal\b/, "400").replace(/\bbold\b/, "700").trim().split(/\s+/).map(Number);
|
|
22
|
+
faces.push({ family: unquote(value("font-family") ?? ""), url, low, high, slant: (value("font-style") ?? "normal").trim().toLowerCase(), range: value("unicode-range") });
|
|
23
|
+
});
|
|
24
|
+
return faces;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Whether a unicode-range covers Latin capital A, the subset first text needs. */
|
|
28
|
+
const coversLatin = range => !range || range.split(",").some(part => { const [first, last = first] = part.trim().replace(/^U\+/i, "").split("-").map(item => parseInt(item.replaceAll("?", "0"), 16)); return first <= 0x41 && 0x41 <= (part.includes("?") ? first + 0xff : last); });
|
|
29
|
+
|
|
30
|
+
/** The font and weight of the body and of headings, as base.css sets them. */
|
|
31
|
+
function firstTextFonts(text, values) {
|
|
32
|
+
const read = pattern => {
|
|
33
|
+
const found = {};
|
|
34
|
+
postcss.parse(text).walkRules(rule => {
|
|
35
|
+
if (!rule.selector.split(",").some(item => pattern.test(item.trim()))) return;
|
|
36
|
+
for (const node of rule.nodes) if (node.type === "decl" && ["font-family", "font-weight"].includes(node.prop.toLowerCase())) found[node.prop.toLowerCase()] = node.value;
|
|
37
|
+
});
|
|
38
|
+
return found;
|
|
39
|
+
};
|
|
40
|
+
const resolve = value => { const name = /^var\(\s*(--[\w-]+)/.exec(value?.trim() ?? "")?.[1]; return name ? resolveValue(values, name) : value; };
|
|
41
|
+
const body = read(/^(?::where\()?(?:html|body|:root)\)?$/), heading = read(/^(?::where\()?h[1-6]\)?$/);
|
|
42
|
+
const family = resolve(body["font-family"]), weight = Number(resolve(body["font-weight"])) || 400;
|
|
43
|
+
const headingWeight = resolve(heading["font-weight"]);
|
|
44
|
+
return [{ family, weight }, ...(heading["font-family"] || Number(headingWeight) ? [{ family: resolve(heading["font-family"]) ?? family, weight: Number(headingWeight) || weight }] : [])];
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** The generated module for a project's tokens, or null when no first-text font is a project file. */
|
|
48
|
+
export function fontPreloadText({ dsRoot, config }, values) {
|
|
49
|
+
const directory = path.join(dsRoot, config.tokenDir), fontsFile = path.join(directory, "fonts.css"), baseFile = path.join(directory, "base.css");
|
|
50
|
+
if (!existsSync(fontsFile) || !existsSync(baseFile)) return null;
|
|
51
|
+
let faces, uses;
|
|
52
|
+
try { faces = fontFaces(readFileSync(fontsFile, "utf8")); uses = firstTextFonts(readFileSync(baseFile, "utf8"), values); }
|
|
53
|
+
catch { return null; /* The core CSS syntax diagnostic owns malformed sheets. */ }
|
|
54
|
+
const urls = new Set();
|
|
55
|
+
for (const { family, weight } of uses) {
|
|
56
|
+
const name = (family ?? "").split(",").map(unquote).find(item => faces.some(face => face.family === item));
|
|
57
|
+
if (!name) continue;
|
|
58
|
+
const candidates = faces.filter(face => face.family === name && face.slant === "normal" && coversLatin(face.range));
|
|
59
|
+
const face = candidates.find(item => item.low <= weight && weight <= item.high) ?? candidates.sort((a, b) => Math.abs(a.low - weight) - Math.abs(b.low - weight))[0];
|
|
60
|
+
if (face) urls.add(face.url);
|
|
61
|
+
}
|
|
62
|
+
if (!urls.size) return null;
|
|
63
|
+
const list = [...urls], local = url => !/^(?:[a-z]+:)?\/\//i.test(url) && !url.startsWith("/");
|
|
64
|
+
const type = url => formats[/\.(\w+)(?:[?#].*)?$/.exec(url)?.[1]?.toLowerCase()] ?? "font/woff2";
|
|
65
|
+
return [
|
|
66
|
+
"/* Generated by ADS from fonts.css and base.css: the fonts the first text uses. `ads assets` and the",
|
|
67
|
+
" showcase and MCP server rewrite it; do not edit it. Call preloadFonts() in the app entry before",
|
|
68
|
+
" the first render. */",
|
|
69
|
+
...list.flatMap((url, index) => local(url) ? [`import font${index} from ${JSON.stringify(`${url.startsWith(".") ? url : `./${url}`}?url`)};`] : []),
|
|
70
|
+
"",
|
|
71
|
+
"export const fontPreloads: readonly { readonly href: string; readonly type: string }[] = [",
|
|
72
|
+
...list.map((url, index) => ` { href: ${local(url) ? `font${index}` : JSON.stringify(url)}, type: ${JSON.stringify(type(url))} },`),
|
|
73
|
+
"];",
|
|
74
|
+
"",
|
|
75
|
+
"/** Adds one preload link per font. The crossorigin attribute matches how browsers fetch fonts. */",
|
|
76
|
+
"export function preloadFonts(): void {",
|
|
77
|
+
" for (const { href, type } of fontPreloads) {",
|
|
78
|
+
' const link = document.createElement("link");',
|
|
79
|
+
' link.rel = "preload"; link.as = "font"; link.type = type; link.href = href; link.crossOrigin = "anonymous";',
|
|
80
|
+
" document.head.append(link);",
|
|
81
|
+
" }",
|
|
82
|
+
"}",
|
|
83
|
+
"",
|
|
84
|
+
].join("\n");
|
|
85
|
+
}
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import ts from "typescript";
|
|
4
|
+
import postcss from "postcss";
|
|
5
|
+
import { isDevelopmentFile, isInside, isTestFile, sourceFiles } from "./config.mjs";
|
|
6
|
+
import { findingSeverity } from "./finding-rules.mjs";
|
|
7
|
+
|
|
8
|
+
/** A raw <img> in component, pattern and composition source reserves its space and chooses how it
|
|
9
|
+
* loads. It needs width and height, or a size its own style shows (aspect-ratio, or both a width
|
|
10
|
+
* and a height, or out-of-flow positioning, which shifts nothing), and a loading attribute. An
|
|
11
|
+
* attribute with a dynamic value counts as present. What
|
|
12
|
+
* source cannot settle (a spread, a class from elsewhere) is an img-attributes-unresolved info item.
|
|
13
|
+
* A srcset with width descriptors needs sizes, on <img> and on the project's Image. */
|
|
14
|
+
|
|
15
|
+
const guidance = "ads://guides/performance";
|
|
16
|
+
const sized = declarations => /^(?:absolute|fixed)$/.test(declarations.get("position") ?? "") || declarations.has("aspect-ratio") || ["width", "inline-size"].some(name => declarations.get(name) && declarations.get(name) !== "auto") && ["height", "block-size"].some(name => declarations.get(name) && declarations.get(name) !== "auto");
|
|
17
|
+
|
|
18
|
+
/** What this file's css templates set: per variable, per class and on img selectors. */
|
|
19
|
+
function fileStyles(source) {
|
|
20
|
+
const variables = new Map(), classes = new Map();
|
|
21
|
+
let imgRule = false;
|
|
22
|
+
const read = (name, template) => {
|
|
23
|
+
const text = ts.isNoSubstitutionTemplateLiteral(template) ? template.text : `${template.head.text}${template.templateSpans.map(span => `__ads__${span.literal.text}`).join("")}`;
|
|
24
|
+
try {
|
|
25
|
+
const css = postcss.parse(text), own = new Map();
|
|
26
|
+
for (const node of css.nodes) if (node.type === "decl") own.set(node.prop.toLowerCase(), node.value.trim());
|
|
27
|
+
if (name) variables.set(name, own);
|
|
28
|
+
css.walkRules(rule => {
|
|
29
|
+
const declarations = new Map();
|
|
30
|
+
for (const node of rule.nodes) if (node.type === "decl") declarations.set(node.prop.toLowerCase(), node.value.trim());
|
|
31
|
+
if (!sized(declarations)) return;
|
|
32
|
+
if (/(?:^|[\s,>+~(])img\b/.test(rule.selector)) imgRule = true;
|
|
33
|
+
for (const [, name] of rule.selector.matchAll(/\.([\w-]+)/g)) classes.set(name, declarations);
|
|
34
|
+
});
|
|
35
|
+
} catch { /* The core CSS syntax diagnostic owns malformed templates. */ }
|
|
36
|
+
};
|
|
37
|
+
const visit = node => {
|
|
38
|
+
if (ts.isTaggedTemplateExpression(node) && /(?:^|\.)css$|^styled/.test(node.tag.getText(source))) read(ts.isVariableDeclaration(node.parent) ? node.parent.name.getText(source) : undefined, node.template);
|
|
39
|
+
ts.forEachChild(node, visit);
|
|
40
|
+
};
|
|
41
|
+
visit(source);
|
|
42
|
+
return { variables, classes, imgRule };
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Whether a className expression sizes the image: true, false, or null when it cannot tell. */
|
|
46
|
+
function classSize(expression, { variables, classes }) {
|
|
47
|
+
let found = false, unknown = false;
|
|
48
|
+
const words = text => { for (const name of text.split(/\s+/)) if (classes.has(name)) found = true; };
|
|
49
|
+
const visit = node => {
|
|
50
|
+
if (ts.isStringLiteralLike(node)) words(node.text);
|
|
51
|
+
else if (ts.isIdentifier(node)) { if (!variables.has(node.text)) unknown = true; else if (sized(variables.get(node.text))) found = true; }
|
|
52
|
+
else if (ts.isCallExpression(node) && ts.isIdentifier(node.expression) && node.expression.text === "cx") node.arguments.forEach(visit);
|
|
53
|
+
else if (ts.isConditionalExpression(node)) { visit(node.whenTrue); visit(node.whenFalse); }
|
|
54
|
+
else if (ts.isBinaryExpression(node)) { if (node.operatorToken.kind === ts.SyntaxKind.AmpersandAmpersandToken) visit(node.right); else { visit(node.left); visit(node.right); } }
|
|
55
|
+
else if (ts.isParenthesizedExpression(node) || ts.isJsxExpression(node)) { if (node.expression) visit(node.expression); }
|
|
56
|
+
else unknown = true;
|
|
57
|
+
};
|
|
58
|
+
visit(expression);
|
|
59
|
+
return found ? true : unknown ? null : false;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export function imageAttributeFindings({ root, dsRoot }) {
|
|
63
|
+
const options = { root, dsRoot }, findings = [];
|
|
64
|
+
const inScope = file => isInside(path.join(dsRoot, "composition"), file) && !isTestFile(file) || ["components", "patterns"].some(layer => isInside(path.join(dsRoot, layer), file)) && !isDevelopmentFile(file, options);
|
|
65
|
+
for (const file of sourceFiles(dsRoot).filter(file => /\.[jt]sx$/.test(file) && inScope(file))) {
|
|
66
|
+
const text = readFileSync(file, "utf8");
|
|
67
|
+
if (!/<(?:img|Image)\b/.test(text)) continue;
|
|
68
|
+
const source = ts.createSourceFile(file, text, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX), relative = path.relative(root, file).replaceAll("\\", "/");
|
|
69
|
+
const styles = fileStyles(source);
|
|
70
|
+
const visit = node => {
|
|
71
|
+
if (ts.isJsxSelfClosingElement(node) || ts.isJsxOpeningElement(node)) {
|
|
72
|
+
const tag = node.tagName.getText(source);
|
|
73
|
+
if (tag === "img" || tag === "Image") inspectCandidates(node, tag);
|
|
74
|
+
if (tag === "img") inspect(node);
|
|
75
|
+
}
|
|
76
|
+
ts.forEachChild(node, visit);
|
|
77
|
+
};
|
|
78
|
+
/** Width descriptors say nothing about display size, so sizes must. */
|
|
79
|
+
const inspectCandidates = (node, tag) => {
|
|
80
|
+
const attributes = node.attributes.properties;
|
|
81
|
+
const attribute = name => attributes.find(item => ts.isJsxAttribute(item) && item.name.getText(source) === name);
|
|
82
|
+
const candidates = attribute("srcset") ?? attribute("srcSet");
|
|
83
|
+
if (!candidates || attribute("sizes")) return;
|
|
84
|
+
const { line, character } = source.getLineAndCharacterOfPosition(node.getStart(source));
|
|
85
|
+
const add = (rule, message) => findings.push({ rule, severity: findingSeverity(rule), file: relative, line: line + 1, column: character + 1, guidanceUri: guidance, message: `${relative}:${line + 1} ${message}` });
|
|
86
|
+
let value = candidates.initializer;
|
|
87
|
+
if (value && ts.isJsxExpression(value)) value = value.expression;
|
|
88
|
+
const literal = value && ts.isStringLiteralLike(value) ? value.text : null;
|
|
89
|
+
if (attributes.some(ts.isJsxSpreadAttribute) || literal === null) add("img-attributes-unresolved", `<${tag}> has a srcset ADS cannot read or spread props that may hold sizes. With width descriptors it needs sizes, the width it displays at.`);
|
|
90
|
+
else if (/\d\s*w\s*(?:,|$)/.test(literal.trim())) add("img-attributes", `<${tag}> has a srcset with width descriptors and no sizes, so the browser assumes the full viewport width and can pick a larger file than it shows. Add sizes, such as "(min-width: 1024px) 50vw, 100vw".`);
|
|
91
|
+
};
|
|
92
|
+
const inspect = node => {
|
|
93
|
+
const { line, character } = source.getLineAndCharacterOfPosition(node.getStart(source));
|
|
94
|
+
const add = (rule, message) => findings.push({ rule, severity: findingSeverity(rule), file: relative, line: line + 1, column: character + 1, guidanceUri: guidance, message: `${relative}:${line + 1} ${message}` });
|
|
95
|
+
const attributes = node.attributes.properties, spread = attributes.some(ts.isJsxSpreadAttribute);
|
|
96
|
+
const attribute = name => attributes.find(item => ts.isJsxAttribute(item) && item.name.getText(source) === name);
|
|
97
|
+
const styleText = attribute("style")?.initializer?.getText(source) ?? "";
|
|
98
|
+
const className = attribute("className") ?? attribute("class");
|
|
99
|
+
let size = !!(attribute("width") && attribute("height")) || /\baspectRatio\b|aspect-ratio/.test(styleText) || styles.imgRule;
|
|
100
|
+
if (!size && className?.initializer) size = classSize(className.initializer, styles);
|
|
101
|
+
const loading = !!attribute("loading");
|
|
102
|
+
if (spread && (size !== true || !loading)) { add("img-attributes-unresolved", `spreads props onto <img>, so ADS cannot see its dimensions or loading. Pass width, height and loading explicitly so the page reserves the space and the load order is a choice.`); return; }
|
|
103
|
+
if (size === null) add("img-attributes-unresolved", `styles <img> with a class ADS cannot read here, so its size is not checked. Set width and height so the page reserves the space.`);
|
|
104
|
+
if (size === false) add("img-attributes", `<img> has no width and height or a visible aspect-ratio, so the page shifts when it loads. Set the file's width and height, or a sized aspect-ratio in its style.`);
|
|
105
|
+
if (!loading) add("img-attributes", `<img> has no loading attribute. Use loading="lazy" below the fold; the page's main visible image uses loading="eager" with fetchpriority="high", or the project's image component with priority.`);
|
|
106
|
+
};
|
|
107
|
+
visit(source);
|
|
108
|
+
}
|
|
109
|
+
return findings;
|
|
110
|
+
}
|
package/dist/init.mjs
CHANGED
|
@@ -145,6 +145,8 @@ export function initProject(directory = process.cwd(), { toolPackage, packageMan
|
|
|
145
145
|
}
|
|
146
146
|
pkg.scripts = scripts;
|
|
147
147
|
pkg.devDependencies = { ...pkg.devDependencies, [tool.name]: spec };
|
|
148
|
+
// The validation and acceptance policies run the browser audit, which needs project Playwright.
|
|
149
|
+
if (!["@playwright/test", "playwright"].some(name => pkg.devDependencies[name] ?? pkg.dependencies?.[name])) pkg.devDependencies["@playwright/test"] = tool.devDependencies["@playwright/test"];
|
|
148
150
|
if (pkg.dependencies?.[tool.name]) delete pkg.dependencies[tool.name];
|
|
149
151
|
|
|
150
152
|
const updates = new Map();
|
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
import valueParser from "postcss-value-parser";
|
|
2
|
+
import { contextValues } from "./themes.mjs";
|
|
3
|
+
import { findingSeverity } from "./finding-rules.mjs";
|
|
4
|
+
|
|
5
|
+
/** Widths are fluid on the grid. In component, pattern and composition styles, a width (width,
|
|
6
|
+
* min-/max-width, the logical inline sizes, flex-basis or the flex shorthand's basis, and
|
|
7
|
+
* grid-template-columns tracks) is a layout-fixed-width error when it resolves to a fixed length
|
|
8
|
+
* above 48 px: raw, through tokens, or by arithmetic on spacing tokens. 48 px is the top of the
|
|
9
|
+
* control-height and icon range, so anything wider is a layout width rather than a part's size.
|
|
10
|
+
* A flex item that both grows and shrinks is fluid whatever its basis.
|
|
11
|
+
* Fluid values pass: %, fr, font-relative measures (ch, em, ex, lh), viewport and container
|
|
12
|
+
* units, sizing keywords, and min()/max()/clamp()/calc() with a fluid part. Tokens named by
|
|
13
|
+
* layout.widthTokens pass; each must be defined fluidly, except a fixed --container-* or
|
|
14
|
+
* --content-max token, a cap, which passes as max-width or max-inline-size only. The size families of
|
|
15
|
+
* fixed-size parts pass (sizeFamilies). Owners matched by layout.fixedWidthUnits, which is where
|
|
16
|
+
* overlays such as dialogs, menus, popovers and tooltips are declared, are not checked: ADS
|
|
17
|
+
* knows a unit's layer, not whether it floats. */
|
|
18
|
+
|
|
19
|
+
export const fixedWidthLimitPx = 48;
|
|
20
|
+
const widthProperties = new Set(["width", "max-width", "min-width", "inline-size", "max-inline-size", "min-inline-size", "flex-basis", "flex", "grid-template-columns"]);
|
|
21
|
+
const capProperties = new Set(["max-width", "max-inline-size"]);
|
|
22
|
+
const capToken = /^--container-|^--content-max$/;
|
|
23
|
+
/** Token families that size a part, not a layout: exempt wherever they are used. */
|
|
24
|
+
export const sizeFamilies = /^--(?:icon|control|avatar|border|focus|ring|radius|side-pane|toast)-|^--(?:navigation-rail-width|app-header-height|row-height-compact|compact-column-min)$/;
|
|
25
|
+
const fluidUnits = /^(?:%|fr|ch|em|ex|cap|ic|lh|rlh|[sld]?v(?:w|h|i|b|min|max)|cq(?:w|h|i|b|min|max))$/i;
|
|
26
|
+
const absoluteUnits = { px: 1, rem: 16, pt: 4 / 3, pc: 16, in: 96, cm: 96 / 2.54, mm: 96 / 25.4, q: 96 / 101.6 };
|
|
27
|
+
const keywords = /^(?:auto|none|min-content|max-content|fit-content|stretch|inherit|initial|unset|revert|revert-layer|content|subgrid)$/i;
|
|
28
|
+
const fluid = { fluid: true }, neutral = { neutral: true }, unknown = { unknown: true };
|
|
29
|
+
|
|
30
|
+
/** A regular expression for a token or path glob: * within a path segment, ** across them. */
|
|
31
|
+
export function globPattern(glob) {
|
|
32
|
+
const literal = text => text.replace(/[.+?^${}()|[\]\\]/g, "\\$&");
|
|
33
|
+
return new RegExp(`^${glob.split("**").map(part => part.split("*").map(literal).join("[^/]*")).join(".*")}$`);
|
|
34
|
+
}
|
|
35
|
+
export const globMatcher = globs => { const patterns = globs.map(globPattern); return name => patterns.some(pattern => pattern.test(name)); };
|
|
36
|
+
|
|
37
|
+
const meaningful = nodes => nodes.filter(node => !["space", "comment"].includes(node.type));
|
|
38
|
+
function splitArguments(nodes) {
|
|
39
|
+
const parts = [[]];
|
|
40
|
+
for (const node of nodes) { if (node.type === "div" && node.value === ",") parts.push([]); else parts.at(-1).push(node); }
|
|
41
|
+
return parts;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function createLayoutWidths(tokens, { themes, layout }) {
|
|
45
|
+
const values = contextValues(tokens, { theme: themes[0].name, themes });
|
|
46
|
+
const widthToken = globMatcher(layout.widthTokens);
|
|
47
|
+
const isFluid = (name, value) => sequence(valueParser(value).nodes, { seen: new Set([name]), locals: new Map() }).fluid === true;
|
|
48
|
+
/** A named width token is allowed; only a fixed --container-* cap is limited to max sizes. */
|
|
49
|
+
const cap = name => capToken.test(name) && values.has(name) && !isFluid(name, values.get(name).value);
|
|
50
|
+
|
|
51
|
+
function variable(node, scope) {
|
|
52
|
+
const [name, fallback = []] = splitArguments(node.nodes).map(meaningful);
|
|
53
|
+
const token = name?.find(child => child.type === "word")?.value;
|
|
54
|
+
if (!token?.startsWith("--")) return unknown;
|
|
55
|
+
if (widthToken(token)) return cap(token) ? { cap: token } : neutral;
|
|
56
|
+
if (sizeFamilies.test(token)) return neutral;
|
|
57
|
+
if (scope.seen.has(token)) return unknown;
|
|
58
|
+
const seen = new Set([...scope.seen, token]);
|
|
59
|
+
// Component variables declared in the same template are read through, so a width cannot hide in one.
|
|
60
|
+
const local = scope.locals.get(token);
|
|
61
|
+
if (local) return local.map(value => sequence(valueParser(value).nodes, { ...scope, seen })).find(result => result.px !== undefined) ?? unknown;
|
|
62
|
+
const value = values.get(token)?.value;
|
|
63
|
+
if (value === undefined) return fallback.length ? sequence(fallback, { ...scope, seen }) : unknown;
|
|
64
|
+
const result = sequence(valueParser(value).nodes, { ...scope, seen });
|
|
65
|
+
return token.startsWith("--space-") && result.px !== undefined ? { ...result, space: true } : result;
|
|
66
|
+
}
|
|
67
|
+
/** One value part: { fluid } | { neutral } | { unknown } | { cap } | { number } | { px, space?, math? }. */
|
|
68
|
+
function measure(node, scope) {
|
|
69
|
+
if (node.type === "word") {
|
|
70
|
+
const parsed = valueParser.unit(node.value);
|
|
71
|
+
if (!parsed) return keywords.test(node.value) ? neutral : unknown;
|
|
72
|
+
const number = Number(parsed.number), unit = parsed.unit.toLowerCase();
|
|
73
|
+
if (!unit) return { number };
|
|
74
|
+
if (number === 0 || fluidUnits.test(unit)) return number === 0 ? neutral : fluid;
|
|
75
|
+
return absoluteUnits[unit] ? { px: number * absoluteUnits[unit] } : unknown;
|
|
76
|
+
}
|
|
77
|
+
if (node.type !== "function") return unknown;
|
|
78
|
+
const name = node.value.toLowerCase();
|
|
79
|
+
if (name === "var") return variable(node, scope);
|
|
80
|
+
if (name === "calc" || name === "") return calculation(node.nodes, scope);
|
|
81
|
+
if (name === "fit-content") return neutral;
|
|
82
|
+
if (!["min", "max", "clamp"].includes(name)) return unknown;
|
|
83
|
+
const parts = splitArguments(node.nodes).map(part => sequence(part, scope));
|
|
84
|
+
if (parts.some(part => part.fluid)) return fluid;
|
|
85
|
+
if (parts.some(part => part.px === undefined)) return unknown;
|
|
86
|
+
const lengths = parts.map(part => part.px);
|
|
87
|
+
const px = name === "min" ? Math.min(...lengths) : name === "max" ? Math.max(...lengths) : Math.max(lengths[0], Math.min(lengths[1], lengths[2] ?? Infinity));
|
|
88
|
+
return { px, space: parts.some(part => part.space), math: parts.some(part => part.math) };
|
|
89
|
+
}
|
|
90
|
+
function sequence(nodes, scope) {
|
|
91
|
+
const items = meaningful(nodes);
|
|
92
|
+
return items.length === 1 ? measure(items[0], scope) : unknown;
|
|
93
|
+
}
|
|
94
|
+
/** calc(): fluid when any term is; otherwise its fixed result, marked as arithmetic. */
|
|
95
|
+
function calculation(nodes, scope) {
|
|
96
|
+
const operands = [], operators = [];
|
|
97
|
+
for (const item of meaningful(nodes)) {
|
|
98
|
+
if (item.type === "div" && item.value === "/") { operators.push("/"); continue; }
|
|
99
|
+
if (item.type !== "word") { operands.push(measure(item, scope)); continue; }
|
|
100
|
+
if (["+", "-"].includes(item.value)) { operators.push(item.value); continue; }
|
|
101
|
+
// valueParser keeps * and calc()'s / in a word, spaced or not.
|
|
102
|
+
for (const part of item.value.split(/([*/])/).filter(Boolean)) { if (part === "*" || part === "/") operators.push(part); else operands.push(measure({ type: "word", value: part }, scope)); }
|
|
103
|
+
}
|
|
104
|
+
if (operands.some(operand => operand.fluid)) return fluid;
|
|
105
|
+
if (operands.length !== operators.length + 1 || operands.some(operand => operand.px === undefined && operand.number === undefined)) return unknown;
|
|
106
|
+
// Multiplication and division bind first.
|
|
107
|
+
const terms = [operands[0]], signs = [];
|
|
108
|
+
operators.forEach((operator, index) => {
|
|
109
|
+
const next = operands[index + 1];
|
|
110
|
+
if (operator !== "*" && operator !== "/") { terms.push(next); signs.push(operator); return; }
|
|
111
|
+
const last = terms.pop(), length = last.px ?? next.px, factor = last.px === undefined ? last.number : next.number;
|
|
112
|
+
if (length === undefined) terms.push({ number: operator === "*" ? last.number * next.number : last.number / next.number });
|
|
113
|
+
else terms.push({ px: operator === "*" ? length * factor : length / factor });
|
|
114
|
+
});
|
|
115
|
+
if (terms.some(term => term.px === undefined)) return unknown;
|
|
116
|
+
const px = terms.slice(1).reduce((sum, term, index) => signs[index] === "+" ? sum + term.px : sum - term.px, terms[0].px);
|
|
117
|
+
return { px, space: operands.some(operand => operand.space), math: operators.length > 0 };
|
|
118
|
+
}
|
|
119
|
+
/** The sizes of a grid-template-columns value, through repeat() and minmax()'s maximum. */
|
|
120
|
+
function tracks(nodes, scope) {
|
|
121
|
+
const sizes = [];
|
|
122
|
+
for (const node of meaningful(nodes)) {
|
|
123
|
+
const name = node.type === "function" ? node.value.toLowerCase() : "";
|
|
124
|
+
if (node.type === "word" && node.value.startsWith("[")) continue;
|
|
125
|
+
if (name === "repeat") sizes.push(...tracks(splitArguments(node.nodes).slice(1).flat(), scope));
|
|
126
|
+
else if (name === "minmax") sizes.push(sequence(splitArguments(node.nodes)[1] ?? [], scope));
|
|
127
|
+
else sizes.push(measure(node, scope));
|
|
128
|
+
}
|
|
129
|
+
return sizes;
|
|
130
|
+
}
|
|
131
|
+
/** Why a width declaration is fixed, or null when it is fluid or allowed. */
|
|
132
|
+
function fixed(property, value, scope) {
|
|
133
|
+
const verdict = result => {
|
|
134
|
+
if (result.cap) return capProperties.has(property) ? null : `${result.cap} is a fixed container cap, valid only as max-width or max-inline-size`;
|
|
135
|
+
if (result.px === undefined) return null;
|
|
136
|
+
if (result.px <= fixedWidthLimitPx) return null;
|
|
137
|
+
return result.space && result.math ? `${Math.round(result.px)}px of arithmetic on spacing tokens` : `a fixed ${Math.round(result.px)}px, above the ${fixedWidthLimitPx}px control and icon range`;
|
|
138
|
+
};
|
|
139
|
+
const nodes = valueParser(value).nodes;
|
|
140
|
+
if (property === "grid-template-columns") {
|
|
141
|
+
for (const track of tracks(nodes, scope)) { const reason = verdict(track); if (reason) return `a fixed track, ${reason}`; }
|
|
142
|
+
return null;
|
|
143
|
+
}
|
|
144
|
+
if (property === "flex") {
|
|
145
|
+
const parts = meaningful(nodes);
|
|
146
|
+
if (parts.length < 2) return null;
|
|
147
|
+
const basis = parts.at(-1), shrink = parts.length === 3 ? Number(parts[1].value) : 1;
|
|
148
|
+
return Number(parts[0].value) > 0 && shrink > 0 ? null : verdict(measure(basis, scope));
|
|
149
|
+
}
|
|
150
|
+
return verdict(sequence(nodes, scope));
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
return {
|
|
154
|
+
/** layout-fixed-width findings for one parsed style sheet or Linaria template. */
|
|
155
|
+
inspect(css, file, offset = { line: 1, column: 1 }) {
|
|
156
|
+
const findings = [], locals = new Map();
|
|
157
|
+
css.walkDecls(/^--/, decl => { locals.set(decl.prop, [...(locals.get(decl.prop) ?? []), decl.value]); });
|
|
158
|
+
css.walkDecls(decl => {
|
|
159
|
+
const property = decl.prop.toLowerCase();
|
|
160
|
+
if (!widthProperties.has(property) || decl.value.includes("__ds_expression__")) return;
|
|
161
|
+
const reason = fixed(property, decl.value, { seen: new Set(), locals });
|
|
162
|
+
if (!reason) return;
|
|
163
|
+
const line = offset.line + decl.source.start.line - 1;
|
|
164
|
+
findings.push({ rule: "layout-fixed-width", severity: findingSeverity("layout-fixed-width"), file, line, column: decl.source.start.column + (decl.source.start.line === 1 ? offset.column - 1 : 0), guidanceUri: "ads://guides/tokens",
|
|
165
|
+
message: `${file}:${line} sets ${property}: ${decl.value}, ${reason}. Widths are fluid on the grid: span columns with a --grid-span-N token in a container query, use % or fr, or cap text with a ch measure (max-inline-size: 65ch).` });
|
|
166
|
+
});
|
|
167
|
+
return findings;
|
|
168
|
+
},
|
|
169
|
+
/** Every layout.widthTokens token is defined fluidly, or is a --container-* cap. */
|
|
170
|
+
tokenFindings() {
|
|
171
|
+
const findings = [];
|
|
172
|
+
for (const token of tokens) {
|
|
173
|
+
if (!widthToken(token.name) || capToken.test(token.name)) continue;
|
|
174
|
+
for (const definition of token.definitions) {
|
|
175
|
+
const value = definition.authored ?? definition.value;
|
|
176
|
+
if (isFluid(token.name, value)) continue;
|
|
177
|
+
findings.push({ rule: "layout-fixed-width", severity: findingSeverity("layout-fixed-width"), file: definition.file, line: definition.line, column: definition.column, tokens: [token.name], guidanceUri: "ads://guides/tokens",
|
|
178
|
+
message: `${token.name} is named by layout.widthTokens but is ${value}, not a fluid width. Define it with % or container units, such as calc((100% + var(--grid-gutter)) * 3 / 16 - var(--grid-gutter)); only a --container-* or --content-max token may be a fixed cap.` });
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
return findings;
|
|
182
|
+
},
|
|
183
|
+
};
|
|
184
|
+
}
|
package/dist/mcp/context.mjs
CHANGED
|
@@ -6,7 +6,7 @@ import { developmentRuntime, packageScriptCommand } from "../development-runtime
|
|
|
6
6
|
|
|
7
7
|
export const GUIDE_URI = "ads://project/guide";
|
|
8
8
|
// Put the task triggers and entry path first: some hosts shorten server guidance.
|
|
9
|
-
export const serverInstructions = "Use ADS for UI work: components, patterns, controllers, hooks, tokens, themes, branding, layout, interaction, accessibility, motion and showcase review. Start with ads_status; if tools are not exposed, read ads://project/guide then ads://project/status. Use the returned projectRoot and commands. Choose direct source editing or MCP-only editing using ads://guides/workflows, based on actual editor access and user preference, not mutations.enabled. With direct code access, edit owned files normally and use MCP for preview/checks; ordinary direct edits do not require drafts or ads_accept. MCP-only iterative design uses enabled draft tools, rendered review and exact-revision ads_accept; read ads://guides/drafts. Complete tracked proposals by accepting required drafts; accept dependencies first and review dependents again. Without a source editor or enabled mutation tools, inspection is available but editing is not. Low-level MCP repairs can use ads_units and guarded ads_apply_patch for one owner or ads_apply_transaction for coupled owners. Find existing public UI with ads_catalog; discover its previews with ads_scenarios and open ads_show_scenario. Starting ADS also serves its built-in showcase: use ads_status.showcaseUrl for browser review instead of starting another runtime/compiler or project browser app. Read one relevant ADS skill before editing. Inspect the real preview, edit its owned source, check the build and review again. Scope source/guides to the project, its instruction ancestry and user-selected import/reference sources; broad searches of /mnt or home are not ADS discovery. Domain-model/requirements work is a separate project workflow. For requested visual evidence, use ads_capture or screenshot-enabled patch dry runs; read ads://guides/captures for named targets, image resources and the current/candidate lifecycle. For behavior work, read ads://guides/behaviors and use ads_behaviors/ads_verify: scenario exercises are demonstrations, and registered guarantees need current passing execution evidence. For direct edits, use ads_validate with policy acceptance to enforce the project acceptance policy without applying source. Draft acceptance and guarded patches use the same configured policy on their candidate, including the axe-core audit of affected UI scenarios
|
|
9
|
+
export const serverInstructions = "Use ADS for UI work: components, patterns, controllers, hooks, tokens, themes, branding, layout, interaction, accessibility, motion and showcase review. Start with ads_status; if tools are not exposed, read ads://project/guide then ads://project/status. Use the returned projectRoot and commands. Choose direct source editing or MCP-only editing using ads://guides/workflows, based on actual editor access and user preference, not mutations.enabled. With direct code access, edit owned files normally and use MCP for preview/checks; ordinary direct edits do not require drafts or ads_accept. MCP-only iterative design uses enabled draft tools, rendered review and exact-revision ads_accept; read ads://guides/drafts. Complete tracked proposals by accepting required drafts; accept dependencies first and review dependents again. Without a source editor or enabled mutation tools, inspection is available but editing is not. Low-level MCP repairs can use ads_units and guarded ads_apply_patch for one owner or ads_apply_transaction for coupled owners. Find existing public UI with ads_catalog; discover its previews with ads_scenarios and open ads_show_scenario. Starting ADS also serves its built-in showcase: use ads_status.showcaseUrl for browser review instead of starting another runtime/compiler or project browser app. Read one relevant ADS skill before editing. Inspect the real preview, edit its owned source, check the build and review again. Scope source/guides to the project, its instruction ancestry and user-selected import/reference sources; broad searches of /mnt or home are not ADS discovery. Domain-model/requirements work is a separate project workflow. For requested visual evidence, use ads_capture or screenshot-enabled patch dry runs; read ads://guides/captures for named targets, image resources and the current/candidate lifecycle. For behavior work, read ads://guides/behaviors and use ads_behaviors/ads_verify: scenario exercises are demonstrations, and registered guarantees need current passing execution evidence. For direct edits, use ads_validate with policy acceptance to enforce the project acceptance policy without applying source. Draft acceptance and guarded patches use the same configured policy on their candidate, including the axe-core audit of affected UI scenarios unless acceptance.browserAudit is false; draft edit/show runs neither policy. Test registration alone does not gate acceptance. Use ads_validate with scope changed during editing, and the default full validation policy/scope after test/ownership/config migrations, before releases, or for explicit complete audits. Read ads://guides/validation; report actual scope/revision and inspect failures through ads_results. Execution replies are bounded summaries. Read only needed sections with ads_results(resultId, section, status, cursor); follow nextCursor without rerunning. For a failure, inspect its boundary and acceptance, then ads_investigate with the outcome's exact unit/check/runId; detail sections and artifacts load separately (ads://guides/evidence). Preserve valid APIs when source tracing is inconclusive. After targeted investigation, record suspected ADS defects with ads_report_bug or missing capabilities with ads_request_feature; read ads://guides/reporting. These are local untriaged reports, not established causes or upstream issues. Use the configured project framework and declared dependencies; MCP hosts supply no ad hoc APIs. MCP source checks do not replace browser tests; direct edits still need project checks. Reading HTML is not rendering, and reading a skill is not native activation. A running watcher is not proof of current source: inspect ads_status.build or ads://project/build after edits. Notifications may not reach the agent. Only explicitly enabled mutation tools edit project-owned ADS units after validation. Checks and compiler commands come from validated project configuration, never an ad hoc command argument.";
|
|
10
10
|
|
|
11
11
|
function manager(root, pkg) {
|
|
12
12
|
if (typeof pkg.packageManager === "string") return pkg.packageManager.split("@")[0];
|
package/dist/mcp/mutations.mjs
CHANGED
|
@@ -2,6 +2,7 @@ import { trackExecutionWorkspace } from "./execution-context.mjs";
|
|
|
2
2
|
import { createHash, randomUUID } from "node:crypto";
|
|
3
3
|
import { cpSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
|
|
4
4
|
import path from "node:path";
|
|
5
|
+
import { hasProjectConfig } from "../project-boundary.mjs";
|
|
5
6
|
import ts from "typescript";
|
|
6
7
|
import { isInside, loadConfig } from "../config.mjs";
|
|
7
8
|
import { affectedBehaviorUnits, createVerificationController } from "../verification.mjs";
|
|
@@ -13,7 +14,7 @@ import { inspectScenarios } from "../scenarios.mjs";
|
|
|
13
14
|
import { checkUnitCandidate, checkUnitFiles, inspectUnits, validateUnitId } from "../units.mjs";
|
|
14
15
|
import { acceptance, failure as evidenceFailure } from "../evidence.mjs";
|
|
15
16
|
import { checkCandidate, checkCommand, projectChecks as checks } from "../validation-checks.mjs";
|
|
16
|
-
import { preparePreviewCache } from "../scenarios-compiler.mjs";
|
|
17
|
+
import { holdLivePreview, preparePreviewCache } from "../scenarios-compiler.mjs";
|
|
17
18
|
import { validationInputFiles } from "../validation-inputs.mjs";
|
|
18
19
|
import { mutationLimits } from "./mutation-limits.mjs";
|
|
19
20
|
import { writeThemesCss } from "../themes-generated.mjs";
|
|
@@ -116,7 +117,7 @@ function snapshot(options) {
|
|
|
116
117
|
const relative = path.relative(options.root, file);
|
|
117
118
|
if (generated.some(base => isInside(base, file))) continue;
|
|
118
119
|
if (entry.isSymbolicLink()) continue;
|
|
119
|
-
if (entry.isDirectory()) walk(file);
|
|
120
|
+
if (entry.isDirectory()) { if (!hasProjectConfig(file)) walk(file); }
|
|
120
121
|
else if (entry.isFile()) {
|
|
121
122
|
if (bytes + lstatSync(file).size > mutationLimits.snapshotBytes || entries.length >= mutationLimits.snapshotFiles) throw fail("mutation-snapshot", "Project source exceeds the bounded validation snapshot limit.");
|
|
122
123
|
const content = readFileSync(file);
|
|
@@ -175,7 +176,7 @@ export function createMutationController(directory, { captures = createCaptureCo
|
|
|
175
176
|
busy = true;
|
|
176
177
|
active = new AbortController();
|
|
177
178
|
signal = signal ? AbortSignal.any([signal, active.signal]) : active.signal;
|
|
178
|
-
let temporary, candidateRevision, releasePreview, previewHost;
|
|
179
|
+
let temporary, candidateRevision, releasePreview, releasePublication, previewHost;
|
|
179
180
|
let boundary=evidenceFailure("runner","mutation-execution","ADS_MUTATION_EXCEPTION",{certainty:"unclassified"});
|
|
180
181
|
const verified = [];
|
|
181
182
|
try {
|
|
@@ -309,7 +310,7 @@ export function createMutationController(directory, { captures = createCaptureCo
|
|
|
309
310
|
verified.push(await checkCommand(check.command, check.args, candidate, signal, undefined, {category:"build",phase:`project-check:${check.args.at(-1)}`}, candidateOptions.config.mcp.mutationCheckTimeoutMs));
|
|
310
311
|
}
|
|
311
312
|
const behaviorUnits = candidateOptions.config.acceptance.behaviorChecks ? affectedBehaviorUnits(candidateOptions, changes.map(change => change.path)) : [];
|
|
312
|
-
// acceptance.browserAudit: axe-core audits the candidate's affected UI scenarios before any source is written.
|
|
313
|
+
// acceptance.browserAudit (on unless false): axe-core audits the candidate's affected UI scenarios before any source is written.
|
|
313
314
|
// It reuses the candidate preview host built for behavior checks/captures; on its own it starts a
|
|
314
315
|
// candidate host that compiles only the selected scenarios.
|
|
315
316
|
const audit = candidateOptions.config.acceptance.browserAudit ? await import("../browser-audit.mjs") : null;
|
|
@@ -374,6 +375,7 @@ export function createMutationController(directory, { captures = createCaptureCo
|
|
|
374
375
|
}
|
|
375
376
|
if (!dryRun) {
|
|
376
377
|
beforeApply?.();
|
|
378
|
+
if (preparedPreview) releasePublication = holdLivePreview(root);
|
|
377
379
|
const written = [];
|
|
378
380
|
const directories = [];
|
|
379
381
|
function mkdir(directory) { if (!existsSync(directory)) { mkdir(path.dirname(directory)); mkdirSync(directory); directories.push(directory); } }
|
|
@@ -407,7 +409,7 @@ export function createMutationController(directory, { captures = createCaptureCo
|
|
|
407
409
|
preview: "Source validation passed. Inspect the managed preview build and rendered scenario after applying; validation is not visual verification." },candidateRevision);
|
|
408
410
|
} catch (error) {
|
|
409
411
|
return lastResult = mutationEvidence({ ok: false, applied: false, diagnostics: [error.diagnostic ?? { rule: "mutation-error", message: error.message,failure:error.failure??boundary }], checks: verified },candidateRevision);
|
|
410
|
-
} finally { try { await previewHost?.close(); } finally { try { if (temporary) rmSync(temporary, { recursive: true, force: true }); } finally { releasePreview?.(); busy = false; active = undefined; progress = undefined; } } }
|
|
412
|
+
} finally { releasePublication?.(); try { await previewHost?.close(); } finally { try { if (temporary) rmSync(temporary, { recursive: true, force: true }); } finally { releasePreview?.(); busy = false; active = undefined; progress = undefined; } } }
|
|
411
413
|
},
|
|
412
414
|
};
|
|
413
415
|
}
|
|
@@ -8,6 +8,7 @@ import { buildFailure, inspectBuildStatus } from "./build-status.mjs";
|
|
|
8
8
|
import { previewSessionDirectories, withPreviewSession } from "../preview-scope.mjs";
|
|
9
9
|
import { developmentExecutable } from "../development-runtime.mjs";
|
|
10
10
|
import { readPreviewManifest } from "../preview-resources.mjs";
|
|
11
|
+
import { activeNow } from "../active-clock.mjs";
|
|
11
12
|
|
|
12
13
|
function stamp(file) {
|
|
13
14
|
try { const stat = statSync(file); return `${stat.mtimeMs}:${stat.ctimeMs}:${stat.size}`; }
|
|
@@ -173,13 +174,13 @@ export function createPreviewWatch(root, config, { log = process.stderr, buildTi
|
|
|
173
174
|
if (signal?.aborted) throw new Error("Preview request cancelled.");
|
|
174
175
|
const app = config.apps.find((entry) => path.resolve(root, entry.file) === file);
|
|
175
176
|
let baseline = baselines.get(file) ?? null;
|
|
176
|
-
let deadline =
|
|
177
|
+
let deadline = activeNow() + buildTimeout;
|
|
177
178
|
let restarted = false;
|
|
178
|
-
while (
|
|
179
|
+
while (activeNow() < deadline) {
|
|
179
180
|
if (signal?.aborted) throw new Error("Preview request cancelled.");
|
|
180
181
|
if (suspended) {
|
|
181
|
-
const pausedAt =
|
|
182
|
-
await waitForResume(signal); deadline +=
|
|
182
|
+
const pausedAt = activeNow();
|
|
183
|
+
await waitForResume(signal); deadline += activeNow() - pausedAt;
|
|
183
184
|
if (disposed) throw new Error("Preview watcher is stopped.");
|
|
184
185
|
start(); request(file, true); baseline = baselines.get(file) ?? null;
|
|
185
186
|
}
|
|
@@ -255,8 +256,8 @@ export function createPreviewWatch(root, config, { log = process.stderr, buildTi
|
|
|
255
256
|
if (!command || disposed) throw new Error("A full managed preview build requires mcp.previewWatch.");
|
|
256
257
|
if (state === "failed" || restarting || stalled) await restart();
|
|
257
258
|
start(); full = randomUUID(); request(active, true);
|
|
258
|
-
const token = full, deadline =
|
|
259
|
-
while (
|
|
259
|
+
const token = full, deadline = activeNow() + timeoutMs;
|
|
260
|
+
while (activeNow() < deadline) {
|
|
260
261
|
if (signal?.aborted) throw new Error("Preview build cancelled.");
|
|
261
262
|
if (state !== "running") throw new Error(error ?? "Preview compiler stopped during full build.");
|
|
262
263
|
let result;
|
|
@@ -279,8 +280,8 @@ export function createPreviewWatch(root, config, { log = process.stderr, buildTi
|
|
|
279
280
|
if (disposed) return;
|
|
280
281
|
if (state === "failed" || restarting || stalled) await restart();
|
|
281
282
|
start();
|
|
282
|
-
const deadline =
|
|
283
|
-
while (!disposed && state === "running" &&
|
|
283
|
+
const deadline = activeNow() + buildTimeout;
|
|
284
|
+
while (!disposed && state === "running" && activeNow() < deadline) {
|
|
284
285
|
try { if (JSON.parse(readFileSync(reportFile, "utf8")).session === session) return; } catch { /* Waiting for compiler initialization, without requesting a graph. */ }
|
|
285
286
|
await new Promise(resolve => setTimeout(resolve, 20));
|
|
286
287
|
}
|
package/dist/mcp/server.mjs
CHANGED
|
@@ -284,6 +284,7 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
|
|
|
284
284
|
{ uri: "ads://guides/tokens", name: "Shared Data and component variable boundaries", mimeType: "text/markdown" },
|
|
285
285
|
{ uri: "ads://guides/branding", name: "Brand artwork, icons, committed targets and glyph sets", mimeType: "text/markdown" },
|
|
286
286
|
{ uri: "ads://guides/accessibility", name: "WCAG 2.2 AA guards and accessibility practice", mimeType: "text/markdown" },
|
|
287
|
+
{ uri: "ads://guides/performance", name: "Images, fonts, layout shift and what ADS leaves to Lighthouse", mimeType: "text/markdown" },
|
|
287
288
|
{ uri: "ads://guides/reporting", name: "Report suspected ADS bugs and feature requests", mimeType: "text/markdown" },
|
|
288
289
|
{ uri: TOKENS_APP_URI, name: "Experimental token widget", mimeType: APP_MIME },
|
|
289
290
|
{ uri: SCENARIO_APP_URI, name: "Experimental scenario widget", mimeType: APP_MIME },
|
|
@@ -331,6 +332,7 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
|
|
|
331
332
|
if (uri === "ads://guides/validation") return { contents: [{ uri, mimeType: "text/markdown", text: readFileSync(new URL("../skills/ads-designer/references/validation.md", import.meta.url), "utf8") }] };
|
|
332
333
|
if (uri === "ads://guides/runtimes") return { contents: [{ uri, mimeType: "text/markdown", text: readFileSync(new URL("../skills/ads-designer/references/runtimes.md", import.meta.url), "utf8") }] };
|
|
333
334
|
if (uri === "ads://guides/evidence") return { contents: [{ uri, mimeType: "text/markdown", text: readFileSync(new URL("../skills/ads-designer/references/evidence.md", import.meta.url), "utf8") }] };
|
|
335
|
+
if (uri === "ads://guides/performance") return { contents: [{ uri, mimeType: "text/markdown", text: readFileSync(new URL("../skills/ads-designer/references/performance.md", import.meta.url), "utf8") }] };
|
|
334
336
|
if (uri === "ads://guides/accessibility") return { contents: [{ uri, mimeType: "text/markdown", text: readFileSync(new URL("../skills/ads-designer/references/accessibility.md", import.meta.url), "utf8") }] };
|
|
335
337
|
if (uri === "ads://guides/branding") return { contents: [{ uri, mimeType: "text/markdown", text: readFileSync(new URL("../skills/ads-designer/references/branding.md", import.meta.url), "utf8") }] };
|
|
336
338
|
if (uri === "ads://guides/tokens") return { contents: [{ uri, mimeType: "text/markdown", text: readFileSync(new URL("../skills/ads-designer/references/design-data.md", import.meta.url), "utf8") }] };
|
|
@@ -442,7 +444,7 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
|
|
|
442
444
|
{ name:"ads_create_draft", description:"Create a Git-committable proposal under ads-drafts/ for 1–64 coupled ADS owners, copying only their source/companions into non-importable .ads files. New owners are allowed. Optional dependencies name separate unaccepted drafts used by pattern/composition previews. Creation does not change accepted source. Edit the returned files normally; use ads_update_draft to register additions/deletions.", schema:z.object({units:z.array(z.string().min(1).max(256)).min(1).max(mutationLimits.units),title:z.string().min(1).max(160).optional(),id:draftIdSchema.optional(),dependencies:z.array(draftIdSchema).max(8).default([]),tokenGroups:z.array(z.string().min(1).max(160)).max(32).default([])}).strict(),_meta:{ui:{visibility:["model"]}},annotations:{...annotations,readOnlyHint:false,idempotentHint:false},call:async args=>{const result=drafts.create(args);if(observeChanges)await refresh();return json(result);} },
|
|
443
445
|
{ name:"ads_update_draft", description:"Update marked draft source or register new/deleted canonical target paths. Pass the current revision from ads_drafts. Source is UTF-8 unless encoding:base64; content:null proposes deletion. refresh:true rebases onto current accepted source using stored baselines; non-overlapping edits merge and overlapping edits leave the draft unchanged with diagnostics. Use changes with refresh only for explicit resolved contents of existing draft files; refresh separately from dependency changes. Optional dependencies replaces the draft dependency list. Normal local file edits need no iteration tool. Accepted source remains unchanged; ownership and all required checks run at acceptance.",schema:z.object({id:draftIdSchema,revision:draftRevisionSchema,refresh:z.boolean().default(false),dependencies:z.array(draftIdSchema).max(8).optional(),changes:z.array(z.object({unit:z.string().max(256),path:z.string().min(1).max(500),content:z.string().max(256*1024).nullable(),encoding:z.enum(["utf8","base64"]).optional()}).strict()).max(32).default([])}).strict(),_meta:{ui:{visibility:["model"]}},annotations:{...annotations,readOnlyHint:false,idempotentHint:false},call:async args=>{const result=drafts.update(args);if(observeChanges)await refresh();return json(result);} },
|
|
444
446
|
{ name:"ads_drop_draft",description:"Delete an exact tracked draft and its generated preview. This is Drop, not a separate refusal workflow. Accepted source is unchanged. Dependents report a missing dependency until corrected.",schema:z.object({id:draftIdSchema,revision:draftRevisionSchema}).strict(),_meta:{ui:{visibility:["model"]}},annotations:{...annotations,readOnlyHint:false,destructiveHint:true,idempotentHint:false},call:async args=>{const result=await drafts.drop(args);if(observeChanges)await refresh();return json(result);} },
|
|
445
|
-
{ name:"ads_accept",title:"Accept a reviewed draft",description:"Auto-mode acceptance: validate and apply the exact rendered/reviewed draft revision in one operation. Accept dependency drafts first; dependent drafts automatically switch to their final @ds implementations. Mandatory ADS guards and acceptance.checks run once on the candidate; affected registered tests gate acceptance when acceptance.behaviorChecks is true.
|
|
447
|
+
{ name:"ads_accept",title:"Accept a reviewed draft",description:"Auto-mode acceptance: validate and apply the exact rendered/reviewed draft revision in one operation. Accept dependency drafts first; dependent drafts automatically switch to their final @ds implementations. Mandatory ADS guards and acceptance.checks run once on the candidate; affected registered tests gate acceptance when acceptance.behaviorChecks is true. Unless acceptance.browserAudit is false, axe-core audits the candidate's affected UI scenarios in every declared brand and theme; any a11y-axe error (or an audit that cannot run) rejects acceptance. Draft/source changes invalidate acceptance. On failure retain the draft and inspect ads_results; on success apply normal source, remove the draft and publish an event. No additional human approval or manual Apply step.",schema:z.object({fresh:z.boolean().default(false),id:draftIdSchema,revision:draftRevisionSchema}).strict(),_meta:{ui:{visibility:["model"]}},annotations:{...annotations,readOnlyHint:false,destructiveHint:true,idempotentHint:false},call:async(args,signal,progress)=>{
|
|
446
448
|
const result=await drafts.accept(args,signal,progress);
|
|
447
449
|
if(result.applied){await previewWatch?.invalidate?.();await refresh(true);}else await refresh();
|
|
448
450
|
return finishExecution("mutation",result);
|
|
@@ -526,7 +528,7 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
|
|
|
526
528
|
{ name:"ads_report_bug",title:"Report a suspected ADS defect",description:"Record an unexpected ADS guard, preview, build, transport or runner behavior after targeted investigation. Provide expected/observed behavior, minimal steps and frequency; keep suspectedCause separate. Evidence optionally selects a returned resultId or exact unit/check/runId. ADS snapshots compact evidence, version, configured framework and revisions. A report is an untriaged agent claim, not proof of an ADS cause. Returns a small receipt with the report ID and local file path; submitted reports cannot be read through MCP. Stored locally under .ds/reports/ with deduplication, no automatic expiry and no upload. Read ads://guides/reporting; ordinary valid guard rejections should be fixed in their owner.",schema:bugReportSchema,annotations:{readOnlyHint:false,destructiveHint:false,idempotentHint:false,openWorldHint:false},call:args=>submitReport("bug",args) },
|
|
527
529
|
{ name:"ads_request_feature",title:"Request an ADS capability",description:"Record a legitimate workflow that needs a missing ADS capability. Provide workflow, capability and impact; proposal is optional. Preserve valid design/API rather than weakening guards or inventing workaround props. Optional evidence references an existing execution/check, not pasted files/logs. ADS attaches compact context and returns a receipt with the report ID and local file path. Intake is submission-only; no report-reading tools or resources. Shared local report store: deduplicated, untriaged, no automatic expiry or upload. Read ads://guides/reporting; use ads_report_bug for suspected broken existing behavior.",schema:featureRequestSchema,annotations:{readOnlyHint:false,destructiveHint:false,idempotentHint:false,openWorldHint:false},call:args=>submitReport("feature",args) },
|
|
528
530
|
{ name: "ads_investigate", title: "Inspect check evidence", description: "Read a summary for an exact unit/check, or list latest investigations when no check is selected. Pass the outcome's runId to reject superseded evidence. Summary is at most 4 KiB JSON; details, requests, browserErrors and artifacts are separate paged sections (default 10/max 20 entries, 8 KiB). Read truncated rows with recordIndex/offset/chars and the exact runId. Artifact URIs are read separately. Does not rerun checks or infer root cause. Lists latest checks; an exact runId reads retained historical evidence, including candidate runs.", schema: z.object({unit:z.string().min(1).max(256).optional(),check:z.string().min(1).max(100).optional(),runId:z.string().min(1).max(100).optional(),section:z.enum(investigationSections).optional(),...paged,...recordRange}).strict(), call: args => json(investigationPage(root,args)) },
|
|
529
|
-
{ name: "ads_validate", description: "Run mandatory ADS architecture/freshness guards and the selected project policy. policy defaults to validation: its configured scripts, preview freshness, optional registered behavior checks and,
|
|
531
|
+
{ name: "ads_validate", description: "Run mandatory ADS architecture/freshness guards and the selected project policy. policy defaults to validation: its configured scripts, preview freshness, optional registered behavior checks and, unless <policy>.browserAudit is false, an axe-core audit of every rendered UI scenario in every declared brand and theme (a11y-axe findings are blocking errors in the diagnostics section). policy acceptance runs acceptance.checks, acceptance.behaviorChecks and acceptance.browserAudit without applying source, for direct editing; draft acceptance and guarded patches run the same acceptance policy, auditing only the candidate's affected UI scenarios. No script names are inferred. scope changed selects affected registered checks from this policy's own successful full baseline; broad changes expand to all. Project scripts keep full scope. Draft edit/show never triggers policies. Reports skipped stages honestly and a bounded resultId; use ads_results for details. Read ads://guides/validation. Trusted configured commands run; nothing is installed.", schema: z.object({scope:z.enum(["all","changed"]).default("all"),policy:z.enum(["acceptance","validation"]).default("validation"),fresh:z.boolean().default(false)}).strict(), annotations: {readOnlyHint:false,destructiveHint:false,idempotentHint:false,openWorldHint:false}, call: async (args,signal,progress) => {
|
|
530
532
|
return finishExecution("validation",await validation.run(args,signal,progress));
|
|
531
533
|
} },
|
|
532
534
|
{ name: "ads_verify", description: "Run one owner's registered development behavior checks using its configured runner/profile. Executes trusted project commands with bounded output, cancellation and process-tree cleanup; installs nothing. Progress and per-check timings are available through ads_status; a profile timeout bounds the whole run. Browser profiles use an isolated managed showcase/MCP App. React StrictMode requires a project development harness, not a production widget. Missing/skipped cases, stale inputs and process exit alone cannot produce passing evidence. Replies contain counts, acceptance, at most three failure summaries and a resultId (4 KiB JSON maximum). Page outcomes with ads_results; inspect one exact unit/check/runId with ads_investigate. Discover exact unit/check IDs with ads_behaviors first.", schema: z.object({ unit: z.string().min(1).max(256), checks: z.array(z.string().min(1).max(100)).min(1).max(100).optional() }).strict(), annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false }, call: async (args, signal, progress) => {
|
|
@@ -543,11 +545,11 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
|
|
|
543
545
|
const {patch,...result}=reconcileTokenSamples(options,args);
|
|
544
546
|
return json({...result,removed:result.removed.slice(0,50),unresolved:result.unresolved.slice(0,50),unresolvedCount:result.unresolved.length,...storePreparedPatch(options,patch)});
|
|
545
547
|
}},
|
|
546
|
-
{ name: "ads_apply_patch", description: "Apply one Git diff to one ADS unit from ads_units. Pass exactly one of patch (inline) or patchFile (a regular .patch/.diff under .ds/patches/, for large/binary diffs without model-context bytes). Text uses --- a/path, +++ b/path and exact @@ hunks; /dev/null creates/deletes. Git binary patches require git diff --binary --full-index and installed Git. A unit owns its implementation, previews and fixtures; imported peers are separate. Foundation, documentation, assets and configuration are editable too. Configuration changes may register/edit project guards and builders; the proposed schema, mandatory ADS and candidate project checks must pass. Only selected-unit public re-exports may change; preserve unrelated statements. A real selected-unit re-export may remove a redundant export {}; placeholder. A tokens patch may include its companionFiles foundation entry only to add/remove canonical imports required by token files created/deleted in this patch, preserving other imports/comments and canonical order. A runtime owner patch may also include its ds.config.json companion solely for that owner's inlineStyleFiles/styleWrites entries alongside its source. Unused permissions fail validation.
|
|
548
|
+
{ name: "ads_apply_patch", description: "Apply one Git diff to one ADS unit from ads_units. Pass exactly one of patch (inline) or patchFile (a regular .patch/.diff under .ds/patches/, for large/binary diffs without model-context bytes). Text uses --- a/path, +++ b/path and exact @@ hunks; /dev/null creates/deletes. Git binary patches require git diff --binary --full-index and installed Git. A unit owns its implementation, previews and fixtures; imported peers are separate. Foundation, documentation, assets and configuration are editable too. Configuration changes may register/edit project guards and builders; the proposed schema, mandatory ADS and candidate project checks must pass. Only selected-unit public re-exports may change; preserve unrelated statements. A real selected-unit re-export may remove a redundant export {}; placeholder. A tokens patch may include its companionFiles foundation entry only to add/remove canonical imports required by token files created/deleted in this patch, preserving other imports/comments and canonical order. A runtime owner patch may also include its ds.config.json companion solely for that owner's inlineStyleFiles/styleWrites entries alongside its source. Unused permissions fail validation. Unless acceptance.browserAudit is false, axe-core audits the candidate's affected UI scenarios in every brand and theme; a11y-axe errors reject the patch. Set dryRun true to validate without writing. Optional screenshot:true plus captures:[{scenario,target?,theme?,brand?,viewport?}] captures current/candidate only after gates pass. For genuinely coupled owner changes use ads_apply_transaction with one patch per owner. Fix rejected patches and inspect current previews after acceptance. Reply is a 4 KiB summary; read diagnostics, outcomes and requested captures through ads_results using its resultId.",
|
|
547
549
|
schema: z.object({ unit: z.string().min(1).max(256), dryRun: z.boolean(), patch: z.string().min(1).max(mutationLimits.patchBytes).optional(), patchFile: z.string().min(1).max(500).optional(), ...screenshotFields }).strict().refine(args => (args.patch !== undefined) !== (args.patchFile !== undefined), "Provide exactly one of patch or patchFile."),
|
|
548
550
|
annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: false }, _meta: { ui: { visibility: ["model"] } },
|
|
549
551
|
call: applyEdits,
|
|
550
|
-
}, {name:"ads_apply_transaction",description:"Apply genuinely coupled ADS changes as 2–64 distinct owner Git patches. Each patch must obey its unit and narrow companion rules. Patches run in order; later patches use the earlier candidate's shared-entry content. Core guards, configured project checks, affected behavior checks and,
|
|
552
|
+
}, {name:"ads_apply_transaction",description:"Apply genuinely coupled ADS changes as 2–64 distinct owner Git patches. Each patch must obey its unit and narrow companion rules. Patches run in order; later patches use the earlier candidate's shared-entry content. Core guards, configured project checks, affected behavior checks and, unless acceptance.browserAudit is false, the axe-core audit of affected UI scenarios validate the complete final candidate before any live source is written. Maximum 256 distinct files/16 MiB combined. Dry runs, failures and cancellation publish nothing; publication rolls back on write failure. Optional screenshot:true with dryRun:true and explicit captures selects current/candidate images. Prefer ads_apply_patch for independent edits. Reply is a bounded summary; page diagnostics, outcomes and captures with ads_results using the returned resultId.",schema:z.object({patches:z.array(ownerPatch).min(2).max(mutationLimits.units),dryRun:z.boolean(),...screenshotFields}).strict(),annotations:{readOnlyHint:false,destructiveHint:true,idempotentHint:false,openWorldHint:false},_meta:{ui:{visibility:["model"]}},call:applyEdits}] : []),
|
|
551
553
|
...options.config.mcp.apps.map((app) => ({ name: `ads_show_${app.id.replaceAll("-", "_")}`, title: app.title, description: `${app.description ?? app.title}. Renders the project's built ${app.kind} examples through MCP Apps; text fallback provides the showcase URL.`, schema: empty, _meta: { ui: { resourceUri: appUri(app.id) } }, call: async (_args, signal) => {
|
|
552
554
|
// Validate readiness without embedding executable HTML in model results.
|
|
553
555
|
const build = await previewBuild(app, signal);
|