@reqvire-org/ads 0.3.49 → 0.3.51
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/first-render.mjs +18 -0
- package/dist/browser-audit/layout-overflow.mjs +98 -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 +52 -15
- package/dist/browser-audit.mjs +239 -22
- package/dist/capture/worker.mjs +2 -5
- package/dist/check.mjs +16 -1
- package/dist/cli.mjs +9 -5
- package/dist/component-contrast.mjs +138 -0
- package/dist/config.mjs +12 -6
- package/dist/finding-rules.mjs +16 -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 +228 -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 +9 -0
- package/dist/skills/ads-break-ui/references/atomic-styles.md +2 -0
- package/dist/skills/ads-break-ui/references/design-data.md +52 -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 +26 -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 +52 -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 +52 -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 +52 -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 +52 -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/package.json +1 -0
- package/dist/starters/react/ADS.md +1 -1
- package/dist/starters/react/README.md +16 -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 +51 -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/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 +16 -3
- package/docs/CHANGELOG.md +127 -12
- package/docs/GUIDE.md +238 -14
- package/docs/MCP.md +14 -10
- package/package.json +1 -1
package/dist/config.mjs
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { existsSync, readFileSync, readdirSync } from "node:fs";
|
|
2
2
|
import path from "node:path";
|
|
3
|
+
import { hasProjectConfig } from "./project-boundary.mjs";
|
|
3
4
|
import { fileURLToPath } from "node:url";
|
|
4
5
|
import { isDraftFile, draftImportViolation } from "./draft-boundary.mjs";
|
|
5
6
|
import { isSharedToken } from "./token-policy.mjs";
|
|
@@ -27,11 +28,13 @@ export const defaultConfig = {
|
|
|
27
28
|
followSystemTheme: false,
|
|
28
29
|
inlineStyleFiles: [],
|
|
29
30
|
boundaries: { styleWrites: [], componentVariables: [] },
|
|
30
|
-
assets: { publicDirs: ["public/assets"], generatedPaths: ["dist", "dist-showcase", ".vite", ".ds"], generatedFiles: [], iconSource: null, targets: [], glyphs: null },
|
|
31
|
+
assets: { publicDirs: ["public/assets"], generatedPaths: ["dist", "dist-showcase", ".vite", ".ds"], generatedFiles: [], iconSource: null, targets: [], glyphs: null, imageBudgetKb: null },
|
|
31
32
|
oxlint: { plugins: [], rules: {}, overrides: [] },
|
|
32
|
-
acceptance: { checks: [], behaviorChecks: false, browserAudit:
|
|
33
|
-
validation: { checks: [], behaviorChecks: true, browserAudit:
|
|
33
|
+
acceptance: { checks: [], behaviorChecks: false, browserAudit: true },
|
|
34
|
+
validation: { checks: [], behaviorChecks: true, browserAudit: true, inputs: [] },
|
|
34
35
|
resources: { memoryLimitMb: null },
|
|
36
|
+
// Width tokens and owners allowed fixed widths; see src/layout-widths.mjs.
|
|
37
|
+
layout: { widthTokens: [], fixedWidthUnits: [] },
|
|
35
38
|
mcp: { showcaseUrl: null, showcaseTitle: null, apps: [], previewWatch: null, previewManifest: null, mutationCheckTimeoutMs: 60000, behaviorProfiles: {}, capture: {}, resultRetention: {maxRuns:50,maxAgeDays:7,maxBytesMb:256} },
|
|
36
39
|
};
|
|
37
40
|
|
|
@@ -113,11 +116,11 @@ export function loadConfig(directory = process.cwd()) {
|
|
|
113
116
|
}
|
|
114
117
|
if (user.oxlint !== undefined && (!user.oxlint || typeof user.oxlint !== "object" || Array.isArray(user.oxlint))) throw new Error("oxlint must be an object.");
|
|
115
118
|
if (user.mcp && Object.hasOwn(user.mcp,"mutationChecks")) throw new Error("Move mcp.mutationChecks to acceptance.checks; choose acceptance.behaviorChecks explicitly. ADS no longer infers project scripts.");
|
|
116
|
-
for (const field of ["boundaries", "assets", "oxlint", "mcp", "acceptance", "validation", "usage", "resources"]) {
|
|
119
|
+
for (const field of ["boundaries", "assets", "oxlint", "mcp", "acceptance", "validation", "usage", "resources", "layout"]) {
|
|
117
120
|
if (user[field] !== undefined && (!user[field] || typeof user[field] !== "object" || Array.isArray(user[field]))) throw new Error(`${field} must be an object.`);
|
|
118
121
|
for (const key of Object.keys(user[field] ?? {})) if (!(key in defaultConfig[field])) throw new Error(`Unknown ${field} configuration field: ${key}`);
|
|
119
122
|
}
|
|
120
|
-
const config = { ...defaultConfig, ...user, boundaries: { ...defaultConfig.boundaries, ...user.boundaries }, assets: { ...defaultConfig.assets, ...user.assets }, oxlint: { ...defaultConfig.oxlint, ...user.oxlint }, acceptance: { ...defaultConfig.acceptance, ...user.acceptance }, validation: { ...defaultConfig.validation, ...user.validation }, mcp: { ...defaultConfig.mcp, ...user.mcp }, usage: { ...defaultConfig.usage, ...user.usage }, resources: { ...defaultConfig.resources, ...user.resources } };
|
|
123
|
+
const config = { ...defaultConfig, ...user, boundaries: { ...defaultConfig.boundaries, ...user.boundaries }, assets: { ...defaultConfig.assets, ...user.assets }, oxlint: { ...defaultConfig.oxlint, ...user.oxlint }, acceptance: { ...defaultConfig.acceptance, ...user.acceptance }, validation: { ...defaultConfig.validation, ...user.validation }, mcp: { ...defaultConfig.mcp, ...user.mcp }, usage: { ...defaultConfig.usage, ...user.usage }, resources: { ...defaultConfig.resources, ...user.resources }, layout: { ...defaultConfig.layout, ...user.layout } };
|
|
121
124
|
validateThemes(config.themes);
|
|
122
125
|
validateBrands(config.brands);
|
|
123
126
|
if (typeof config.followSystemTheme !== "boolean") throw new Error("followSystemTheme must be true or false.");
|
|
@@ -127,6 +130,9 @@ export function loadConfig(directory = process.cwd()) {
|
|
|
127
130
|
}
|
|
128
131
|
for (const brand of config.brands) if (config.themes.some(theme => theme.name === `brand-${brand.name}`)) throw new Error(`Theme "brand-${brand.name}" and brand "${brand.name}" would share the display switch --display-brand-${brand.name}; rename one.`);
|
|
129
132
|
if(config.resources.memoryLimitMb!==null&&(!Number.isInteger(config.resources.memoryLimitMb)||config.resources.memoryLimitMb<64||config.resources.memoryLimitMb>1048576))throw new Error("resources.memoryLimitMb must be null (automatic) or an integer from 64 to 1048576 MiB.");
|
|
133
|
+
if (config.assets.imageBudgetKb !== null && (!Number.isInteger(config.assets.imageBudgetKb) || config.assets.imageBudgetKb < 1 || config.assets.imageBudgetKb > 1048576)) throw new Error("assets.imageBudgetKb must be null (a limit per format) or a positive whole number of KB for every format.");
|
|
134
|
+
if (!Array.isArray(config.layout.widthTokens) || config.layout.widthTokens.length > 200 || new Set(config.layout.widthTokens).size !== config.layout.widthTokens.length || config.layout.widthTokens.some(name => typeof name !== "string" || !/^--[\w-][\w*-]*$/.test(name))) throw new Error("layout.widthTokens must contain distinct token names or globs such as --panel-*, and cannot name every token.");
|
|
135
|
+
if (!Array.isArray(config.layout.fixedWidthUnits) || config.layout.fixedWidthUnits.length > 200 || new Set(config.layout.fixedWidthUnits).size !== config.layout.fixedWidthUnits.length || config.layout.fixedWidthUnits.some(glob => typeof glob !== "string" || !glob || glob.includes("\\") || glob.startsWith("/") || glob.split("/").includes("..") || !/[^*/]/.test(glob))) throw new Error("layout.fixedWidthUnits must contain distinct unit ids or project-relative globs such as components/Overlay/*, and cannot name every unit.");
|
|
130
136
|
if (!Array.isArray(config.usage.notifications) || config.usage.notifications.length > 100) throw new Error("usage.notifications must be an array of notification API registrations.");
|
|
131
137
|
const notificationNames = new Set();
|
|
132
138
|
for (const entry of config.usage.notifications) {
|
|
@@ -312,7 +318,7 @@ export function sourceFiles(root) {
|
|
|
312
318
|
for (const entry of readdirSync(root, { withFileTypes: true })) {
|
|
313
319
|
if (ignored.has(entry.name) || entry.isSymbolicLink() || isDraftFile(path.join(root, entry.name))) continue;
|
|
314
320
|
const file = path.join(root, entry.name);
|
|
315
|
-
if (entry.isDirectory()) files.push(...sourceFiles(file));
|
|
321
|
+
if (entry.isDirectory()) { if (!hasProjectConfig(file)) files.push(...sourceFiles(file)); }
|
|
316
322
|
else if (entry.isFile() && (/\.(css|html|[cm]?[jt]sx?)$/.test(entry.name) || isBehaviorFile(entry.name))) files.push(file);
|
|
317
323
|
}
|
|
318
324
|
return files.sort();
|
package/dist/finding-rules.mjs
CHANGED
|
@@ -6,16 +6,31 @@
|
|
|
6
6
|
export const findingRules = Object.freeze({
|
|
7
7
|
// Accessibility: deterministic source and token rules, and axe-core where the audit runs.
|
|
8
8
|
"a11y-axe": "error", "a11y-focus": "error", "a11y-icon-label": "error", "a11y-image-alt": "error", "a11y-reduced-motion": "error",
|
|
9
|
-
|
|
9
|
+
// A rendered scenario the audit could not complete after its retries.
|
|
10
|
+
"browser-audit": "error",
|
|
11
|
+
"a11y-non-text-contrast": "error", "a11y-target-size": "error", "a11y-text-resize": "error", "a11y-text-spacing": "error",
|
|
10
12
|
// A click handler on a non-control may be reachable through a delegated or wrapping control.
|
|
11
13
|
"a11y-keyboard": "review",
|
|
14
|
+
// What axe reports it could not decide: nothing fails, and someone checks it by hand.
|
|
15
|
+
"a11y-incomplete": "info",
|
|
12
16
|
// Atomic styles: the composition analysis is heuristic; its limits are informational.
|
|
13
17
|
"atomic-composition-review": "review", "atomic-composition-limit": "info",
|
|
18
|
+
// Text and background a component style block pairs itself; a side that names no color token is informational.
|
|
19
|
+
"component-contrast": "error", "component-contrast-unresolved": "info",
|
|
14
20
|
// Brand artwork and brand token values.
|
|
15
21
|
"brand-coverage": "error", "brand-empty": "error", "brand-license": "error", "brand-new-token": "error", "brand-preview": "error", "brand-readme": "error",
|
|
16
22
|
// Artwork may be used by code ADS cannot trace (a CMS, a server template).
|
|
17
23
|
"brand-unused": "review",
|
|
18
24
|
"control-padding": "error",
|
|
25
|
+
// Widths are fluid on the grid: fixed widths from source, and overflow where the audit renders.
|
|
26
|
+
"layout-fixed-width": "error", "layout-overflow": "error",
|
|
27
|
+
// Whether a declared width must stay fixed, a fluid wrapper does anything, or a part ever sits in
|
|
28
|
+
// a narrow pane takes judgement.
|
|
29
|
+
"layout-declared-width": "review", "layout-width-noop": "review", "layout-overflow-narrow": "review",
|
|
30
|
+
// Images reserve their space and choose how they load; a spread or foreign class cannot be read.
|
|
31
|
+
"img-attributes": "error", "img-attributes-unresolved": "info",
|
|
32
|
+
"asset-image-budget": "error",
|
|
33
|
+
"layout-shift": "error",
|
|
19
34
|
"glyph-aliases": "error", "glyph-color": "error", "glyph-viewbox": "error",
|
|
20
35
|
// Local source cannot prove pointer-capture cleanup or dynamic scenario execution.
|
|
21
36
|
"pointer-capture-review": "review", "scenario-exercise-review": "review",
|
|
@@ -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,228 @@
|
|
|
1
|
+
import valueParser from "postcss-value-parser";
|
|
2
|
+
import { contextValues } from "./themes.mjs";
|
|
3
|
+
import { findingSeverity } from "./finding-rules.mjs";
|
|
4
|
+
|
|
5
|
+
/** In component, pattern and composition styles, a width (width, min-width, the logical inline
|
|
6
|
+
* sizes, flex-basis or the flex shorthand's basis, and grid-template-columns tracks) is a
|
|
7
|
+
* layout-fixed-width error when it cannot shrink below smallPartLimitPx: raw, through tokens, in
|
|
8
|
+
* any length unit, or by arithmetic. Every value is read as what it resolves to in the smallest
|
|
9
|
+
* and the largest container, so max(100%, 280px) is fixed at 280px, and min(100%, 280px) is not.
|
|
10
|
+
* A maximum cannot force overflow, so max-width and max-inline-size are not read at all, except
|
|
11
|
+
* that a fluid one in the same rule lets a width shrink.
|
|
12
|
+
* What the source cannot settle (a variable with no definition) passes; the audit renders it.
|
|
13
|
+
* Tokens named by layout.widthTokens pass when used plainly, and fixed ones are listed for review,
|
|
14
|
+
* as are the fixed widths of owners matched by layout.fixedWidthUnits, which is where overlays
|
|
15
|
+
* such as dialogs, menus, popovers and tooltips are declared: ADS knows a unit's layer, not
|
|
16
|
+
* whether it floats. */
|
|
17
|
+
|
|
18
|
+
/** The largest plain size a part may have: see the Layout section of the guide for the evidence. */
|
|
19
|
+
export const smallPartLimitPx = 96;
|
|
20
|
+
const widthProperties = new Set(["width", "min-width", "inline-size", "min-inline-size", "flex-basis", "flex", "grid-template-columns"]);
|
|
21
|
+
const fluidUnits = /^(?:%|fr|[sld]?v(?:w|h|i|b|min|max)|cq(?:w|h|i|b|min|max))$/i;
|
|
22
|
+
/** Lengths in px; a font-relative one at the 16 px root font, as an estimate. It is still fixed. */
|
|
23
|
+
const absoluteUnits = { px: 1, pt: 4 / 3, pc: 16, in: 96, cm: 96 / 2.54, mm: 96 / 25.4, q: 96 / 101.6 };
|
|
24
|
+
const fontUnits = { rem: 16, em: 16, ic: 16, ch: 8, ex: 8, cap: 11, lh: 24, rlh: 24 };
|
|
25
|
+
const keywords = /^(?:auto|none|min-content|max-content|fit-content|stretch|inherit|initial|unset|revert|revert-layer|content|subgrid)$/i;
|
|
26
|
+
const fluid = { low: 0, high: Infinity }, neutral = { neutral: true }, unknown = { unknown: true };
|
|
27
|
+
const isLength = part => part.low !== undefined;
|
|
28
|
+
const fixedAt = px => ({ low: px, high: px });
|
|
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 declaredUses = new Map();
|
|
48
|
+
|
|
49
|
+
function variable(node, scope) {
|
|
50
|
+
const [name, fallback = []] = splitArguments(node.nodes).map(meaningful);
|
|
51
|
+
const token = name?.find(child => child.type === "word")?.value;
|
|
52
|
+
if (!token?.startsWith("--")) return unknown;
|
|
53
|
+
if (scope.seen.has(token)) return unknown;
|
|
54
|
+
const seen = new Set([...scope.seen, token]);
|
|
55
|
+
// Component variables declared in the same template are read through, so a width cannot hide in one.
|
|
56
|
+
const local = scope.locals.get(token);
|
|
57
|
+
if (local) {
|
|
58
|
+
const results = local.map(value => sequence(valueParser(value).nodes, { ...scope, seen })).filter(isLength);
|
|
59
|
+
return results.length ? results.reduce((worst, result) => result.low > worst.low ? result : worst) : unknown;
|
|
60
|
+
}
|
|
61
|
+
const value = values.get(token)?.value;
|
|
62
|
+
if (value === undefined) return fallback.length ? sequence(fallback, { ...scope, seen }) : unknown;
|
|
63
|
+
const result = sequence(valueParser(value).nodes, { ...scope, seen });
|
|
64
|
+
if (!widthToken(token)) return result;
|
|
65
|
+
scope.declared?.add(token);
|
|
66
|
+
return { ...(isLength(result) ? result : neutral), declared: token };
|
|
67
|
+
}
|
|
68
|
+
/** One value part: { neutral } | { unknown } | { number } | { low, high, declared? }, the length
|
|
69
|
+
* it resolves to in the smallest and the largest container. */
|
|
70
|
+
function measure(node, scope) {
|
|
71
|
+
if (node.type === "word") {
|
|
72
|
+
const parsed = valueParser.unit(node.value);
|
|
73
|
+
if (!parsed) return keywords.test(node.value) ? neutral : unknown;
|
|
74
|
+
const number = Number(parsed.number), unit = parsed.unit.toLowerCase();
|
|
75
|
+
if (!unit) return number === 0 ? fixedAt(0) : { number };
|
|
76
|
+
if (number === 0) return fixedAt(0);
|
|
77
|
+
if (fluidUnits.test(unit)) return fluid;
|
|
78
|
+
const size = absoluteUnits[unit] ?? fontUnits[unit];
|
|
79
|
+
return size ? fixedAt(number * size) : unknown;
|
|
80
|
+
}
|
|
81
|
+
if (node.type !== "function") return unknown;
|
|
82
|
+
const name = node.value.toLowerCase();
|
|
83
|
+
if (name === "var") return variable(node, scope);
|
|
84
|
+
if (name === "calc" || name === "") return calculation(node.nodes, scope);
|
|
85
|
+
if (name === "fit-content") return neutral;
|
|
86
|
+
if (name === "min") return smallest(splitArguments(node.nodes).map(part => sequence(part, scope)));
|
|
87
|
+
if (name === "max") return largest(splitArguments(node.nodes).map(part => sequence(part, scope)));
|
|
88
|
+
if (name !== "clamp") return unknown;
|
|
89
|
+
const [floor, preferred, ceiling] = splitArguments(node.nodes).map(part => sequence(part, scope));
|
|
90
|
+
if (floor?.neutral) return ceiling?.neutral || !ceiling ? preferred ?? unknown : smallest([preferred, ceiling]);
|
|
91
|
+
return largest([floor, !ceiling || ceiling.neutral ? preferred : smallest([preferred, ceiling])]);
|
|
92
|
+
}
|
|
93
|
+
/** min(): a part that reaches zero lets the whole shrink, whatever the others are. */
|
|
94
|
+
function smallest(parts) {
|
|
95
|
+
const lengths = parts.filter(isLength), open = lengths.length !== parts.length;
|
|
96
|
+
if (!lengths.length || open && !lengths.some(part => part.low === 0)) return unknown;
|
|
97
|
+
return { low: Math.min(...lengths.map(part => part.low)), high: open ? Infinity : Math.min(...lengths.map(part => part.high)) };
|
|
98
|
+
}
|
|
99
|
+
/** max(): it cannot shrink below any part, so a part that cannot be read leaves it unread. */
|
|
100
|
+
function largest(parts) {
|
|
101
|
+
if (!parts.every(isLength)) return unknown;
|
|
102
|
+
return { low: Math.max(...parts.map(part => part.low)), high: Math.max(...parts.map(part => part.high)) };
|
|
103
|
+
}
|
|
104
|
+
function sequence(nodes, scope) {
|
|
105
|
+
const items = meaningful(nodes);
|
|
106
|
+
return items.length === 1 ? measure(items[0], scope) : unknown;
|
|
107
|
+
}
|
|
108
|
+
const scaled = (length, factor) => {
|
|
109
|
+
const [low, high] = [length.low, length.high].map(size => factor === 0 ? 0 : size * factor);
|
|
110
|
+
return factor < 0 ? { low: high, high: low } : { low, high };
|
|
111
|
+
};
|
|
112
|
+
/** calc(): evaluated at both ends, so 100% - 200px reaches zero and 100% + 200px does not. */
|
|
113
|
+
function calculation(nodes, scope) {
|
|
114
|
+
const operands = [], operators = [];
|
|
115
|
+
for (const item of meaningful(nodes)) {
|
|
116
|
+
if (item.type === "div" && item.value === "/") { operators.push("/"); continue; }
|
|
117
|
+
if (item.type !== "word") { operands.push(measure(item, scope)); continue; }
|
|
118
|
+
if (["+", "-"].includes(item.value)) { operators.push(item.value); continue; }
|
|
119
|
+
// valueParser keeps * and calc()'s / in a word, spaced or not.
|
|
120
|
+
for (const part of item.value.split(/([*/])/).filter(Boolean)) { if (part === "*" || part === "/") operators.push(part); else operands.push(measure({ type: "word", value: part }, scope)); }
|
|
121
|
+
}
|
|
122
|
+
if (operands.length !== operators.length + 1 || operands.some(operand => !isLength(operand) && operand.number === undefined)) return unknown;
|
|
123
|
+
// Multiplication and division bind first.
|
|
124
|
+
const terms = [operands[0]], signs = [];
|
|
125
|
+
operators.forEach((operator, index) => {
|
|
126
|
+
const next = operands[index + 1];
|
|
127
|
+
if (operator !== "*" && operator !== "/") { terms.push(next); signs.push(operator); return; }
|
|
128
|
+
const last = terms.pop(), length = isLength(last) ? last : next, factor = isLength(last) ? next.number : last.number;
|
|
129
|
+
if (!isLength(length)) terms.push({ number: operator === "*" ? last.number * next.number : last.number / next.number });
|
|
130
|
+
else if (factor === undefined) terms.push(unknown);
|
|
131
|
+
else terms.push(scaled(length, operator === "*" ? factor : 1 / factor));
|
|
132
|
+
});
|
|
133
|
+
if (!terms.every(isLength)) return unknown;
|
|
134
|
+
let { low, high } = terms[0];
|
|
135
|
+
terms.slice(1).forEach((term, index) => {
|
|
136
|
+
if (signs[index] === "+") { low += term.low; high += term.high; } else { low -= term.high; high -= term.low; }
|
|
137
|
+
});
|
|
138
|
+
return { low: Math.max(low, 0), high: Math.max(high, 0) };
|
|
139
|
+
}
|
|
140
|
+
/** The sizes of a grid-template-columns value. minmax() can shrink to its minimum, and a track
|
|
141
|
+
* repeated with auto-fill or auto-fit wraps instead of forcing overflow. */
|
|
142
|
+
function tracks(nodes, scope) {
|
|
143
|
+
const sizes = [];
|
|
144
|
+
for (const node of meaningful(nodes)) {
|
|
145
|
+
const name = node.type === "function" ? node.value.toLowerCase() : "";
|
|
146
|
+
if (node.type === "word" && node.value.startsWith("[")) continue;
|
|
147
|
+
if (name === "repeat") {
|
|
148
|
+
const [count, ...rest] = splitArguments(node.nodes);
|
|
149
|
+
if (!/^auto-(?:fill|fit)$/i.test(meaningful(count)[0]?.value ?? "")) sizes.push(...tracks(rest.flat(), scope));
|
|
150
|
+
} else if (name === "minmax") {
|
|
151
|
+
const floor = sequence(splitArguments(node.nodes)[0] ?? [], scope);
|
|
152
|
+
sizes.push(isLength(floor) ? { ...floor, high: Infinity } : neutral);
|
|
153
|
+
} else sizes.push(measure(node, scope));
|
|
154
|
+
}
|
|
155
|
+
return sizes;
|
|
156
|
+
}
|
|
157
|
+
/** What a width that can give way looks like, in the terms of the property it is set on. */
|
|
158
|
+
const fix = (property, value, px) => property === "grid-template-columns" ? `a track of minmax(0, ${px}px)` : property === "flex" || property === "flex-basis" ? `flex: 1 1 ${px}px` : `${property}: min(100%, ${value})`;
|
|
159
|
+
/** What is wrong with a resolved width: { error } | { review } | null when it is fluid or allowed. */
|
|
160
|
+
function verdict(result, property, value) {
|
|
161
|
+
if (!isLength(result) || result.declared) return null;
|
|
162
|
+
if (result.low > smallPartLimitPx) {
|
|
163
|
+
const px = Math.round(result.low);
|
|
164
|
+
return { error: result.low === result.high ? `fixed at about ${px}px` : `unable to shrink below about ${px}px`, fix: fix(property, value, px) };
|
|
165
|
+
}
|
|
166
|
+
return result.low !== result.high && result.high <= smallPartLimitPx ? { review: Math.round(result.high) } : null;
|
|
167
|
+
}
|
|
168
|
+
function judge(property, value, scope) {
|
|
169
|
+
const nodes = valueParser(value).nodes;
|
|
170
|
+
if (property === "grid-template-columns") {
|
|
171
|
+
for (const track of tracks(nodes, scope)) { const found = verdict(track, property, value); if (found?.error) return { ...found, error: `a track ${found.error}` }; }
|
|
172
|
+
return null;
|
|
173
|
+
}
|
|
174
|
+
if (property === "flex") {
|
|
175
|
+
const parts = meaningful(nodes);
|
|
176
|
+
if (parts.length < 2) return null;
|
|
177
|
+
const basis = parts.at(-1), shrink = parts.length === 3 ? Number(parts[1].value) : 1;
|
|
178
|
+
return Number(parts[0].value) > 0 && shrink > 0 ? null : verdict(measure(basis, scope), property, value);
|
|
179
|
+
}
|
|
180
|
+
return verdict(sequence(nodes, scope), property, value);
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
return {
|
|
184
|
+
/** layout-fixed-width and layout-width-noop findings for one parsed style sheet or Linaria template. */
|
|
185
|
+
inspect(css, file, offset = { line: 1, column: 1 }) {
|
|
186
|
+
const findings = [], locals = new Map();
|
|
187
|
+
css.walkDecls(/^--/, decl => { locals.set(decl.prop, [...(locals.get(decl.prop) ?? []), decl.value]); });
|
|
188
|
+
css.walkDecls(decl => {
|
|
189
|
+
const property = decl.prop.toLowerCase();
|
|
190
|
+
if (!widthProperties.has(property) || decl.value.includes("__ds_expression__")) return;
|
|
191
|
+
const declared = new Set(), scope = { seen: new Set(), locals, declared }, found = judge(property, decl.value, scope);
|
|
192
|
+
for (const token of declared) declaredUses.set(token, (declaredUses.get(token) ?? 0) + 1);
|
|
193
|
+
if (!found) return;
|
|
194
|
+
// width: 280px with max-width: 100% in the same rule is min(100%, 280px).
|
|
195
|
+
if (found.error && /^(?:width|inline-size)$/.test(property) && decl.parent.nodes.some(sibling => sibling.type === "decl" && /^max-(?:width|inline-size)$/i.test(sibling.prop) && sequence(valueParser(sibling.value).nodes, scope).low === 0)) return;
|
|
196
|
+
const line = offset.line + decl.source.start.line - 1, column = decl.source.start.column + (decl.source.start.line === 1 ? offset.column - 1 : 0);
|
|
197
|
+
if (found.review !== undefined) {
|
|
198
|
+
findings.push({ rule: "layout-width-noop", severity: findingSeverity("layout-width-noop"), file, line, column, property, value: decl.value, guidanceUri: "ads://guides/tokens",
|
|
199
|
+
message: `${file}:${line} sets ${property}: ${decl.value}. It never exceeds ${found.review}px, within the ${smallPartLimitPx}px a small part may use plainly, so the fluid part does nothing. Write the plain size.` });
|
|
200
|
+
return;
|
|
201
|
+
}
|
|
202
|
+
findings.push({ rule: "layout-fixed-width", severity: findingSeverity("layout-fixed-width"), file, line, column, property, value: decl.value, guidanceUri: "ads://guides/tokens",
|
|
203
|
+
message: `${file}:${line} sets ${property}: ${decl.value}, ${found.error}, above the ${smallPartLimitPx}px a small part may use. The fix depends on what this is. A small part: size it at ${smallPartLimitPx}px or less, plainly, and leave it. A panel, column or anything else that can give way: ${found.fix}. A part that truly stays this wide: give it a token, list the token in layout.widthTokens in ds.config.json, and use the token plainly; ads check lists it for review. These do not fix it: another unit (ch, em and rem are fixed too), max() or a min() that stays under ${smallPartLimitPx}px, or a token name such as --control-*, since no name is exempt.` });
|
|
204
|
+
});
|
|
205
|
+
return findings;
|
|
206
|
+
},
|
|
207
|
+
/** Every fixed width the project declared, for review, so that it stays visible: tokens named by
|
|
208
|
+
* layout.widthTokens with how many widths use them, and what fixedWidthUnits owners set. Call
|
|
209
|
+
* it after inspect has seen every style. */
|
|
210
|
+
declaredWidths(ownerFindings = []) {
|
|
211
|
+
const findings = [];
|
|
212
|
+
for (const token of tokens) {
|
|
213
|
+
if (!widthToken(token.name)) continue;
|
|
214
|
+
const value = values.get(token.name)?.value;
|
|
215
|
+
const result = value === undefined ? unknown : sequence(valueParser(value).nodes, { seen: new Set([token.name]), locals: new Map() });
|
|
216
|
+
if (!isLength(result) || result.low <= smallPartLimitPx) continue;
|
|
217
|
+
const definition = token.definitions[0], uses = declaredUses.get(token.name) ?? 0;
|
|
218
|
+
findings.push({ rule: "layout-declared-width", severity: findingSeverity("layout-declared-width"), file: definition.file, line: definition.line, column: definition.column, tokens: [token.name], guidanceUri: "ads://guides/tokens",
|
|
219
|
+
message: `${token.name} is ${value}, declared in layout.widthTokens: it cannot shrink below about ${Math.round(result.low)}px. ${uses ? `${uses} width declaration${uses === 1 ? " uses" : "s use"} it. Confirm it must stay fixed.` : "No width uses it, and a maximum needs no declaration: remove it from layout.widthTokens."}` });
|
|
220
|
+
}
|
|
221
|
+
const owners = new Map();
|
|
222
|
+
for (const finding of ownerFindings) owners.set(finding.file, [...(owners.get(finding.file) ?? []), finding]);
|
|
223
|
+
for (const [file, list] of owners) findings.push({ rule: "layout-declared-width", severity: findingSeverity("layout-declared-width"), file, line: list[0].line, column: list[0].column, guidanceUri: "ads://guides/tokens",
|
|
224
|
+
message: `${file} is in layout.fixedWidthUnits, so its widths are not checked: ${list.map(finding => `${finding.property}: ${finding.value} (line ${finding.line})`).join(", ")}. Confirm it floats above the layout.` });
|
|
225
|
+
return findings;
|
|
226
|
+
},
|
|
227
|
+
};
|
|
228
|
+
}
|
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
|
}
|