@reqvire-org/ads 0.4.3 → 0.4.5
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 +12 -9
- package/dist/bun-compiler.mjs +6 -5
- package/dist/check.mjs +3 -43
- package/dist/cli.mjs +1 -1
- package/dist/contrast-composition.mjs +6 -60
- package/dist/contrast-styles.mjs +88 -0
- package/dist/mcp/apps.mjs +7 -1
- package/dist/mcp/build-status.mjs +8 -3
- package/dist/mcp/drafts.mjs +13 -1
- package/dist/mcp/preview-http.bundle.js +7 -0
- package/dist/mcp/preview-http.mjs +148 -0
- package/dist/mcp/preview-widget.bundle.js +47 -47
- package/dist/mcp/resource-loader.js +1 -201
- package/dist/mcp/sandbox-host.mjs +6 -1
- package/dist/mcp/server.mjs +35 -4
- package/dist/mcp/showcase-host.mjs +55 -5
- package/dist/mcp/showcase-http.mjs +66 -0
- package/dist/preview-bun.mjs +75 -60
- package/dist/preview-incremental.mjs +358 -0
- package/dist/preview-manifest-update.mjs +70 -0
- package/dist/preview-resources.mjs +33 -1
- package/dist/render-composition.mjs +27 -5
- package/dist/scenarios-compiler.mjs +19 -1
- package/dist/showcase/client.bundle.js +54 -54
- package/dist/showcase/comparison.js +15 -12
- package/dist/showcase/connection.js +10 -0
- package/dist/showcase/http-client.bundle.js +9 -0
- package/dist/showcase/http-connection.js +86 -0
- package/dist/showcase/http-preview.js +81 -0
- package/dist/showcase-http-routes.mjs +31 -0
- package/dist/skills/README.md +3 -3
- package/dist/skills/ads-designer/SKILL.md +5 -1
- package/dist/skills/ads-designer/references/accessibility.md +6 -2
- package/dist/skills/ads-designer/references/captures.md +1 -1
- package/dist/skills/ads-designer/references/runtimes.md +31 -0
- package/dist/skills/ads-designer/references/workflows.md +16 -0
- package/dist/skills/ads-import/references/captures.md +1 -1
- package/dist/skills/ads-import/references/runtimes.md +31 -0
- package/dist/skills/ads-import/references/workflows.md +16 -0
- package/dist/skills/ads-migrate/SKILL.md +3 -1
- package/dist/skills/ads-migrate/references/0.4.1-to-0.4.2.md +2 -3
- package/dist/skills/ads-migrate/references/0.4.3-to-0.4.4.md +89 -0
- package/dist/skills/ads-migrate/references/0.4.4-to-0.4.5.md +72 -0
- package/dist/skills/ads-port/references/captures.md +1 -1
- package/dist/skills/ads-port/references/runtimes.md +31 -0
- package/dist/skills/ads-port/references/workflows.md +16 -0
- package/dist/style-token-rules.mjs +51 -0
- package/dist/verification/browser.mjs +2 -2
- package/docs/ADS.md +9 -7
- package/docs/ARCHITECTURE.md +109 -48
- package/docs/CACHING.md +40 -1
- package/docs/CHANGELOG.md +100 -22
- package/docs/GUIDE.md +37 -10
- package/docs/HTTP-SHOWCASE-POC.md +397 -0
- package/docs/MCP.md +104 -25
- package/docs/benchmarks/README.md +1 -1
- package/docs/benchmarks/http-showcase-optimized.json +1879 -0
- package/docs/benchmarks/http-showcase-profile.json +308 -0
- package/docs/benchmarks/http-showcase.json +3069 -0
- package/package.json +6 -4
package/README.md
CHANGED
|
@@ -151,7 +151,7 @@ Linaria; integrate its extraction with your build as described in the
|
|
|
151
151
|
| `ads check` | Check tokens, styles, imports, and ADS ownership; errors fail, review items are listed |
|
|
152
152
|
| `ads validate` | Run the full gate: `ads check`, project scripts, every behavior test and the render audit |
|
|
153
153
|
| `ads validate --changed` | The same gate for what changed since the last successful full run |
|
|
154
|
-
| `ads compile` | Compile
|
|
154
|
+
| `ads compile` | Compile complete previews with Bun; `--watch` uses incremental module updates |
|
|
155
155
|
| `ads tokens` | Inspect token values and themes |
|
|
156
156
|
| `ads behaviors` | Inspect registered behavior guarantees and current evidence |
|
|
157
157
|
| `ads verify --unit <id>` | Run an owner's registered behavior checks |
|
|
@@ -234,14 +234,17 @@ Clients without Apps can inspect text/resources and use the regular showcase.
|
|
|
234
234
|
|
|
235
235
|
## Showcase
|
|
236
236
|
|
|
237
|
-
The showcase is
|
|
238
|
-
|
|
239
|
-
collapsible
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
237
|
+
The showcase is a neutral browser workspace delivered over HTTP. Brand, Icons,
|
|
238
|
+
Pictograms, Tokens, Components, Patterns and Composition share its header,
|
|
239
|
+
collapsible menu, theme/brand switches and preview area. The browser receives
|
|
240
|
+
catalogues and checked assets directly from the local ADS runtime, with live
|
|
241
|
+
build reports over server-sent events. It contains no MCP client.
|
|
242
|
+
|
|
243
|
+
Real scenarios run inside a persistent, isolated preview iframe. Compatible
|
|
244
|
+
edits update that frame while retaining state; project code and styles stay
|
|
245
|
+
inside its sandbox. Agents and external MCP Apps use the same compiler and
|
|
246
|
+
checks through the existing MCP interface. The project owns its implementations
|
|
247
|
+
and colocated scenarios/fixtures.
|
|
245
248
|
|
|
246
249
|
Starting `ads mcp` also starts the local showcase. Open the URL returned by
|
|
247
250
|
`ads_status`; use that existing runtime when an agent is already connected.
|
package/dist/bun-compiler.mjs
CHANGED
|
@@ -3,14 +3,15 @@ import { fileURLToPath } from "node:url";
|
|
|
3
3
|
import { restoreCompiledPreviews, runScenarioCompiler } from "./scenarios-compiler.mjs";
|
|
4
4
|
import { loadConfig } from "./config.mjs";
|
|
5
5
|
import { withPreviewSession } from "./preview-scope.mjs";
|
|
6
|
-
import {
|
|
6
|
+
import { previewFrameFiles } from "./preview-bun.mjs";
|
|
7
|
+
import { createIncrementalPreviewBuilder } from "./preview-incremental.mjs";
|
|
7
8
|
import { checkCandidate } from "./validation-checks.mjs";
|
|
8
9
|
import { renderStoppingRules } from "./finding-rules.mjs";
|
|
9
10
|
|
|
10
11
|
const compilerFiles = [
|
|
11
12
|
import.meta.filename,
|
|
12
13
|
...previewFrameFiles,
|
|
13
|
-
...["preview-bun.mjs", "preview-imports.mjs", "bun-worker.mjs", "construction-styles.cjs", "lockup-model.cjs", "spatial-model.cjs", "spatial-inputs.cjs", "spatial-contexts.cjs", "spatial-css.cjs", "linaria/spatial-inputs.cjs", "linaria/preserve-values.cjs"].map((file) => fileURLToPath(new URL(file, import.meta.url))),
|
|
14
|
+
...["preview-bun.mjs", "preview-incremental.mjs", "preview-resources.mjs", "preview-imports.mjs", "bun-worker.mjs", "construction-styles.cjs", "lockup-model.cjs", "spatial-model.cjs", "spatial-inputs.cjs", "spatial-contexts.cjs", "spatial-css.cjs", "linaria/spatial-inputs.cjs", "linaria/preserve-values.cjs"].map((file) => fileURLToPath(new URL(file, import.meta.url))),
|
|
14
15
|
];
|
|
15
16
|
|
|
16
17
|
function validator(root) {
|
|
@@ -25,19 +26,19 @@ function validator(root) {
|
|
|
25
26
|
};
|
|
26
27
|
}
|
|
27
28
|
|
|
28
|
-
/**
|
|
29
|
+
/** One ADS scheduler serves watched module graphs and complete Bun builds. */
|
|
29
30
|
export async function compilePreviews(directory = process.cwd(), { watched = false } = {}) {
|
|
30
31
|
const root = path.resolve(directory);
|
|
31
32
|
if (!watched) {
|
|
32
33
|
const restored = await restoreCompiledPreviews(withPreviewSession(loadConfig(root), process.env.ADS_MCP_BUILD_SESSION), compilerFiles);
|
|
33
34
|
if (restored) return restored;
|
|
34
35
|
}
|
|
35
|
-
//
|
|
36
|
+
// The project and each hosted draft own separate validators and compiler graphs.
|
|
36
37
|
const main = await runScenarioCompiler(root, (projectRoot) => ({
|
|
37
38
|
watched,
|
|
38
39
|
compilerFiles,
|
|
39
40
|
validate: validator(projectRoot),
|
|
40
|
-
buildGraph:
|
|
41
|
+
buildGraph: createIncrementalPreviewBuilder(),
|
|
41
42
|
}));
|
|
42
43
|
if (watched) for (const signal of ["SIGINT", "SIGTERM"]) process.once(signal, async () => main?.stop());
|
|
43
44
|
return main;
|
package/dist/check.mjs
CHANGED
|
@@ -37,7 +37,7 @@ import { inspectScenarioCoverage } from "./scenarios.mjs";
|
|
|
37
37
|
import { uiOperation, importedUiApi } from "./ui-framework.mjs";
|
|
38
38
|
import { inspectStyleBoundaries, pointerCaptureAdvisories } from "./style-boundaries.mjs";
|
|
39
39
|
import { inspectBehaviors, inspectControllers } from "./behaviors.mjs";
|
|
40
|
-
import {
|
|
40
|
+
import { styleTokenViolations } from "./style-token-rules.mjs";
|
|
41
41
|
import { foundationDeclaration, foundationSelector } from "./foundation.mjs";
|
|
42
42
|
import { inspectUnits } from "./units.mjs";
|
|
43
43
|
import { generatedEntryDiagnostics } from "./generated-entries.mjs";
|
|
@@ -49,7 +49,7 @@ import { createScenarioSelectors } from "./scenario-selectors.mjs";
|
|
|
49
49
|
import { architectureEvidence, failure } from "./evidence.mjs";
|
|
50
50
|
import { propertyRegistration } from "./property-registrations.mjs";
|
|
51
51
|
import { createLayerBoundaries, layerSourceFiles } from "./layers.mjs";
|
|
52
|
-
import { createDesignValues, designTemplateVariants, inspectDesignAliases
|
|
52
|
+
import { createDesignValues, designTemplateVariants, inspectDesignAliases } from "./design-values.mjs";
|
|
53
53
|
import { inspectTestBoundaries } from "./test-boundaries.mjs";
|
|
54
54
|
import { inspectBehaviorLibraries } from "./behavior-libraries.mjs";
|
|
55
55
|
import { inspectUsage } from "./usage.mjs";
|
|
@@ -575,47 +575,7 @@ async function checkCapturedProject(directory, { trackingRoot }) {
|
|
|
575
575
|
report(file, "token-reference", `Undefined shared token ${ref.name}.`, offset.line + decl.source.start.line - 1, decl.source.start.column);
|
|
576
576
|
}
|
|
577
577
|
if (fontDescriptor || propertyDescriptor) return; // Font metadata defines source assets, not token-backed UI styles.
|
|
578
|
-
const violations =
|
|
579
|
-
if (decl.value.includes("__ds_expression__"))
|
|
580
|
-
violations.add(
|
|
581
|
-
"Cannot establish this interpolated design value from source. Use a source-resolvable shared token/mapping; unknown interpolation does not grant permission for private design values.",
|
|
582
|
-
);
|
|
583
|
-
valueParser(decl.value).walk((node) => {
|
|
584
|
-
if (node.type === "function" && node.value === "url") return false;
|
|
585
|
-
if (node.type === "word" && decl.prop.startsWith("--") && isColorKeyword(node.value))
|
|
586
|
-
violations.add("Component variables map shared Data; named colors also require shared tokens.");
|
|
587
|
-
if (
|
|
588
|
-
node.type === "word" &&
|
|
589
|
-
(/^#[\da-f]{3,8}$/i.test(node.value) ||
|
|
590
|
-
(tokenLengthLiteral(node.value) &&
|
|
591
|
-
!(
|
|
592
|
-
isReviewFile(file, options) &&
|
|
593
|
-
/^(?:(?:min-|max-)?(?:width|height|inline-size|block-size)|flex-basis|grid-template-columns|grid-template-rows)$/.test(decl.prop)
|
|
594
|
-
)) ||
|
|
595
|
-
["s", "ms"].includes(numericCssUnit(node.value)))
|
|
596
|
-
)
|
|
597
|
-
violations.add(
|
|
598
|
-
"Use a token for colors, absolute/font-relative lengths (including ch), and durations. Unitless geometry and structural angle/viewport/container relationships remain valid.",
|
|
599
|
-
);
|
|
600
|
-
if (node.type === "function" && /^(?:rgb|rgba|hsl|hsla|hwb|lab|lch|oklab|oklch|color|color-mix|cubic-bezier)$/.test(node.value))
|
|
601
|
-
violations.add("Define color formulas and easing in tokens.");
|
|
602
|
-
if (node.type === "function" && /^(?:blur|brightness|contrast|drop-shadow|grayscale|hue-rotate|invert|saturate|sepia)$/.test(node.value))
|
|
603
|
-
violations.add("Define visual filter effects in tokens.");
|
|
604
|
-
if (node.type === "word" && /^ease(?:-in|-out|-in-out)?$/.test(node.value)) violations.add("Use a motion token for easing.");
|
|
605
|
-
if (
|
|
606
|
-
node.type === "word" &&
|
|
607
|
-
/^(?:color|background-color|(?:border|outline|caret|text-decoration|column-rule)(?:-[a-z]+)?-color|fill|stroke)$/.test(decl.prop) &&
|
|
608
|
-
/^[a-z]+$/i.test(node.value) &&
|
|
609
|
-
!/^(?:inherit|initial|unset|revert|currentcolor|transparent|none)$/i.test(node.value)
|
|
610
|
-
)
|
|
611
|
-
violations.add("Use a semantic color token.");
|
|
612
|
-
});
|
|
613
|
-
if (
|
|
614
|
-
/^(?:font-family|font-weight|z-index)$/.test(decl.prop) &&
|
|
615
|
-
!/^(?:var\(|inherit$|initial$|unset$|revert(?:-layer)?$|auto$)/.test(decl.value) &&
|
|
616
|
-
!(foundation && decl.prop === "font-weight" && /^(?:bolder|lighter)$/.test(decl.value))
|
|
617
|
-
)
|
|
618
|
-
violations.add("Use a semantic typography or layering token.");
|
|
578
|
+
const violations = styleTokenViolations(decl, { review: isReviewFile(file, options), foundation });
|
|
619
579
|
for (const message of violations) report(file, "style-token", message, offset.line + decl.source.start.line - 1, decl.source.start.column);
|
|
620
580
|
});
|
|
621
581
|
}
|
package/dist/cli.mjs
CHANGED
|
@@ -30,7 +30,7 @@ Usage: ads init [options] Run inside your project
|
|
|
30
30
|
assets [directory] Generate configured brand assets, glyphs, themes.generated.css and .ts,
|
|
31
31
|
the styles entry, and the public/review barrels from .ads.exports.ts files
|
|
32
32
|
mcp [directory] Serve stdio MCP tools/Apps and the local showcase website
|
|
33
|
-
showcase [directory] Serve the built-in
|
|
33
|
+
showcase [directory] Serve the built-in HTTP showcase (no stdio connection)
|
|
34
34
|
|
|
35
35
|
--help Show this help
|
|
36
36
|
--version Show the tool version
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import path from "node:path";
|
|
2
2
|
import { location } from "./analysis/helpers.mjs";
|
|
3
|
+
import { createContrastStyles } from "./contrast-styles.mjs";
|
|
3
4
|
import { renderComposition } from "./render-composition.mjs";
|
|
4
5
|
|
|
5
|
-
const properties = new Set(["color", "background", "background-color", "background-image", "font", "font-size", "font-weight", "opacity", "filter", "backdrop-filter", "mix-blend-mode", "transform", "text-shadow", "position", "display", "visibility", "all"]);
|
|
6
6
|
const initialText = new Set(["a", "button", "input", "select", "textarea", "option"]);
|
|
7
7
|
const initialFont = new Set(["button", "input", "select", "textarea", "option"]);
|
|
8
8
|
const nativeFill = new Set(["button", "input", "select", "textarea", "option", "progress", "meter"]);
|
|
@@ -15,70 +15,16 @@ const isAbsent = value => value?.kind === "literal" && value.value == null;
|
|
|
15
15
|
/** Bind already-parsed CSS to captured render facts. This is deliberately a
|
|
16
16
|
* proof of simple owned cascades, not a replacement for browser CSS evaluation. */
|
|
17
17
|
export function createContrastComposition(program, options, contrast) {
|
|
18
|
-
const
|
|
19
|
-
let hasColor = false, externalStyles = false;
|
|
18
|
+
const styles = createContrastStyles();
|
|
20
19
|
const relative = node => ({ ...location(node), file: path.relative(options.root, node.getSourceFile().fileName).replaceAll("\\", "/") });
|
|
21
|
-
function record(template, css, file, offset) {
|
|
22
|
-
const entries = new Map();
|
|
23
|
-
let reason;
|
|
24
|
-
css.walkDecls(decl => {
|
|
25
|
-
const prop = decl.prop.startsWith("--") ? decl.prop : decl.prop.toLowerCase();
|
|
26
|
-
if (!properties.has(prop) && !prop.startsWith("--")) return;
|
|
27
|
-
if (prop === "color") hasColor = true;
|
|
28
|
-
// Keyframes and @property describe other contexts, not the base element.
|
|
29
|
-
for (let parent = decl.parent; parent && parent.type !== "root"; parent = parent.parent) {
|
|
30
|
-
if (parent.type === "atrule" && /^(?:property|(?:-\w+-)?keyframes)$/.test(parent.name)) return;
|
|
31
|
-
if (parent.type === "rule" && parent.selector.trim() !== "&" || parent.type === "atrule") {
|
|
32
|
-
reason = "Conditional or descendant paint selectors need the rendered cascade.";
|
|
33
|
-
return;
|
|
34
|
-
}
|
|
35
|
-
}
|
|
36
|
-
const at = { file, line: offset.line + decl.source.start.line - 1, column: decl.source.start.column + (decl.source.start.line === 1 ? offset.column - 1 : 0) };
|
|
37
|
-
const entry = { value: decl.value, prop, important: !!decl.important, at, decl, template };
|
|
38
|
-
const old = entries.get(prop);
|
|
39
|
-
if (!old?.important || entry.important) entries.set(prop, entry);
|
|
40
|
-
if (prop === "background" && (!entries.get("background-color")?.important || entry.important)) entries.delete("background-color");
|
|
41
|
-
if (prop === "background-color" && entries.get("background")?.important && !entry.important) entries.delete("background-color");
|
|
42
|
-
});
|
|
43
|
-
if (!template) { externalStyles ||= !!entries.size || !!reason; return; }
|
|
44
|
-
const fact = { entries, reason };
|
|
45
|
-
const signature = JSON.stringify([[...entries].map(([name, entry]) => [name, entry.value, entry.important]), reason]);
|
|
46
|
-
const variants = templates.get(template) ?? new Map();
|
|
47
|
-
variants.set(signature, fact);
|
|
48
|
-
templates.set(template, variants);
|
|
49
|
-
}
|
|
50
|
-
function style(item) {
|
|
51
|
-
const entries = new Map();
|
|
52
|
-
let reason = item.classes.reason ?? (item.classes.names.length ? "Named classes outside captured style templates need the rendered cascade." : undefined);
|
|
53
|
-
for (const template of item.classes.templates) {
|
|
54
|
-
const variants = templates.get(template);
|
|
55
|
-
if (!variants) { reason ??= "A style template has no complete captured paint facts."; continue; }
|
|
56
|
-
if (variants.size !== 1) {
|
|
57
|
-
reason ??= "Interpolated paint alternatives do not establish one definite cascade.";
|
|
58
|
-
continue;
|
|
59
|
-
}
|
|
60
|
-
const fact = variants.values().next().value;
|
|
61
|
-
reason ??= fact.reason;
|
|
62
|
-
for (const [name, entry] of fact.entries) {
|
|
63
|
-
const old = entries.get(name);
|
|
64
|
-
// Class order alone does not prove stylesheet order (including core css
|
|
65
|
-
// classes and shorthand/longhand conflicts). Do not guess a winner.
|
|
66
|
-
if (old && old.value !== entry.value) reason ??= "Composed classes set competing paint declarations.";
|
|
67
|
-
if (name === "background" && entries.has("background-color") || name === "background-color" && entries.has("background"))
|
|
68
|
-
reason ??= "Composed background shorthand and longhand declarations need the rendered cascade.";
|
|
69
|
-
entries.set(name, entry);
|
|
70
|
-
}
|
|
71
|
-
}
|
|
72
|
-
return { entries, reason };
|
|
73
|
-
}
|
|
74
20
|
async function check() {
|
|
75
|
-
if (!hasColor) return;
|
|
21
|
+
if (!styles.hasColor) return;
|
|
76
22
|
const graph = await renderComposition(program, options);
|
|
77
23
|
const memo = new Map();
|
|
78
24
|
function effective(item) {
|
|
79
25
|
if (memo.has(item)) return memo.get(item);
|
|
80
26
|
const parent = item.parent && effective(item.parent);
|
|
81
|
-
const own =
|
|
27
|
+
const own = styles.get(item.classes), entries = own.entries;
|
|
82
28
|
const state = {
|
|
83
29
|
foreground: initialText.has(item.tag) ? undefined : parent?.foreground,
|
|
84
30
|
backgrounds: [...(parent?.backgrounds ?? [])],
|
|
@@ -113,7 +59,7 @@ export function createContrastComposition(program, options, contrast) {
|
|
|
113
59
|
if (entries.has("all") || ["absolute", "fixed"].includes(entries.get("position")?.value.toLowerCase())) state.reason ??= "A reset or out-of-flow position prevents establishing the backdrop.";
|
|
114
60
|
if (["hidden", "disabled", "aria-disabled"].some(name => item.attributes[name]?.kind !== "literal")) state.reason ??= "Dynamic visibility or disabled state needs a rendered check.";
|
|
115
61
|
if (!isAbsent(item.attributes.style)) state.reason ??= "Inline styles may override the composed paint.";
|
|
116
|
-
if (externalStyles) state.reason ??= "Additional authored CSS needs the rendered selector cascade.";
|
|
62
|
+
if (styles.externalStyles) state.reason ??= "Additional authored CSS needs the rendered selector cascade.";
|
|
117
63
|
return state;
|
|
118
64
|
}
|
|
119
65
|
for (const item of graph.nodes) {
|
|
@@ -130,5 +76,5 @@ export function createContrastComposition(program, options, contrast) {
|
|
|
130
76
|
}
|
|
131
77
|
for (const item of graph.limits) if (item.node) contrast.incomplete(relative(item.node), item.reason);
|
|
132
78
|
}
|
|
133
|
-
return { record, check };
|
|
79
|
+
return { record: styles.record, check };
|
|
134
80
|
}
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import selectorParser from "postcss-selector-parser";
|
|
2
|
+
|
|
3
|
+
const properties = new Set(["color", "background", "background-color", "background-image", "font", "font-size", "font-weight", "opacity", "filter", "backdrop-filter", "mix-blend-mode", "transform", "text-shadow", "position", "display", "visibility", "all"]);
|
|
4
|
+
const signature = fact => JSON.stringify([[...fact.entries].map(([name, entry]) => [name, entry.value, entry.important]).sort(([a], [b]) => a.localeCompare(b)), fact.reason]);
|
|
5
|
+
|
|
6
|
+
/** Check-owned paint facts from the already captured/parsed CSS. Class choices
|
|
7
|
+
* stay factored: comparing each choice avoids exponential class combinations. */
|
|
8
|
+
export function createContrastStyles() {
|
|
9
|
+
const templates = new Map(), targetedHooks = new Set(), selectors = new WeakSet(), memo = new WeakMap();
|
|
10
|
+
let hasColor = false, externalStyles = false, unknownTargets = false;
|
|
11
|
+
function targets(rule) {
|
|
12
|
+
if (selectors.has(rule)) return;
|
|
13
|
+
selectors.add(rule);
|
|
14
|
+
try {
|
|
15
|
+
if (rule.selector.length > 4096) { unknownTargets = true; return; }
|
|
16
|
+
const ast = selectorParser().astSync(rule.selector);
|
|
17
|
+
for (const branch of ast.nodes) {
|
|
18
|
+
const subject = branch.nodes.slice(branch.nodes.findLastIndex(node => node.type === "combinator") + 1);
|
|
19
|
+
// `.card:hover &` styles the attached template, not the card hook.
|
|
20
|
+
// Its uncertainty is already retained on that template's own fact.
|
|
21
|
+
if (subject.some(node => node.type === "nesting")) continue;
|
|
22
|
+
branch.walkClasses(node => targetedHooks.add(node.value));
|
|
23
|
+
}
|
|
24
|
+
} catch { unknownTargets = true; }
|
|
25
|
+
}
|
|
26
|
+
function record(template, css, file, offset) {
|
|
27
|
+
const entries = new Map();
|
|
28
|
+
let reason;
|
|
29
|
+
css.walkDecls(decl => {
|
|
30
|
+
const prop = decl.prop.startsWith("--") ? decl.prop : decl.prop.toLowerCase();
|
|
31
|
+
if (!properties.has(prop) && !prop.startsWith("--")) return;
|
|
32
|
+
const parents = [];
|
|
33
|
+
for (let parent = decl.parent; parent && parent.type !== "root"; parent = parent.parent) parents.push(parent);
|
|
34
|
+
if (parents.some(parent => parent.type === "atrule" && /^(?:property|(?:-\w+-)?keyframes)$/.test(parent.name))) return;
|
|
35
|
+
if (prop === "color") hasColor = true;
|
|
36
|
+
let conditional = false;
|
|
37
|
+
for (const parent of parents) {
|
|
38
|
+
if (parent.type === "rule" && parent.selector.trim() !== "&") { targets(parent); conditional = true; }
|
|
39
|
+
if (parent.type === "atrule") conditional = true;
|
|
40
|
+
}
|
|
41
|
+
if (conditional) { reason = `Conditional or descendant ${prop} at ${file}:${offset.line + decl.source.start.line - 1} needs the rendered cascade.`; return; }
|
|
42
|
+
const at = { file, line: offset.line + decl.source.start.line - 1, column: decl.source.start.column + (decl.source.start.line === 1 ? offset.column - 1 : 0) };
|
|
43
|
+
const entry = { value: decl.value, prop, important: !!decl.important, at, decl, template };
|
|
44
|
+
const old = entries.get(prop);
|
|
45
|
+
if (!old?.important || entry.important) entries.set(prop, entry);
|
|
46
|
+
if (prop === "background" && (!entries.get("background-color")?.important || entry.important)) entries.delete("background-color");
|
|
47
|
+
if (prop === "background-color" && entries.get("background")?.important && !entry.important) entries.delete("background-color");
|
|
48
|
+
});
|
|
49
|
+
if (!template) { externalStyles ||= !!entries.size || !!reason; return; }
|
|
50
|
+
const fact = { entries, reason }, variants = templates.get(template) ?? new Map();
|
|
51
|
+
variants.set(signature(fact), fact);
|
|
52
|
+
templates.set(template, variants);
|
|
53
|
+
}
|
|
54
|
+
function get(classes) {
|
|
55
|
+
if (memo.has(classes)) return memo.get(classes);
|
|
56
|
+
const entries = new Map();
|
|
57
|
+
let reason = classes.reason ?? (classes.names.some(name => unknownTargets || targetedHooks.has(name)) ? "A named class may be targeted by captured paint selectors." : undefined);
|
|
58
|
+
function merge(fact) {
|
|
59
|
+
reason ??= fact.reason;
|
|
60
|
+
for (const [name, entry] of fact.entries) {
|
|
61
|
+
const old = entries.get(name);
|
|
62
|
+
// Class order does not establish stylesheet order, even across choices.
|
|
63
|
+
if (old && old.value !== entry.value) reason ??= "Composed classes set competing paint declarations.";
|
|
64
|
+
if (name === "background" && entries.has("background-color") || name === "background-color" && entries.has("background"))
|
|
65
|
+
reason ??= "Composed background shorthand and longhand declarations need the rendered cascade.";
|
|
66
|
+
entries.set(name, entry);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
for (const template of classes.templates) {
|
|
70
|
+
const variants = templates.get(template);
|
|
71
|
+
if (!variants) { reason ??= "A style template has no complete captured paint facts."; continue; }
|
|
72
|
+
if (variants.size !== 1) { reason ??= "Interpolated paint alternatives do not establish one definite cascade."; continue; }
|
|
73
|
+
merge(variants.values().next().value);
|
|
74
|
+
}
|
|
75
|
+
for (const choice of classes.choices ?? []) {
|
|
76
|
+
const alternatives = choice.map(get), first = alternatives[0];
|
|
77
|
+
if (!first || alternatives.some(fact => fact.reason || signature(fact) !== signature(first))) {
|
|
78
|
+
reason ??= "Class alternatives do not establish identical paint and visibility.";
|
|
79
|
+
continue;
|
|
80
|
+
}
|
|
81
|
+
merge(first);
|
|
82
|
+
}
|
|
83
|
+
const fact = { entries, reason };
|
|
84
|
+
memo.set(classes, fact);
|
|
85
|
+
return fact;
|
|
86
|
+
}
|
|
87
|
+
return { record, get, get hasColor() { return hasColor; }, get externalStyles() { return externalStyles; } };
|
|
88
|
+
}
|
package/dist/mcp/apps.mjs
CHANGED
|
@@ -10,7 +10,13 @@ const safeJson = (value) => JSON.stringify(value).replaceAll("<", "\\u003c");
|
|
|
10
10
|
|
|
11
11
|
export function previewApp(selection) {
|
|
12
12
|
const script = readFileSync(new URL("./preview-widget.bundle.js", import.meta.url), "utf8").replaceAll("</script", "<\\/script");
|
|
13
|
-
return
|
|
13
|
+
return previewDocument(`<script type="module">${script}</script>`, selection);
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** The same frame document/framing for MCP Apps and local HTTP previews. */
|
|
17
|
+
export function previewDocument(scriptTag, selection) {
|
|
18
|
+
const seed = selection ? `<script type="application/json" id="ads-preview-selection">${safeJson(selection)}</script>` : "";
|
|
19
|
+
return `<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>ADS preview</title><style>html,body,#root{height:100%;margin:0}body{overflow:auto}#ads-preview-status{position:fixed;inset:12px 12px auto;z-index:2147483647;padding:12px;border:1px solid GrayText;background:Canvas;color:CanvasText;font:13px system-ui;white-space:pre-wrap}#ads-preview-status[hidden]{display:none}</style></head><body><aside id="ads-preview-status" role="status" hidden></aside><div id="root"></div>${seed}${scriptTag}</body></html>`;
|
|
14
20
|
}
|
|
15
21
|
|
|
16
22
|
export function tokenWidgetData(inventory) {
|
|
@@ -267,9 +267,12 @@ export async function inspectBuildStatus(root, config, { session, previewSession
|
|
|
267
267
|
if (session && report.session !== session) report = undefined;
|
|
268
268
|
}
|
|
269
269
|
} catch (error) {
|
|
270
|
-
|
|
270
|
+
// A watcher restart can remove its report between exists/realpath/read.
|
|
271
|
+
// Absence is pending evidence, just as when existsSync returned false;
|
|
272
|
+
// malformed or unsafe reports still fail closed.
|
|
273
|
+
if (error.code !== "ENOENT") reportError = `Invalid preview build status: ${error.message.slice(0, 500)}`;
|
|
271
274
|
}
|
|
272
|
-
let graphError;
|
|
275
|
+
let graphError, verifiedGraph;
|
|
273
276
|
let sourceRevision, sourceError;
|
|
274
277
|
if (report?.live || report?.previews.some((entry) => entry.state === "ready")) {
|
|
275
278
|
try {
|
|
@@ -290,7 +293,8 @@ export async function inspectBuildStatus(root, config, { session, previewSession
|
|
|
290
293
|
}
|
|
291
294
|
if (report?.previews.some((entry) => entry.state === "ready")) {
|
|
292
295
|
try {
|
|
293
|
-
|
|
296
|
+
verifiedGraph = readPreviewManifest(options, { verify: "cached" });
|
|
297
|
+
if (!verifiedGraph) throw new Error("Preview resource manifest is missing.");
|
|
294
298
|
} catch (error) {
|
|
295
299
|
graphError = `Invalid preview resource graph: ${error.message}`;
|
|
296
300
|
}
|
|
@@ -372,6 +376,7 @@ export async function inspectBuildStatus(root, config, { session, previewSession
|
|
|
372
376
|
state,
|
|
373
377
|
reported: Boolean(report),
|
|
374
378
|
session: report?.session ?? null,
|
|
379
|
+
...(verifiedGraph && !graphError && verifiedGraph.session === report?.session ? { manifestRevision: verifiedGraph.revision } : {}),
|
|
375
380
|
sequence: report?.sequence ?? null,
|
|
376
381
|
updatedAt: report?.updatedAt ?? null,
|
|
377
382
|
...(report?.progress ? { progress: report.progress } : {}),
|
package/dist/mcp/drafts.mjs
CHANGED
|
@@ -1049,7 +1049,12 @@ export function createDraftController(directory, { edits, startPreview, prewarm
|
|
|
1049
1049
|
async function syncPreviews() {
|
|
1050
1050
|
const order = [...previews.keys()].sort((a, b) => (b === lastShown) - (a === lastShown));
|
|
1051
1051
|
for (const id of order) {
|
|
1052
|
-
|
|
1052
|
+
// Earlier resyncs yield; acceptance, drop or shutdown can retire a later
|
|
1053
|
+
// session while this iteration still holds its original ID list.
|
|
1054
|
+
if (closed) break;
|
|
1055
|
+
const session = previews.get(id);
|
|
1056
|
+
if (!session) continue;
|
|
1057
|
+
const reason = stale(id, session);
|
|
1053
1058
|
if (!reason) continue;
|
|
1054
1059
|
if (reason === "own" || id === lastShown) {
|
|
1055
1060
|
backlog.delete(id);
|
|
@@ -1202,6 +1207,13 @@ export function createDraftController(directory, { edits, startPreview, prewarm
|
|
|
1202
1207
|
await session.starting;
|
|
1203
1208
|
return session.runtime.readResource(uri, signal);
|
|
1204
1209
|
},
|
|
1210
|
+
async capturePreview(id, uri, signal) {
|
|
1211
|
+
const session = previews.get(id);
|
|
1212
|
+
if (session?.error) throw new Error(`Draft preview is stale: ${session.error}`);
|
|
1213
|
+
if (!session?.starting) throw new Error("Draft preview is not active. Reopen ads_show_draft.");
|
|
1214
|
+
await session.starting;
|
|
1215
|
+
return session.runtime.capturePreview(uri, signal);
|
|
1216
|
+
},
|
|
1205
1217
|
fingerprint: () => `${draftStamp()}:${discoveryVersion}`,
|
|
1206
1218
|
async close() {
|
|
1207
1219
|
closed = true;
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
function Pe(){let e=new Map,s=new Set,r=!1,t;function n(i){let u={data:e.get(i)?.data??{},callbacks:[],listeners:new Map};return e.set(i,u),{data:u.data,accept(d,m){if(!d||typeof d==="function")u.callbacks.push({deps:[i],callback:(a)=>d?.(a[0])});else u.callbacks.push({deps:typeof d==="string"?[d]:d,callback:(a)=>m?.(typeof d==="string"?a[0]:a)})},acceptExports(d,m){u.callbacks.push({deps:[i],callback:(a)=>m?.(a[0])})},dispose(d){u.dispose=d},prune(d){u.prune=d},invalidate(){r=!0},decline(){r=!0},on(d,m){let a=u.listeners.get(d)??new Set;a.add(m),u.listeners.set(d,a)},off(d,m){u.listeners.get(d)?.delete(m)},send(){throw Error("Preview hot-update custom messages are not a public transport.")}}}async function o(i){for(let c of e.values())for(let u of c.listeners.get(i)??[])await u()}return{context:n,observe(i,c,u){let d=e.get(i);if(!d)return;let m=import(c).then((a)=>{d.exports=a,d.isComponent=u});s.add(m),m.then(()=>s.delete(m),(a)=>{s.delete(m),t=a})},async update(i,c,u,d){if(await Promise.all(s),t)throw t;let m=new Map([...i].filter(([,l])=>l.hot).map(([l,f])=>[f.hot.id,{uri:l,record:f}])),a=new Map([...c].filter(([,l])=>l.hot).map(([l,f])=>[f.hot.id,{uri:l,record:f}])),w=new Map,h=new Map;for(let[l,{record:f}]of m)for(let v of[...f.imports,...f.dynamicImports]){let S=i.get(v)?.hot?.id;if(!S)continue;let E=w.get(S)??new Set;E.add(l),w.set(S,E)}function b(l,f=new Set){if(f.has(l))return!1;let v=e.get(l);if(v?.callbacks.some((R)=>R.deps.includes(l))&&a.has(l))return h.set(l,v),!0;let S=w.get(l);if(!S?.size)return!1;let E=new Set([...f,l]);for(let R of S)if(!b(R,E))return!1;return!0}for(let[l,{record:f}]of m){let v=a.get(l)?.record;if(!v||f.hot.source!==v.hot.source){if(!b(l))return!1}}if(!h.size)return!0;r=!1,await o("vite:beforeUpdate");let y=[];for(let[l,f]of h){if(!d())return!1;await f.dispose?.(f.data),y.push([l,f,await u(a.get(l).uri)])}if(!d())return!1;for(let[,l,f]of y)if(l.isComponent){let v=l.exports,S=Object.keys(f).filter((E)=>E!=="__esModule");if(!v||S.length!==Object.keys(v).filter((E)=>E!=="__esModule").length||S.some((E)=>!Object.hasOwn(v,E)||!l.isComponent(f[E])&&v[E]!==f[E]))return!1}for(let[l,f,v]of y)for(let S of f.callbacks)if(S.deps.includes(l))await S.callback(S.deps.map((E)=>E===l?v:void 0));return await o("vite:afterUpdate"),await new Promise((l)=>setTimeout(l,20)),d()&&!r},async dispose(){for(let i of e.values())await i.dispose?.(i.data),await i.prune?.(i.data);e.clear(),s.clear(),t=void 0}}}async function Se(e,s){let r=await crypto.subtle.digest("SHA-256",s),t="sha256:"+[...new Uint8Array(r)].map((n)=>n.toString(16).padStart(2,"0")).join("");if(s.length!==e.size||t!==e.digest)throw Object.assign(Error("Preview resource integrity check failed. Rebuild and reopen the preview."),{code:"ADS_RESOURCE_INTEGRITY",category:"build"});return s}function Re(e,s){let r=[],t=new Set;function n(o){if(t.has(o))return;t.add(o);let i=e.get(o);if(!i)throw Error(`Missing preview dependency metadata: ${o}`);for(let c of[...i.imports,...i.styles,...i.references])n(c);r.push(o)}return n(s),r}function Oe(e,s){if(!e||e.revision===s.revision)return[];let r=(t,n)=>{let o=new Map(Object.entries(t.assets));return JSON.stringify(Re(o,n.module).map((i)=>[i,o.get(i)]))};return s.scenarios.filter((t)=>{let n=e.scenarios.find((o)=>o.id===t.id);return!n||r(e,n)!==r(s,t)}).map((t)=>t.id)}class me{constructor(e){this.read=e,this.records=new Map,this.bytes=new Map,this.urls=new Map,this.styles=new Map,this.styleReady=new Map,this.revisions=new Set,this.loadedModules=new Set,this.executed=new Map,this.moduleHistory=new Set,this.importing=Promise.resolve(),this.mounting=Promise.resolve(),this.refreshDirty=!1,this.generation=0,this.prefetchGeneration=0,this.closed=!1,this.hot=Pe(),globalThis.__adsPreviewHot=this.hot,globalThis.__dsPreviewImport=(s)=>this.importModule(s)}register(e){if(e.schemaVersion!==1||!Array.isArray(e.scenarios)||!e.assets||typeof e.revision!=="string")throw Error("Unsupported preview manifest. Rebuild previews with the installed ADS version.");if(e.refresh&&(e.refresh.version!==1||typeof e.refresh.epoch!=="string"||!e.refresh.epoch||e.refresh.epoch.length>100))throw Error("Unsupported preview refresh protocol. Reopen with the current ADS version.");let s=new Set;for(let[r,t]of Object.entries(e.assets)){if(!/^ads:\/\/assets\/[a-f0-9]{64}\.[a-z0-9]+$/.test(r)||!/^sha256:[a-f0-9]{64}$/.test(t.digest)||t.hot&&(!e.refresh||t.kind!=="module"||typeof t.hot.id!=="string"||!t.hot.id||t.hot.id.length>4096||s.has(t.hot.id)||!/^[a-f0-9]{64}$/.test(t.hot.source))||!["imports","dynamicImports","styles","references"].every((n)=>Array.isArray(t[n])&&t[n].every((o)=>Object.hasOwn(e.assets,o))))throw Error("Invalid preview dependency graph.");if(t.hot)s.add(t.hot.id);if(this.records.has(r)&&this.records.get(r).digest!==t.digest)throw Object.assign(Error("An immutable preview resource changed its content. Rebuild previews with the current ADS version."),{code:"ADS_RESOURCE_IDENTITY",category:"build",resourceUri:r})}for(let[r,t]of Object.entries(e.assets))this.records.set(r,t)}async resource(e){if(!this.bytes.has(e)){let s=(async()=>{let r=this.records.get(e);if(!r)throw Error(`Unknown preview dependency: ${e}`);let t;try{t=await this.read(e)}catch(i){throw Object.assign(Error(`Preview resource read failed for ${e}: ${i.message}`,{cause:i}),{code:"ADS_RESOURCE_READ",category:"transport",resourceUri:e})}if(this.closed)throw Error("The preview App was closed.");let n=t.contents.find((i)=>i.uri===e);if(!n)throw Object.assign(Error(`Missing preview dependency: ${e}`),{code:"ADS_RESOURCE_CONTENT",category:"build",resourceUri:e});let o=typeof n.text==="string"?new TextEncoder().encode(n.text):Uint8Array.from(atob(n.blob),(i)=>i.charCodeAt(0));try{return await Se(r,o)}catch(i){throw i.resourceUri=e,i}})();this.bytes.set(e,s),s.catch(()=>this.bytes.delete(e))}return this.bytes.get(e)}closure(e){return Re(this.records,e)}async prefetch(e,s){if(this.closed)return;this.register(e);let r=++this.prefetchGeneration,t=new Set,n=[],o=0;for(let d of s){let m=e.scenarios.find((h)=>h.id===d);if(!m)continue;let a=this.closure(m.module).filter((h)=>!this.bytes.has(h)&&!t.has(h)),w=a.reduce((h,b)=>h+this.records.get(b).size,0);if(o+w>16777216||t.size+a.length>256)continue;o+=w,n.push(d);for(let h of a)t.add(h)}let i=[...t],c=0,u=async()=>{while(!this.closed&&r===this.prefetchGeneration&&c<i.length)await this.resource(i[c++])};return await Promise.all(Array.from({length:Math.min(3,i.length)},u)),{scenarios:n,resources:i.length}}async materialize(e){let s=this.closure(e);await Promise.all(s.map((t)=>this.resource(t)));let r={};for(let t of s){if(this.closed)throw Error("The preview App was closed.");if(this.urls.has(t))continue;let n=this.records.get(t),o=await this.resource(t);if(n.kind==="module"||n.mimeType==="text/css"||n.mimeType==="text/javascript"){let c=new TextDecoder().decode(o);for(let u of n.references){let d=this.urls.get(u);if(!d)throw Error("Unsupported cyclic asset reference.");c=c.replaceAll(u,d)}o=c}let i=URL.createObjectURL(new Blob([o],{type:n.mimeType}));if(this.urls.set(t,i),n.kind==="module")r[t]=i}if(Object.keys(r).length){let t=document.createElement("script");t.type="importmap",t.textContent=JSON.stringify({imports:r}),document.head.append(t)}return s}async importModule(e){let s=this.importing.then(()=>this.materialize(e));this.importing=s.catch(()=>{});let r=await s;await this.attachStyles(r);try{let t=await import(e);this.loadedModules.add(e);for(let n of r){let o=this.records.get(n);if(o.hot)this.executed.set(o.hot.id,{uri:n,record:o}),this.moduleHistory.add(n)}return t}catch(t){throw Error(`Preview module import failed for ${e}: ${t.message}. Inspect the App resource bridge, browser network/CSP diagnostics and current build.`,{cause:t})}}async attachStyles(e){for(let s of e){if(this.records.get(s).mimeType!=="text/css")continue;if(this.styles.has(s)){await this.styleReady.get(s);continue}let t=document.createElement("link");t.rel="stylesheet",t.href=this.urls.get(s),this.styles.set(s,t);let n=new Promise((o,i)=>{t.onload=o,t.onerror=()=>i(Error("The host CSP blocked a preview stylesheet."))});this.styleReady.set(s,n),document.head.append(t);try{await n}catch(o){throw t.remove(),this.styles.delete(s),this.styleReady.delete(s),o}}}async refreshStyles(e,s){let r=[e],t=new Set,n=new Set;for(let o=0;o<r.length;o++){let i=r[o];if(t.has(i))continue;t.add(i);for(let c of await this.materialize(i)){n.add(c);for(let u of this.records.get(c).dynamicImports)if(this.loadedModules.has(u)||this.executed.has(this.records.get(u)?.hot?.id))r.push(u)}}if(await this.attachStyles([...n]),s!==this.generation||this.closed)return!1;for(let[o,i]of this.styles)if(!n.has(o))i.remove(),this.styles.delete(o),this.styleReady.delete(o);for(let o of n)if(this.styles.has(o))document.head.append(this.styles.get(o));return!0}async mount(e,s,r){let t=++this.generation,n=this.mounting.then(()=>t!==this.generation||this.closed?!1:this.mountRevision(e,s,r,t));return this.mounting=n.catch(()=>{}),n}async mountRevision(e,s,r,t){this.register(e);let n=e.scenarios.find((a)=>a.id===s);if(!n)throw Error("The selected scenario is no longer registered.");let o=JSON.stringify(this.closure(n.module).map((a)=>[a,this.records.get(a)])),i=new Map(this.closure(n.module).map((a)=>[a,this.records.get(a)])),c=(a)=>{throw Object.assign(Error(a),{code:"ADS_PREVIEW_REOPEN"})};if(this.refreshDirty)c("An interrupted module update requires a clean preview frame.");let u=[...this.urls.keys()].reduce((a,w)=>a+this.records.get(w).size,0);if(this.records.size>4096||u>67108864)c("Reopen the preview to release retained module revisions.");if(this.mounted&&this.mounted.refresh?.epoch!==e.refresh?.epoch)c("The preview compiler changed. Reopening an isolated frame for its new runtime.");if(e.refresh&&this.mounted){let a=new Map(Object.entries(e.assets)),w=new Map([...a].filter(([,y])=>y.hot).map(([y,l])=>[l.hot.id,{uri:y,record:l}]));for(let[y,{record:l}]of this.executed){let f=w.get(y);if(f&&f.record.hot.source!==l.hot.source&&this.moduleHistory.has(f.uri))c("Restoring a previous module revision requires a clean preview frame.")}let h=new Map([...this.executed.values()].map(({uri:y,record:l})=>[y,l]));this.refreshDirty=!0;let b=await this.hot.update(h,a,(y)=>this.importModule(y),()=>t===this.generation&&!this.closed);if(t!==this.generation||this.closed)return!1;if(!b)c("This edit changes a refresh boundary. Reopening the preview with fresh component state.");this.refreshDirty=!1;for(let y of this.executed.keys())if(w.has(y))this.executed.set(y,w.get(y));if(this.mounted.id===s){if(!await this.refreshStyles(n.module,t))return!1;return this.revisions.add(n.module),this.mounted={...this.mounted,signature:o,records:i,module:n.module},!0}}if(this.mounted?.id===s&&this.mounted.container===r&&this.mounted.signature===o)return this.refreshStyles(n.module,t);if(this.revisions.add(n.module),!e.refresh&&this.revisions.size>20)throw Object.assign(Error("Reopen the preview to release retained module revisions."),{code:"ADS_PREVIEW_REOPEN"});let d=await this.importModule(n.module);if(t!==this.generation)return!1;let m=this.unmount;if(this.unmount=void 0,this.mounted=void 0,await m?.(),t!==this.generation||this.closed)return!1;if(r.replaceChildren(),!await this.refreshStyles(n.module,t))return!1;if(typeof d.mount!=="function")throw Error("The compiled scenario has no mount adapter.");if(this.unmount=d.mount(r),typeof this.unmount!=="function")throw Error("The scenario mount adapter must return an unmount callback.");return this.mounted={id:s,container:r,signature:o,records:i,module:n.module,refresh:e.refresh},!0}async dispose(){if(this.closed)return;this.closed=!0,++this.generation,++this.prefetchGeneration,await this.mounting,await this.unmount?.(),await this.hot.dispose(),this.mounted=void 0;for(let e of this.styles.values())e.remove();for(let e of this.urls.values())URL.revokeObjectURL(e);if(this.styles.clear(),this.styleReady.clear(),this.urls.clear(),this.bytes.clear(),this.records.clear(),this.revisions.clear(),this.loadedModules.clear(),this.executed.clear(),this.moduleHistory.clear(),delete globalThis.__dsPreviewImport,globalThis.__adsPreviewHot===this.hot)delete globalThis.__adsPreviewHot}}var Ee="ads-preview-guide-options",Ce="ads-preview-guide-state",Ye=["off","hover","always"],Ke=["bounds","tracks","gaps","padding","margins","mini"],nt=Object.freeze({mode:"off",bounds:!0,tracks:!1,gaps:!1,padding:!0,margins:!0,mini:!1});function ge(e){return{mode:Ye.includes(e?.mode)?e.mode:e?.all===!0?"always":"off",...Object.fromEntries(Ke.map((r)=>[r,e?.[r]===!0]))}}function Me(e){let{mode:s,...r}=ge(e);return{all:s==="always",...r}}function Te(e){let{mode:s,...r}=ge(e);return s!=="off"&&Object.values(r).some(Boolean)}function $e(e,{onDetails:s=()=>{}}={}){let r=e.ownerDocument,t=r.defaultView,n=(P)=>parseFloat(P)||0,o,i,c="",u,d=!1,m=[],a="components",w,h={},b=new Set,y=new t.ResizeObserver(f),l=new t.MutationObserver(f);function f(){if(d&&!i)i=t.requestAnimationFrame(_)}function v(P){let B=P.target,H=B?.closest?.("[data-ads-source]"),N=B?.closest?.('button, summary, a[href], [role="button"]'),D=H&&e.contains(H)?N&&e.contains(N)?N:B:null;if(w!==D)w=D,f()}function S(){if(w)w=null,f()}function E(P){if(!e.contains(P.relatedTarget))S(P)}function R(P){let B=P.closest("[data-ads-source]")?.dataset.adsSource;return m.filter((H)=>H.schemaVersion===1&&H.source===B).flatMap((H)=>H.rules.filter((N)=>{try{return P.matches(N.selector)}catch{return!1}}).flatMap((N)=>N.declarations))}function U(){let P=[...e.querySelectorAll("[data-ads-source]")].filter((B)=>{let H=B.getBoundingClientRect();return H.width&&H.height});if(P.length)return P;return[...(e.querySelector(".ads-preview-root")??e).children].filter((B)=>!["STYLE","SCRIPT","LINK","H1"].includes(B.tagName))}let F=()=>({width:r.documentElement.clientWidth,height:r.documentElement.clientHeight});function T(P){let{width:B,height:H}=F(),N={left:0,top:0,right:B,bottom:H};for(let D=P.parentElement;D;D=D.parentElement){let de=t.getComputedStyle(D),ne=D.getBoundingClientRect(),ue=D.offsetWidth?ne.width/D.offsetWidth:1,A=D.offsetHeight?ne.height/D.offsetHeight:1;if(/(auto|scroll|hidden|clip)/.test(de.overflowX))N.left=Math.max(N.left,ne.left+D.clientLeft*ue),N.right=Math.min(N.right,ne.left+(D.clientLeft+D.clientWidth)*ue);if(/(auto|scroll|hidden|clip)/.test(de.overflowY))N.top=Math.max(N.top,ne.top+D.clientTop*A),N.bottom=Math.min(N.bottom,ne.top+(D.clientTop+D.clientHeight)*A)}return N}function _(){if(i=void 0,!d)return;let P=U();if(w&&!e.contains(w))w=null;let B=h.all===!0?[...P]:w?[w]:[];if(h.all===!0)for(let A of P)for(let I of A.querySelectorAll("*")){if(I.closest("svg")||["STYLE","SCRIPT","LINK"].includes(I.tagName)||B.includes(I))continue;let O=t.getComputedStyle(I);if(/grid|flex/.test(O.display)||["paddingTop","paddingRight","paddingBottom","paddingLeft","marginTop","marginRight","marginBottom","marginLeft"].some((te)=>n(O[te])!==0))B.push(I)}if(w&&!B.includes(w))B.push(w);let H=B.filter((A)=>h.mini===!0||/\/components\//.test(A.closest("[data-ads-source]")?.dataset.adsSource??"")||a==="components"||a==="tokens"),N=new Set(H.filter((A)=>!H.some((I)=>I!==A&&I.contains(A)))),D=[],de=new Set([e]),ne=[];for(let A of B){let Q=function(G,L,p,C,V,q,J=!1){let Y={bounds:"bounds",content:"bounds",column:"tracks",row:"tracks",gap:"gaps",gutter:"gaps",margin:"margins",padding:"padding","mini-unit":"mini"}[V];if(p<=0||C<=0||h[Y]===!1)return;let K=r.createElement("div");return K.dataset.adsGuide=V,Object.assign(K.style,{position:"absolute",left:`${G}px`,top:`${L}px`,width:`${p}px`,height:`${C}px`,boxSizing:"border-box",...J?{border:`1px solid ${q}`}:{background:q}}),fe.append(K),K},X=function(G,L,p,C){let[V,q,J,Y]=G.map((pe,Fe)=>Math.max(0,pe)*(Fe%2?g:x)),K=L?O.left-Y:O.left+k[3]*g,ie=L?O.top-V:O.top+k[0]*x,ae=L?O.width+Y+q:O.width-(k[1]+k[3])*g,ce=L?O.height+V+J:O.height-(k[0]+k[2])*x;Q(K,ie,ae,V,p,C),Q(K,ie+ce-J,ae,J,p,C),Q(K,ie+V,Y,ce-V-J,p,C),Q(K+ae-q,ie+V,q,ce-V-J,p,C)},I=t.getComputedStyle(A),O=A.getBoundingClientRect(),te=T(A);if(!O.width||!O.height||O.right<=te.left||O.left>=te.right||O.bottom<=te.top||O.top>=te.bottom)continue;de.add(A);let g=A.offsetWidth?O.width/A.offsetWidth:1,x=A.offsetHeight?O.height/A.offsetHeight:1,M=["Top","Right","Bottom","Left"],k=M.map((G)=>n(I[`border${G}Width`])),z=M.map((G)=>n(I[`padding${G}`])),le=M.map((G)=>n(I[`margin${G}`])),se=O.left+(k[3]+z[3])*g,oe=O.top+(k[0]+z[0])*x,W=O.width-(k[1]+k[3]+z[1]+z[3])*g,re=O.height-(k[0]+k[2]+z[0]+z[2])*x,fe=r.createElement("div");if(fe.dataset.adsSpatialSource=A.dataset.adsSource??"measured-box",Object.assign(fe.style,{position:"fixed",inset:"0",clipPath:`inset(${te.top}px ${Math.max(0,F().width-te.right)}px ${Math.max(0,F().height-te.bottom)}px ${te.left}px)`}),Q(O.left,O.top,O.width,O.height,"bounds","rgb(70 120 250 / .75)",!0),N.has(A)){let G=I.getPropertyValue("--grid-mini-unit").trim(),L=/^\d*\.?\d+px$/.test(G)?n(G):/^\d*\.?\d+rem$/.test(G)?n(G)*n(t.getComputedStyle(r.documentElement).fontSize):0;if(L>0){let p=t.devicePixelRatio||1,C=Math.floor(O.left*p),V=Math.floor(O.top*p),q=Math.ceil(O.right*p)-C,J=Math.ceil(O.bottom*p)-V,Y=Q(C/p,V/p,q/p,J/p,"mini-unit","transparent");if(Y&&q>0&&J>0){Y.dataset.adsUnit=`${L}`,Y.dataset.adsMajor=`${L*2}`;let K=r.createElement("canvas");K.width=q,K.height=J,Object.assign(K.style,{display:"block",width:`${q/p}px`,height:`${J/p}px`,imageRendering:"pixelated"});let ie=K.getContext("2d");if(ie){let ae=[L*g*p,L*x*p];for(let ce=0;;ce++){let pe=Math.round(O.left*p+ce*ae[0])-C;if(pe>=q)break;ie.fillStyle=ce%2?"#617dba14":"#617dba38",ie.fillRect(pe,0,1,J)}for(let ce=0;;ce++){let pe=Math.round(O.top*p+ce*ae[1])-V;if(pe>=J)break;ie.fillStyle=ce%2?"#617dba14":"#617dba38",ie.fillRect(0,pe,q,1)}}Y.append(K)}}}if(X(le,!0,"margin","rgb(234 149 43 / .2)"),a!=="composition"||w===A||h.padding===!0)X(z,!1,"padding","rgb(55 186 130 / .22)");let Z=R(A);if(I.display.includes("grid")){let G=function(L,p){let C=L.replace(/\[[^\]]*\]/g,"").trim().split(/\s+/);if(!C.length||!C.every((K)=>/^\d*\.?\d+px$/.test(K)))return;let V=C.map(n),q=n(p==="columns"?I.columnGap:I.rowGap)*(p==="columns"?g:x),J=p==="columns"&&I.direction==="rtl",Y=p==="columns"?J?se+W:se:oe;fe.dataset[p==="columns"?"adsGridColumns":"adsGridRows"]=String(V.length),V.forEach((K,ie)=>{let ae=K*(p==="columns"?g:x);if(J)Y-=ae;if(Q(p==="columns"?Y:se,p==="columns"?oe:Y,p==="columns"?ae:W,p==="columns"?re:ae,p==="columns"?"column":"row","rgb(200 66 135 / .35)",!0),Y+=J?0:ae,ie<V.length-1)Q(p==="columns"?J?Y-q:Y:se,p==="columns"?oe:Y,p==="columns"?q:W,p==="columns"?re:q,"gap","rgb(200 66 135 / .12)");Y+=J?-q:q})};if(G(I.gridTemplateColumns,"columns"),Z.some((L)=>L.property==="grid-template-rows"&&L.value!=="none"))G(I.gridTemplateRows,"rows");for(let L of A.children){let p=t.getComputedStyle(L),C=L.getBoundingClientRect();if(p.display==="none"||!C.width||!C.height)continue;let V=n(p.marginLeft)*g,q=n(p.marginRight)*g;Q(C.left-V,C.top,V,C.height,"gutter","rgb(200 66 135 / .16)"),Q(C.right,C.top,q,C.height,"gutter","rgb(200 66 135 / .16)")}}if(I.display.includes("flex")||a==="composition"){let G=[...A.children].filter((L)=>{let p=L.getBoundingClientRect();return p.width&&p.height});for(let L of G){de.add(L);let p=L.getBoundingClientRect();Q(p.left,p.top,p.width,p.height,"content","rgb(70 120 250 / .5)",!0)}for(let L=1;L<G.length;L++){let p=G[L-1].getBoundingClientRect(),C=G[L].getBoundingClientRect();if(C.top>=p.bottom)Q(Math.max(p.left,C.left),p.bottom,Math.min(p.right,C.right)-Math.max(p.left,C.left),C.top-p.bottom,"gap","rgb(200 66 135 / .16)");else if(C.left>=p.right)Q(p.right,Math.max(p.top,C.top),C.left-p.right,Math.min(p.bottom,C.bottom)-Math.max(p.top,C.top),"gap","rgb(200 66 135 / .16)");else if(p.left>=C.right)Q(C.right,Math.max(p.top,C.top),p.left-C.right,Math.min(p.bottom,C.bottom)-Math.max(p.top,C.top),"gap","rgb(200 66 135 / .16)")}}if(D.push(fe),w===A){let G=[...new Set(Z.flatMap((L)=>L.value.match(/--[\w-]+/g)??[]))];ne.push({label:A.getAttribute("aria-label")??A.getAttribute("role")??A.tagName.toLowerCase(),width:Math.round(O.width*10)/10,height:Math.round(O.height*10)/10,display:I.display,padding:z,margin:le,rowGap:I.rowGap,columnGap:I.columnGap,tokens:G})}}for(let A of b)if(!de.has(A))y.unobserve(A),b.delete(A);for(let A of de)if(!b.has(A))y.observe(A),b.add(A);let ue=ne[0];if(ue){u=w;let A=JSON.stringify(ue);if(A!==c)c=A,s(ue)}else if(u&&!e.contains(u))ee();o.replaceChildren(...D)}function ee(){u=void 0,c="",s(null)}function j(P){if(d===P){f();return}if(d=P,P)o=r.createElement("div"),o.id="ads-grid-overlay",o.setAttribute("aria-hidden","true"),o.style.cssText="position:fixed;inset:0;z-index:2147483646;pointer-events:none;overflow:hidden",r.body.append(o),l.observe(e,{childList:!0,subtree:!0,attributes:!0,characterData:!0}),l.observe(r.documentElement,{attributes:!0}),e.addEventListener("pointermove",v,{passive:!0}),e.addEventListener("pointerleave",S),e.addEventListener("focusin",v),e.addEventListener("focusout",E),t.addEventListener("resize",f),r.addEventListener("scroll",f,!0),f();else t.cancelAnimationFrame(i),i=void 0,y.disconnect(),b.clear(),l.disconnect(),e.removeEventListener("pointermove",v),e.removeEventListener("pointerleave",S),e.removeEventListener("focusin",v),e.removeEventListener("focusout",E),t.removeEventListener("resize",f),r.removeEventListener("scroll",f,!0),o?.remove(),o=void 0,w=null,ee()}return{setVisible:j,setGuides(P){h=P??{},f()},setMetadata(P,B){m=P,a=B,w=null,ee(),f()},dispose(){j(!1)}}}function Xe(e){let s=e.map((r)=>({...r}));for(let r=!0;r;){r=!1;e:for(let t=0;t<s.length;t++)for(let n=t+1;n<s.length;n++){let o=s[t],i=s[n];if(o.left<=i.right&&i.left<=o.right&&o.top<=i.bottom&&i.top<=o.bottom){s[t]={left:Math.min(o.left,i.left),top:Math.min(o.top,i.top),right:Math.max(o.right,i.right),bottom:Math.max(o.bottom,i.bottom)},s.splice(n,1),r=!0;break e}}}return s}function je(e,{decorate:s=!0}={}){let r=e.ownerDocument,t=r.defaultView,n=[],o=null,i=null,c=null,u=0,d=null,m=new t.ResizeObserver(()=>v()),a=new t.MutationObserver(()=>S()),w=()=>v();function h(E){let R=E.dataset.adsSource??"";return!R.includes(".ads.")&&n.some((U)=>R.startsWith(`${U}/`)||R.startsWith(`${U}.`))}function b(){if(d?.remove(),d=null,c)delete c.dataset.adsStaged,delete c.dataset.adsSubjectOnly}function y(E){if(E===c)return;if(c?.removeEventListener("scroll",w),m.disconnect(),b(),c=E,!c)return;c.addEventListener("scroll",w,{passive:!0}),m.observe(c)}function l(){y(e.querySelector(":scope > .ads-preview-root"));let E=!c?[]:o?[...c.querySelectorAll(o)]:n.length?[...c.querySelectorAll("[data-ads-source]")].filter(h):[],R=E.filter((T)=>!E.some((_)=>_!==T&&_.contains(T))),U=R.length===1?R[0].parentElement:null,F=U&&(U===c||U.parentElement===c&&U.children.length===1)&&[...c.children].every((T)=>T===d||T===U||T===R[0]);return c?.toggleAttribute("data-ads-subject-only",Boolean(F)),R}function f(){u=0;let E=l();if(!s||c?.hasAttribute("data-ads-subject-only")){if(d?.remove(),d=null,c)delete c.dataset.adsStaged;return}let R=(j)=>{let P=j.parentElement;if(!P||P===c||P.children.length!==1)return j;return[...P.childNodes].some((B)=>B.nodeType===3&&B.textContent.trim())?P:j},U=Xe(E.map(R).flatMap((j)=>{m.observe(j);let P=j.getBoundingClientRect(),B=i&&j.matches(i)?0:8;return P.width&&P.height?[{left:P.left-B,top:P.top-B,right:P.right+B,bottom:P.bottom+B}]:[]}));if(!U.length){b();return}let F=c.getBoundingClientRect(),T={left:F.left+c.clientLeft,top:F.top+c.clientTop};if(T.right=T.left+c.clientWidth,T.bottom=T.top+c.clientHeight,!d||d.parentElement!==c)d?.remove(),d=r.createElement("div"),d.dataset.adsSubjectStage="",d.setAttribute("aria-hidden","true"),Object.assign(d.style,{position:"fixed",inset:"0",pointerEvents:"none",background:"var(--bg-canvas, Canvas)",zIndex:"-1"}),c.prepend(d);c.dataset.adsStaged="";let _=U.map((j)=>({left:Math.max(j.left,T.left),top:Math.max(j.top,T.top),right:Math.min(j.right,T.right),bottom:Math.min(j.bottom,T.bottom)})).filter((j)=>j.right>j.left&&j.bottom>j.top),ee=(j)=>`M${j.left} ${j.top}H${j.right}V${j.bottom}H${j.left}Z`;d.style.clipPath=_.length?`path("${_.map(ee).join("")}")`:"inset(50%)",d.dataset.adsStages=String(U.length)}function v(){if(!u)u=t.requestAnimationFrame(f)}function S(){l(),v()}return a.observe(e,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["class","hidden","open","data-ads-source"]}),t.addEventListener("resize",v),{setSubjects(E){n=[...E??[]],o=null,i=null,S()},setSubjectSelector(E,R=null){n=[],o=E||null,i=R,S()},refresh:S,dispose(){if(a.disconnect(),u)t.cancelAnimationFrame(u);t.removeEventListener("resize",v),y(null),b(),n=[],o=null,i=null}}}function Le(e){return Array.isArray(e)&&e.length>0&&e.every((s)=>s&&typeof s==="object"&&typeof s.token==="string"&&/^--[\w-]+$/.test(s.token)&&typeof s.property==="string"&&/^-?[a-z][a-z0-9-]*$/.test(s.property)&&typeof s.probe==="string"&&s.probe.trim().length>0)&&new Set(e.map((s)=>`${s.token}:${s.property}`)).size===e.length}function Ue(e,s){let r=s.getComputedStyle(e),t=e.getBoundingClientRect();if(r.display==="none"||r.visibility!=="visible"||!e.getClientRects().length||!(t.width||t.height))return!1;for(let n=e;n;n=n.parentElement)if(Number(s.getComputedStyle(n).opacity)===0)return!1;return!0}function Be(e,s){if(!Le(s))return{ok:!1,diagnostics:["Token preview needs explicit { token, property, probe } samples from the project fixture. Rebuild with the current compiler."]};let r=e.ownerDocument,{defaultView:t,documentElement:n}=r,o=[],i=[],c=[...e.querySelectorAll("[data-ads-token], [data-ads-property]")],u=new Set(s.map((d)=>`${d.token}:${d.property}`));for(let d of c)if(!u.has(`${d.dataset.adsToken}:${d.dataset.adsProperty}`))o.push(`Undeclared rendered token sample ${d.dataset.adsToken}:${d.dataset.adsProperty}.`);for(let d of s){if(!t.CSS.supports(d.property,d.probe)){o.push(`${d.token}: the fixture probe is invalid for ${d.property}.`);continue}let m=t.getComputedStyle(n).getPropertyValue(d.token).trim();if(!m||!t.CSS.supports(d.property,m)){o.push(`${d.token}: its current value is invalid for the fixture's ${d.property} binding.`);continue}let a=c.filter((h)=>h.dataset.adsToken===d.token&&h.dataset.adsProperty===d.property);if(!a.length){o.push(`${d.token} needs a rendered ${d.property} sample, not only a name/value label.`);continue}let w=!1;for(let h of a){let b=[];for(let f=h.parentElement;f&&f!==e;f=f.parentElement)if(f.tagName==="DETAILS"&&!f.open)f.open=!0,b.push(f);let y=n.getAttribute("style"),l=h.getAttribute("style");try{if(!/^(?:-[a-z]+-)?transition(?:-|$)/.test(d.property))h.style.setProperty("transition","none","important");let f=t.getComputedStyle(h).getPropertyValue(d.property),v=Ue(h,t);n.style.setProperty(d.token,d.probe,"important");let S=t.getComputedStyle(h).getPropertyValue(d.property);w=Boolean(S&&S!==f&&(v||Ue(h,t)))}finally{if(y===null)n.removeAttribute("style");else n.setAttribute("style",y);if(l===null)h.removeAttribute("style");else h.setAttribute("style",l);for(let f of b)f.open=!1}if(w)break}if(w)i.push(d);else o.push(`${d.token} has no visible ${d.property} sample that responds to its value. Hardcoded copies do not satisfy coverage.`)}return{ok:!o.length,verified:i,diagnostics:o}}function Ie({container:e=document.getElementById("root"),bindings:s=[],auditResources:r=!1}={}){let t=[],n=[],o=[];if(!e||!Array.isArray(s)||s.length>100)return{ok:!1,diagnostics:["Invalid bounded paint-audit descriptor."],verified:n};let i=e.ownerDocument,c=i.defaultView,u=["color","fill","stroke","stop-color","background-color","border-top-color","border-right-color","border-bottom-color","border-left-color"];function d(a,w,h,b=new Set){if(a=a.trim(),["none","currentColor"].includes(a))return!0;let y=/^var\(\s*(--[\w-]+)\s*\)$/.exec(a);if(y){let v=y[1];if(!h.tokens.includes(v)||b.has(v))return!1;let S=c.getComputedStyle(w).getPropertyValue(v).trim();return!!S&&c.CSS.supports("color",S)}let l=Array.isArray(h.themes)?h.themes:[];if(l.length&&a.startsWith("var(--ads-if-")){let v=/^var\(\s*--ads-if-([a-z][a-z0-9-]*)\s*,\s*(var\(\s*--[\w-]+\s*\)|currentColor|none)\s*\)/,S=a,E=[];while(S){let R=v.exec(S);if(!R)return!1;E.push(R),S=S.slice(R[0].length).trimStart()}return E.length===l.length&&E.every((R,U)=>R[1]===l[U]&&d(R[2],w,h,b))}let f=/^url\(\s*(["']?)#([^\s"'()#\\\p{Cc}]+)\1\s*\)$/u.exec(a);if(f&&c.CSS.supports("fill",a)){let v=[...i.querySelectorAll("[id]")].filter((S)=>S.id===f[2]);return v.length===1&&["linearGradient","radialGradient","pattern"].includes(v[0].localName)&&w.contains(v[0])}return!1}for(let a of s){if(!a||typeof a.scope!=="string"||!Array.isArray(a.tokens)||typeof a.prefix!=="string"||typeof a.suffix!=="string"){t.push("Invalid paint binding metadata; rebuild previews.");continue}let w;try{w=[...e.querySelectorAll(a.scope)]}catch{t.push(`${a.owner}: invalid binding scope.`);continue}if(w.length>20)o.push(`${a.owner}: only the first 20 instances were audited; use a focused scenario for complete evidence.`);for(let h of w.slice(0,20)){let b=[h,...h.querySelectorAll("*")];if(b.length>1000){o.push(`${a.owner}: instance exceeds 1000 elements; paint effects are not established.`);continue}let y=[...h.style].filter((l)=>l.startsWith(a.prefix)&&l.endsWith(a.suffix));if(y.length>100)o.push(`${a.owner}: only the first 100 binding keys were audited.`);for(let l of y.slice(0,100)){let f=h.style.getPropertyValue(l).trim(),v=l.slice(a.prefix.length,a.suffix?-a.suffix.length:void 0);if(!/^[A-Za-z0-9_-]+$/.test(v)||!d(f,h,a)){t.push(`${a.owner}: invalid or inaccessible paint ${l}: ${f}. Use an accessible token, instance-local SVG paint server, none or currentColor.`);continue}let S=h.getAttribute("style"),E=b.map((R)=>R.getAttribute("style"));try{for(let F of b)F.style.setProperty("transition","none","important");let R=b.map((F)=>u.map((T)=>c.getComputedStyle(F).getPropertyValue(T)));h.style.setProperty(l,"rgb(17, 103, 211)","important");let U=b.some((F,T)=>u.some((_,ee)=>c.getComputedStyle(F).getPropertyValue(_)!==R[T][ee]));if(!U)h.style.setProperty(l,"rgb(211, 67, 23)","important"),U=b.some((F,T)=>u.some((_,ee)=>c.getComputedStyle(F).getPropertyValue(_)!==R[T][ee]));if(!U)o.push(`${a.owner}: ${l} has no observed paint effect in its current instance. A written variable alone is not rendering evidence; check the relevant selected/visible consumer.`);else n.push({owner:a.owner,binding:a.name,variable:l})}finally{if(b.forEach((R,U)=>{if(E[U]===null)R.removeAttribute("style");else R.setAttribute("style",E[U])}),S===null)h.removeAttribute("style");else h.setAttribute("style",S)}}for(let l of b)for(let f of["fill","stroke","stop-color"]){let v=l.getAttribute(f);if(!v)continue;let S=/^var\(\s*(--[\w-]+)\s*\)$/.exec(v);if(S&&S[1].startsWith(a.prefix)&&S[1].endsWith(a.suffix)&&!y.includes(S[1]))t.push(`${a.owner}: ${S[1]} is consumed without a value in this instance.`);if(v.startsWith("url(")&&!d(v,h,a))t.push(`${a.owner}: missing, duplicated or out-of-instance local paint resource ${v}.`)}}}let m=r?[...e.querySelectorAll("[fill], [stroke], [style]")]:[];if(m.length>1000)o.push("Only the first 1000 potential SVG paint consumers were audited.");for(let a of m.slice(0,1000))for(let w of["fill","stroke"]){let h=a.getAttribute(w)??a.style.getPropertyValue(w);if(!h?.startsWith("url("))continue;let b=/^url\(\s*(["']?)#([^\s"'()#\\\p{Cc}]+)\1\s*\)$/u.exec(h)?.[2],y=b?[...i.querySelectorAll("[id]")].filter((f)=>f.id===b):[],l=a.ownerSVGElement??(a.localName==="svg"?a:null);if(y.length!==1||!l?.contains(y[0])||!["linearGradient","radialGradient","pattern"].includes(y[0]?.localName))t.push(`Invalid, missing, duplicated or nonlocal SVG paint resource ${h}. Keep IDs isolated per rendered instance.`)}return{ok:!t.length,complete:!o.length,verified:n,diagnostics:t.slice(0,40),limits:o.slice(0,20),scope:"observed App instances and current input; repeat after updates"}}var ze=/^[a-f0-9]{64}$/,Ze=/^ads:\/\/assets\/[a-f0-9]{64}\.[a-z0-9]+$/;function xe(e){if(e?.schemaVersion!==1||!["react","preact"].includes(e.framework)||!ze.test(e.revision)||!e.assets||typeof e.assets!=="object"||Array.isArray(e.assets)||!Array.isArray(e.scenarios))throw Error("Invalid preview manifest update.");let s=new Set;for(let r of e.scenarios){if(!r||typeof r.id!=="string"||s.has(r.id)||e.assets[r.module]?.kind!=="module")throw Error("Invalid updated preview scenarios.");s.add(r.id)}for(let[r,t]of Object.entries(e.assets))if(!Ze.test(r)||!t||!["imports","dynamicImports","styles","references"].every((n)=>Array.isArray(t[n])&&t[n].every((o)=>Object.hasOwn(e.assets,o))))throw Error("Invalid updated preview dependencies.");return e}function ve(e,s){if(e?.version!==1)throw Error("Unsupported preview manifest update.");if(e.type==="full")return xe(e.manifest);if(!s||e.baseRevision!==s.revision)throw Error("Preview manifest update base does not match.");let r=e.header;if(!r||Object.hasOwn(r,"assets")||Object.hasOwn(r,"scenarios")||!ze.test(r.revision))throw Error("Invalid preview manifest update header.");if(e.type==="unchanged"){if(r.revision!==s.revision)throw Error("Unchanged preview revision does not match.");return xe({...r,assets:s.assets,scenarios:s.scenarios})}if(e.type!=="delta"||!e.assets?.upsert||!Array.isArray(e.assets.remove)||!Array.isArray(e.scenarios?.upsert)||!Array.isArray(e.scenarios.remove))throw Error("Invalid preview manifest delta.");let t=new Map(Object.entries(s.assets)),n=new Map(s.scenarios.map((c)=>[c.id,c]));for(let c of e.assets.remove)if(!t.delete(c))throw Error("Unknown removed preview asset.");for(let[c,u]of Object.entries(e.assets.upsert))t.set(c,u);for(let c of e.scenarios.remove)if(!n.delete(c))throw Error("Unknown removed preview scenario.");let o=new Set;for(let c of e.scenarios.upsert){if(!c||o.has(c.id))throw Error("Duplicate updated preview scenario.");o.add(c.id),n.set(c.id,c)}let i=e.scenarios.order??s.scenarios.map((c)=>c.id);if(!Array.isArray(i)||i.length!==n.size||new Set(i).size!==i.length||i.some((c)=>!n.has(c)))throw Error("Invalid updated preview scenario order.");return xe({...r,assets:Object.fromEntries(t),scenarios:i.map((c)=>n.get(c))})}function De(e){let s=new Map,r=new Map,t=0,n,o=0,i=0,c=!0;function u(m){s.delete(m.revision),s.set(m.revision,{graph:m,size:new TextEncoder().encode(JSON.stringify(m)).byteLength});let a=[...s.values()].reduce((w,h)=>w+h.size,0);while(s.size>6||a>8388608){let w=s.keys().next().value;a-=s.get(w).size,s.delete(w)}}let d=(m)=>JSON.parse(m.contents.find((a)=>typeof a.text==="string").text);return{clear(){t++,s.clear(),r.clear(),n=void 0,c=!0},async get(m,{revision:a,session:w}={}){let h=a&&s.get(a)?.graph;if(h&&(!w||h.session===w))return{...h,transportManifestUri:m};let b=n,y=t,l=JSON.stringify([m,a,w,b?.revision]);if(!r.has(l)){let f=++o,v=(async()=>{let S;if(b&&c)try{S=await e(m+"?from="+b.revision)}catch(U){if(U.code!==-32002&&!/unknown (?:ADS )?resource|resource not found/i.test(U.message))throw U;if(y===t)c=!1;S=await e(m)}else S=await e(m);let E=d(S),R=ve(E.type?E:{version:1,type:"full",manifest:E},b);if(y===t){if(u(R),f>=i)n=R,i=f}return R})();r.set(l,v),v.then(()=>{if(r.get(l)===v)r.delete(l)},()=>{if(r.get(l)===v)r.delete(l)})}return{...await r.get(l),transportManifestUri:m}}}}async function Ge(e,s=(r)=>new me(r)){let r=document.getElementById("root"),t=document.getElementById("ads-preview-status"),n,o=async(g)=>{if(!e.getHostCapabilities()?.serverResources)throw Error("This host does not forward MCP resource reads. Open the same preview in the ADS showcase.");try{return await e.readServerResource({uri:n?n+encodeURIComponent(g):g},{timeout:15000})}catch(x){if(x.code===-32601||x.message==="Method not found")throw Error("This host does not forward MCP resource reads. Open the same preview in the ADS showcase.");throw x}},i=s(o),c=De(o);document.documentElement.dataset.adsPreviewDelivery=e.delivery??"mcp-blob";let u,d,m,a,w,h=!1,b,y=0,l={},f=[],v="",S=!1,E,R,U=new Set;function F(g){if(e.getHostVersion()?.name!=="ADS showcase")return;let x=R;if(R=g,!x)return;let M=Oe(x,g).filter((k)=>k!==u&&U.has(k));if(!M.length)return;i.prefetch(g,M).then((k)=>_("prefetched",{revision:g.revision,...k})).catch((k)=>console.warn("ADS preview prefetch",k.message))}function T(g,x=!1){t.textContent=g,t.hidden=!g||e.getHostVersion()?.name==="ADS showcase",t.setAttribute("role",x?"alert":"status")}async function _(g,x={}){try{if(e.getHostCapabilities()?.logging)await e.sendLog({level:g==="error"?"error":"info",logger:"ads-preview",data:{state:g,id:u,...x}})}catch{}}let ee=!1,j=$e(r),P=je(r,{decorate:globalThis.__ADS_RENDER_AUDIT__!==!0}),B=".ads-token-sample:not(.ads-token-shadow):not(.ads-token-motion), .ads-token-stage-shadow, .ads-token-stage-motion, .ads-grid-example, .ads-foundation-ratios, .ads-brand-master, .ads-brand-art, .ads-brand-sizes img, .ads-pictogram-image";function H(g){l={...l,...g,styles:{...l.styles,...g.styles}};let x=l.adsTheme??(["light","dark"].includes(l.theme)?(f.find((M)=>M.scheme===l.theme)??{name:l.theme}).name:void 0);if(x)document.documentElement.dataset.theme=x;if(typeof l.adsBrand==="string"&&/^[a-z][a-z0-9-]*$/.test(l.adsBrand))document.documentElement.dataset.brand=l.adsBrand;j.setGuides(l.gridGuides),j.setVisible(ee&&l.gridOverlay===!0),N(),ue()}function N(){document.dispatchEvent(new CustomEvent(Ce,{detail:ge(l.gridGuideChoices??l.gridGuides)}))}function D(g){if(!g.detail){N();return}let x=ge(g.detail);H({gridGuideChoices:x,gridGuides:Me(x),gridOverlay:Te(x)}),_("guide-options",{options:x})}document.addEventListener(Ee,D);let de=(g)=>{if(typeof g.detail?.target==="string")_("navigate",{target:g.detail.target,token:g.detail.token})};document.addEventListener("ads-preview-navigate",de);let ne;function ue(){let g=l.adsFocus;if(!g||g.nonce===ne||g.target!==u||document.documentElement.dataset.adsPreviewState!=="ready")return;ne=g.nonce,document.dispatchEvent(new CustomEvent("ads-preview-focus",{detail:{token:g.token}}))}async function A(g="ads://preview/manifest",x,M){try{return await(i.manifest?i.manifest(g,{revision:x,session:M,scenario:u}):c.get(g,{revision:x,session:M}))}catch(k){throw Object.assign(Error(k.message,{cause:k}),{code:"ADS_MANIFEST_READ",category:"transport"})}}async function I(g,x,M=!1,k="",z=!1,le){let se=M||z;if(!k&&g===u&&x&&x===m&&(!le||le===a)&&se===S){T(v||(se?"Checking changes…":""),Boolean(v)),await _(v?"error":se?"checking":"ready",v?{message:v}:{revision:m});return}let oe=++y;++i.generation,u=g,ee=!1,j.setVisible(!1),U.add(g),document.documentElement.dataset.adsScenario=g,document.documentElement.dataset.adsPreviewState="loading";for(let W of["adsPreviewErrorCategory","adsPreviewErrorCode","adsPreviewResourceUri"])delete document.documentElement.dataset[W];v="",T(""),await _(k?"reverting":"loading");try{let W=performance.now(),re=await A(M?"ads://preview/live":"ads://preview/manifest",x,le);if(oe!==y)return;if(Array.isArray(re.themes))f=re.themes,H({});if(x&&re.revision!==x||le&&re.session!==le){if(oe===y)T("Updating preview…"),await _("loading",{code:"ADS_PREVIEW_CHANGED"});return}if(oe!==y)return;let fe=performance.now();performance.measure("ads-preview:manifest",{start:W,end:fe});let Q=await i.mount(re,g,r);if(performance.measure("ads-preview:load-mount",{start:fe,end:performance.now()}),!Q||oe!==y)return;let X=re.scenarios.find((Z)=>Z.id===g);if(r.dataset.adsScenarioKind=X?.kind??"",X?.foundation)P.setSubjectSelector(B,".ads-grid-example");else P.setSubjects(["components","patterns"].includes(X?.kind)?X.subjects:[]);if(m=re.revision,a=re.session,S=se,await new Promise((Z)=>requestAnimationFrame(()=>requestAnimationFrame(Z))),await document.fonts.ready,oe!==y)return;if(ee=["components","patterns","composition"].includes(X?.kind)||g==="tokens/Layout",j.setMetadata(Object.values(re.assets).flatMap((Z)=>Z.spatial?[Z.spatial]:[]),X?.kind),H({}),r.dataset.adsPaintBindings=JSON.stringify(X?.paintBindings??[]),r.dataset.adsPaintAudit=String(Boolean(X?.paintAudit)),r.dataset.adsPaintAuditComplete="not-requested",X?.paintBindings?.length||X?.paintAudit){let Z=Ie({container:r,bindings:X.paintBindings??[],auditResources:Boolean(X.paintAudit)});if(!Z.ok)throw Object.assign(Error(`Paint binding verification failed:
|
|
2
|
+
${Z.diagnostics.join(`
|
|
3
|
+
`)}`),{code:"ADS_PAINT_BINDING",category:"assertion"});if(r.dataset.adsPaintAuditComplete=String(Z.complete),!Z.complete)await _("audit-limited",{limits:Z.limits})}if(X?.kind==="tokens"&&!X.foundation){let Z=Be(r,X.samples);if(!Z.ok)throw v=`Token preview verification failed:
|
|
4
|
+
${Z.diagnostics.slice(0,20).join(`
|
|
5
|
+
`)}`,Object.assign(Error(v),{code:"ADS_TOKEN_SAMPLE",category:"assertion"})}if(oe===y){if(document.documentElement.dataset.adsPreviewRevision=m,document.documentElement.dataset.adsPreviewState=k?"error":se?"checking":"ready",T(k||(se?"Checking changes…":""),Boolean(k)),await _(k?"error":se?"checking":"ready",{revision:m,selectionRevision:d,...k?{message:k}:{}}),!se&&!k)F(re)}if(oe===y)ue()}catch(W){if(oe===y){if(document.documentElement.dataset.adsPreviewState="error",document.documentElement.dataset.adsPreviewErrorCategory=W.category??"runner",document.documentElement.dataset.adsPreviewErrorCode=W.code??"ADS_PREVIEW_STARTUP",W.resourceUri)document.documentElement.dataset.adsPreviewResourceUri=W.resourceUri;T(W.message,!0),await _("error",{message:W.message,...W.code?{code:W.code}:{},...W.category?{category:W.category}:{},...W.resourceUri?{resourceUri:W.resourceUri}:{}})}}}async function O(g){if(!u)return;if(document.visibilityState==="hidden"){if(g)b=g;return}if(h){if(g)b=g;return}h=!0;let x=y;try{let M=g??JSON.parse((await o("ads://project/build")).contents.find((z)=>typeof z.text==="string").text);if(x!==y)return;E=void 0;let k=M.previews.find((z)=>z.id===u);if(k?.live&&!k.current)if(k.live.revision!==m||M.session!==a||!S)await I(u,k.live.revision,!0,"",!1,M.session);else T(v||"Checking changes…",Boolean(v));else if(!k||!k.current){let z=k?.diagnostics?.[0]?.message;if(z&&S){let le=await A("ads://preview/manifest",M.manifestRevision,M.session);await I(u,le.revision,!1,`Build failed. Showing the previous preview.
|
|
6
|
+
${z}`,!1,M.session)}T(z?`Build failed. Showing the previous preview.
|
|
7
|
+
${z}`:"Rebuilding. This is the previous preview.",Boolean(z))}else{let z=await A("ads://preview/manifest",M.manifestRevision,M.session);if(x!==y)return;if(z.revision!==m||z.session!==a||S)await I(u,z.revision,!1,"",!1,M.session);else T(v,Boolean(v)),F(z)}}catch(M){if(x!==y)return;let k=`Preview freshness unavailable: ${M.message}`;if(T(k,!0),E!==k)E=k,await _("error",{message:k})}finally{h=!1;let M=b;if(b=void 0,M)O(M)}}e.onbuildreport=(g)=>{O(g)};let te=()=>{if(document.visibilityState!=="hidden")b=void 0,O()};document.addEventListener("visibilitychange",te),e.ontoolresult=(g)=>{let x=g.structuredContent?.draftScope;if(x!==n)++y,++i.generation,c.clear(),m=a=R=void 0,U.clear();n=x;let M=g.structuredContent?.previewResult?.structuredContent??g.structuredContent;if(M?.scenario?.id)d=M.manifestRevision,I(M.scenario.id,M.manifestRevision,M.manifestUri==="ads://preview/live","",M.build?.current===!1,M.build?.session).then(()=>{if(e.buildPollInterval===0)O()})},e.onhostcontextchanged=H,e.onteardown=async()=>(++y,u=b=void 0,e.onbuildreport=void 0,c.clear(),document.removeEventListener("visibilitychange",te),document.removeEventListener(Ee,D),document.removeEventListener("ads-preview-navigate",de),j.dispose(),P.dispose(),clearInterval(w),await i.dispose(),{});try{let g=performance.now();if(await e.connect(),performance.measure("ads-preview:connect",{start:g,end:performance.now()}),H(e.getHostContext()??{}),!e.getHostCapabilities()?.serverResources)throw Error("This host does not forward MCP resource reads. Open the same preview in the ADS showcase.");let x=e.buildPollInterval??150;if(x>0)w=setInterval(()=>{O()},x);let M=document.getElementById("ads-preview-selection");if(M)I(JSON.parse(M.textContent).id)}catch(g){T(g.message,!0)}window.addEventListener("pagehide",()=>{u=b=void 0,e.onbuildreport=void 0,clearInterval(w),c.clear(),i.dispose()},{once:!0})}class ke extends me{constructor(e,s){super(e);this.publish=s,this.visited=new Set,this.fetched=new Set,this.http=new AbortController,this.preparing=new Map,this.prepareSerial=0,this.preparedSerial=0}async manifest(e,{revision:s,session:r,scenario:t}){let n=this.prepared;if(n?.uri===e&&n.graph.revision===s&&(!r||n.graph.session===r)&&n.scenarios.includes(t))return{...n.graph,transportManifestUri:e,httpBase:n.base};let o=JSON.stringify([e,s,r,t]);if(!this.preparing.has(o)){let i=++this.prepareSerial,c=performance.now(),u=(async()=>{let d=await this.publish({uri:e,revision:s,scenario:t,retained:[...this.visited],from:n?.graph.revision});if(this.closed)throw Error("The HTTP preview was closed.");let m=ve(d.update,n?.graph);if(m.revision!==d.revision||!d.changed&&!d.scenarios.includes(t))throw Error("HTTP publication does not match its manifest.");if(d.changed)return{...m,transportManifestUri:e};if(i>=this.preparedSerial)this.preparedSerial=i,this.prepared={graph:m,uri:e,base:d.base,scenarios:d.scenarios};return performance.measure("ads-preview:http-prepare",{start:c,end:performance.now()}),{...m,transportManifestUri:e,httpBase:d.base}})();this.preparing.set(o,u),u.then(()=>this.preparing.delete(o),()=>this.preparing.delete(o))}return this.preparing.get(o)}async mountRevision(e,s,r,t){if(this.closed||t!==this.generation)return!1;if(!e.httpBase)throw Error("The preview graph has not been published for HTTP.");return this.base=e.httpBase,this.visited.add(s),super.mountRevision(e,s,r,t)}async materialize(e){let s=this.closure(e),r={};for(let t of s){if(this.closed)throw Error("The HTTP preview was closed.");if(this.urls.has(t))continue;let n=this.records.get(t),o=this.base+t.slice(13);if(n.kind==="asset"&&n.mimeType==="text/javascript"||n.references.some((i)=>this.urls.get(i)?.startsWith("blob:"))){let i=new TextDecoder().decode(await this.resource(t));for(let c of n.references){let u=this.urls.get(c);if(!u)throw Error("Unsupported cyclic asset reference.");i=i.replaceAll(c,u)}o=URL.createObjectURL(new Blob([i],{type:n.mimeType}))}if(this.urls.set(t,o),n.kind==="module")r[t]=o}if(Object.keys(r).length){let t=document.createElement("script");t.type="importmap",t.textContent=JSON.stringify({imports:r}),document.head.append(t)}return s}async resource(e){if(!this.bytes.has(e)){let s=(async()=>{let r=await fetch(this.base+e.slice(13)+"?raw=1",{signal:this.http.signal});if(!r.ok)throw Error(`HTTP preview asset unavailable: ${r.status}`);let t=new Uint8Array(await r.arrayBuffer());if(this.closed)throw Error("The HTTP preview was closed.");try{return await Se(this.records.get(e),t)}catch(n){throw n.resourceUri=e,n}})();this.bytes.set(e,s),s.catch(()=>this.bytes.delete(e))}return this.bytes.get(e)}async prefetch(e,s){if(this.closed)return;this.register(e);let r=++this.prefetchGeneration,t=new Set,n=[],o=0;for(let m of s){let a=e.scenarios.find((b)=>b.id===m);if(!a)continue;let w=this.closure(a.module).filter((b)=>!this.urls.has(b)&&!this.fetched.has(b)&&!t.has(b)),h=w.reduce((b,y)=>b+this.records.get(y).size,0);if(o+h>16777216||t.size+w.length>256||n.length>=128)continue;o+=h,n.push(m);for(let b of w)t.add(b)}if(!t.size)return{scenarios:n,resources:0};let i=await this.manifest(e.transportManifestUri,{revision:e.revision,session:e.session,scenario:n[0]});if(i.revision!==e.revision||this.closed||r!==this.prefetchGeneration)return{scenarios:[],resources:0};let c=[...t],u=0,d=async()=>{while(!this.closed&&r===this.prefetchGeneration&&u<c.length){let m=c[u++],a=await fetch(i.httpBase+m.slice(13),{signal:this.http.signal});if(!a.ok)throw Error(`HTTP preview prefetch failed: ${a.status}`);if(await a.arrayBuffer(),!this.closed)this.fetched.add(m)}};return await Promise.all(Array.from({length:Math.min(3,c.length)},d)),{scenarios:n,resources:c.length}}async dispose(){this.http.abort(),await super.dispose(),this.visited.clear(),this.fetched.clear(),this.prepared=void 0,this.preparing.clear()}}var{id:Ne,parentOrigin:He}=JSON.parse(document.getElementById("ads-http-instance").textContent),Qe=new EventSource(new URL("lifetime",location.href)),he=new Map,et=0,Ae=0,ye,Ve,_e=!1,be=(e)=>parent.postMessage({channel:"ads-preview-http",instance:Ne,epoch:Ae,...e},He);function qe(e,s){return new Promise((r,t)=>{let n=++et,o=setTimeout(()=>{he.delete(n),t(Error("HTTP preview control timed out."))},15000);he.set(n,{resolve:r,reject:t,timer:o}),be({method:e,params:s,request:n})})}var we={delivery:"http",buildPollInterval:0,getHostCapabilities:()=>({serverResources:{},logging:{}}),getHostVersion:()=>({name:"ADS showcase"}),getHostContext:()=>ye,connect:()=>new Promise((e)=>{Ve=e,be({method:"ready"})}),readServerResource:(e)=>qe("read",e),sendLog:(e)=>be({method:"log",params:e})};function We(){if(_e)return;_e=!0,window.removeEventListener("message",Je),Qe.close();for(let e of he.values())clearTimeout(e.timer),e.reject(Error("HTTP preview disposed."));he.clear()}async function Je(e){let s=e.data;if(e.source!==parent||e.origin!==He||s?.channel!=="ads-preview-http"||s.instance!==Ne)return;if(s.method==="init"){ye=s.params,Ve?.();return}if(s.method==="select"){for(let r of he.values())clearTimeout(r.timer),r.reject(Error("Preview selection superseded."));he.clear(),Ae=s.epoch,we.ontoolresult?.(s.params);return}if(s.epoch!==Ae)return;if(s.method==="context")ye=s.params,we.onhostcontextchanged?.(ye);else if(s.method==="build")we.onbuildreport?.(s.params);else if(s.method==="response"){let r=he.get(s.request);if(!r)return;if(clearTimeout(r.timer),he.delete(s.request),s.error)r.reject(Object.assign(Error(s.error),{code:s.code}));else r.resolve(s.result)}else if(s.method==="teardown")await we.onteardown?.(),be({method:"disposed"}),We()}window.addEventListener("message",Je);window.addEventListener("pagehide",We,{once:!0});await Ge(we,(e)=>new ke(e,(s)=>qe("prepare",s)));
|