@reqvire-org/ads 0.3.42 → 0.3.44

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (131) hide show
  1. package/README.md +11 -5
  2. package/dist/assets.mjs +48 -2
  3. package/dist/bootstrap-ds/ADS.md +2 -1
  4. package/dist/bootstrap-ds/README.md +25 -14
  5. package/dist/bootstrap-ds/design-system/assets/brand/README.md +26 -19
  6. package/dist/bootstrap-ds/design-system/assets/brand/app-icon.svg +4 -0
  7. package/dist/bootstrap-ds/design-system/assets/brand/logo.dark.svg +6 -0
  8. package/dist/bootstrap-ds/design-system/assets/brand/logo.svg +6 -0
  9. package/dist/bootstrap-ds/design-system/components/Actions/Button/Button.ads.fixture.ts +1 -0
  10. package/dist/bootstrap-ds/design-system/components/Actions/Button/Button.ads.scenario.tsx +13 -0
  11. package/dist/bootstrap-ds/design-system/components/Actions/Button/Button.tsx +49 -0
  12. package/dist/bootstrap-ds/design-system/components/Actions/Button/README.md +12 -0
  13. package/dist/bootstrap-ds/design-system/components/Content/Logo/Logo.ads.fixture.ts +1 -0
  14. package/dist/bootstrap-ds/design-system/components/Content/Logo/Logo.ads.scenario.tsx +12 -0
  15. package/dist/bootstrap-ds/design-system/components/Content/Logo/Logo.tsx +41 -0
  16. package/dist/bootstrap-ds/design-system/components/Content/Logo/README.md +10 -0
  17. package/dist/bootstrap-ds/design-system/components/Forms/TextField/README.md +14 -0
  18. package/dist/bootstrap-ds/design-system/components/Forms/TextField/TextField.ads.fixture.ts +6 -0
  19. package/dist/bootstrap-ds/design-system/components/Forms/TextField/TextField.ads.scenario.tsx +13 -0
  20. package/dist/bootstrap-ds/design-system/components/Forms/TextField/TextField.tsx +57 -0
  21. package/dist/bootstrap-ds/design-system/composition/Search/SearchPage/README.md +4 -0
  22. package/dist/bootstrap-ds/design-system/composition/Search/SearchPage/SearchPage.ads.fixture.ts +7 -0
  23. package/dist/bootstrap-ds/design-system/composition/Search/SearchPage/SearchPage.ads.scenario.tsx +16 -0
  24. package/dist/bootstrap-ds/design-system/index.ts +5 -1
  25. package/dist/bootstrap-ds/design-system/patterns/Search/SearchBar/README.md +12 -0
  26. package/dist/bootstrap-ds/design-system/patterns/Search/SearchBar/SearchBar.ads.fixture.ts +1 -0
  27. package/dist/bootstrap-ds/design-system/patterns/Search/SearchBar/SearchBar.ads.scenario.tsx +11 -0
  28. package/dist/bootstrap-ds/design-system/patterns/Search/SearchBar/SearchBar.tsx +41 -0
  29. package/dist/bootstrap-ds/design-system/review/brand-preview/BrandPreview.tsx +115 -0
  30. package/dist/bootstrap-ds/design-system/review/demo-frame/DemoFrame.tsx +29 -0
  31. package/dist/bootstrap-ds/design-system/review/index.ts +3 -0
  32. package/dist/bootstrap-ds/design-system/review/screen-frame/ScreenFrame.tsx +34 -0
  33. package/dist/bootstrap-ds/design-system/review/token-preview/TokenPreview.tsx +107 -19
  34. package/dist/bootstrap-ds/design-system/tokens/Brand.ads.fixture.ts +12 -0
  35. package/dist/bootstrap-ds/design-system/tokens/Brand.ads.scenario.tsx +4 -0
  36. package/dist/bootstrap-ds/design-system/tokens/Color.ads.fixture.ts +18 -0
  37. package/dist/bootstrap-ds/design-system/tokens/{Foundation.ads.scenario.tsx → Color.ads.scenario.tsx} +1 -1
  38. package/dist/{skills/ads-designer/assets/bootstrap-ds/design-system/tokens/Foundation.ads.fixture.ts → bootstrap-ds/design-system/tokens/SpaceTypeMotion.ads.fixture.ts} +1 -13
  39. package/dist/bootstrap-ds/design-system/tokens/SpaceTypeMotion.ads.scenario.tsx +4 -0
  40. package/dist/bootstrap-ds/ds.config.json +2 -1
  41. package/dist/bootstrap-ds-preact/design-system/review/demo-frame/DemoFrame.tsx +29 -0
  42. package/dist/bootstrap-ds-preact/design-system/review/screen-frame/ScreenFrame.tsx +34 -0
  43. package/dist/bootstrap-ds-preact/design-system/review/token-preview/TokenPreview.tsx +119 -0
  44. package/dist/bootstrap-ds-preact/design-system/showcase/mcp/main.tsx +6 -0
  45. package/dist/bootstrap-ds-preact/ds.config.json +20 -0
  46. package/dist/bootstrap-ds-preact/package.json +38 -0
  47. package/dist/bootstrap-ds-preact/src/vite-env.d.ts +7 -0
  48. package/dist/bootstrap-ds-preact/tsconfig.json +36 -0
  49. package/dist/bootstrap-ds-preact/vite.config.ts +23 -0
  50. package/dist/brand-assets.mjs +136 -3
  51. package/dist/check.mjs +4 -2
  52. package/dist/config.mjs +49 -1
  53. package/dist/init.mjs +16 -7
  54. package/dist/mcp/preview-widget.bundle.js +1 -1
  55. package/dist/mcp/project-widget.bundle.js +1 -1
  56. package/dist/mcp/server.mjs +5 -2
  57. package/dist/mcp/showcase-host.mjs +5 -1
  58. package/dist/preview-builder.mjs +8 -2
  59. package/dist/preview-bun.mjs +4 -2
  60. package/dist/preview-resources.mjs +1 -1
  61. package/dist/scenarios.mjs +11 -4
  62. package/dist/skills/ads-break-ui/SKILL.md +2 -2
  63. package/dist/skills/ads-designer/SKILL.md +42 -19
  64. package/dist/skills/ads-designer/assets/bootstrap-ds/ADS.md +2 -1
  65. package/dist/skills/ads-designer/assets/bootstrap-ds/README.md +25 -14
  66. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/assets/brand/README.md +26 -19
  67. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/assets/brand/app-icon.svg +4 -0
  68. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/assets/brand/logo.dark.svg +6 -0
  69. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/assets/brand/logo.svg +6 -0
  70. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/components/Actions/Button/Button.ads.fixture.ts +1 -0
  71. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/components/Actions/Button/Button.ads.scenario.tsx +13 -0
  72. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/components/Actions/Button/Button.tsx +49 -0
  73. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/components/Actions/Button/README.md +12 -0
  74. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/components/Content/Logo/Logo.ads.fixture.ts +1 -0
  75. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/components/Content/Logo/Logo.ads.scenario.tsx +12 -0
  76. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/components/Content/Logo/Logo.tsx +41 -0
  77. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/components/Content/Logo/README.md +10 -0
  78. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/components/Forms/TextField/README.md +14 -0
  79. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/components/Forms/TextField/TextField.ads.fixture.ts +6 -0
  80. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/components/Forms/TextField/TextField.ads.scenario.tsx +13 -0
  81. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/components/Forms/TextField/TextField.tsx +57 -0
  82. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/composition/Search/SearchPage/README.md +4 -0
  83. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/composition/Search/SearchPage/SearchPage.ads.fixture.ts +7 -0
  84. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/composition/Search/SearchPage/SearchPage.ads.scenario.tsx +16 -0
  85. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/index.ts +5 -1
  86. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/patterns/Search/SearchBar/README.md +12 -0
  87. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/patterns/Search/SearchBar/SearchBar.ads.fixture.ts +1 -0
  88. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/patterns/Search/SearchBar/SearchBar.ads.scenario.tsx +11 -0
  89. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/patterns/Search/SearchBar/SearchBar.tsx +41 -0
  90. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/review/brand-preview/BrandPreview.tsx +115 -0
  91. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/review/demo-frame/DemoFrame.tsx +29 -0
  92. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/review/index.ts +3 -0
  93. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/review/screen-frame/ScreenFrame.tsx +34 -0
  94. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/review/token-preview/TokenPreview.tsx +107 -19
  95. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/tokens/Brand.ads.fixture.ts +12 -0
  96. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/tokens/Brand.ads.scenario.tsx +4 -0
  97. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/tokens/Color.ads.fixture.ts +18 -0
  98. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/tokens/{Foundation.ads.scenario.tsx → Color.ads.scenario.tsx} +1 -1
  99. package/dist/{bootstrap-ds/design-system/tokens/Foundation.ads.fixture.ts → skills/ads-designer/assets/bootstrap-ds/design-system/tokens/SpaceTypeMotion.ads.fixture.ts} +1 -13
  100. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/tokens/SpaceTypeMotion.ads.scenario.tsx +4 -0
  101. package/dist/skills/ads-designer/assets/bootstrap-ds/ds.config.json +2 -1
  102. package/dist/skills/ads-designer/assets/bootstrap-ds-preact/design-system/review/demo-frame/DemoFrame.tsx +29 -0
  103. package/dist/skills/ads-designer/assets/bootstrap-ds-preact/design-system/review/screen-frame/ScreenFrame.tsx +34 -0
  104. package/dist/skills/ads-designer/assets/bootstrap-ds-preact/design-system/review/token-preview/TokenPreview.tsx +119 -0
  105. package/dist/skills/ads-designer/assets/bootstrap-ds-preact/design-system/showcase/mcp/main.tsx +6 -0
  106. package/dist/skills/ads-designer/assets/bootstrap-ds-preact/ds.config.json +20 -0
  107. package/dist/skills/ads-designer/assets/bootstrap-ds-preact/package.json +38 -0
  108. package/dist/skills/ads-designer/assets/bootstrap-ds-preact/src/vite-env.d.ts +7 -0
  109. package/dist/skills/ads-designer/assets/bootstrap-ds-preact/tsconfig.json +36 -0
  110. package/dist/skills/ads-designer/assets/bootstrap-ds-preact/vite.config.ts +23 -0
  111. package/dist/skills/ads-designer/references/branding.md +89 -0
  112. package/dist/skills/ads-designer/references/cli.md +1 -1
  113. package/dist/skills/ads-designer/references/design-craft.md +1 -1
  114. package/dist/skills/ads-import/SKILL.md +2 -2
  115. package/dist/skills/ads-import/references/branding.md +10 -3
  116. package/dist/skills/ads-import/references/cli.md +1 -1
  117. package/dist/skills/ads-motion/SKILL.md +2 -2
  118. package/dist/skills/ads-port/SKILL.md +3 -3
  119. package/dist/skills/ads-port/references/cli.md +1 -1
  120. package/dist/token-fixtures.mjs +2 -2
  121. package/docs/ADS.md +12 -9
  122. package/docs/ARCHITECTURE.md +3 -2
  123. package/docs/CHANGELOG.md +56 -12
  124. package/docs/GUIDE.md +57 -15
  125. package/package.json +1 -1
  126. package/dist/bootstrap-ds/design-system/components/.gitkeep +0 -0
  127. package/dist/bootstrap-ds/design-system/composition/.gitkeep +0 -0
  128. package/dist/bootstrap-ds/design-system/patterns/.gitkeep +0 -0
  129. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/components/.gitkeep +0 -0
  130. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/composition/.gitkeep +0 -0
  131. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/patterns/.gitkeep +0 -0
@@ -0,0 +1,20 @@
1
+ {
2
+ "framework": "preact",
3
+ "behaviorLibraries": [],
4
+ "acceptance": { "checks": [], "behaviorChecks": false },
5
+ "validation": { "checks": [], "behaviorChecks": true, "inputs": [] },
6
+ "mcp": {
7
+ "previewManifest": ".ds/preview/manifest.json"
8
+ },
9
+ "boundaries": {
10
+ "styleWrites": [
11
+ {
12
+ "file": "design-system/review/token-preview/TokenPreview.tsx",
13
+ "properties": [
14
+ "--ux-token-preview-value"
15
+ ]
16
+ }
17
+ ]
18
+ },
19
+ "assets": { "iconSource": "assets/brand/app-icon.svg" }
20
+ }
@@ -0,0 +1,38 @@
1
+ {
2
+ "name": "native-design-system",
3
+ "version": "0.1.0",
4
+ "private": true,
5
+ "type": "module",
6
+ "description": "Private starter workspace for a project's local Preact design system.",
7
+ "engines": {
8
+ "node": ">=22.12.0",
9
+ "bun": ">=1.4.1"
10
+ },
11
+ "sideEffects": [
12
+ "**/*.css"
13
+ ],
14
+ "scripts": {
15
+ "dev": "ads showcase",
16
+ "dev:showcase": "ads showcase",
17
+ "lint": "oxlint --deny-warnings src design-system && biome lint --config-path=biome.css.json .",
18
+ "typecheck": "tsc --noEmit",
19
+ "build": "npm run lint && npm run typecheck && npm run build:lib",
20
+ "build:lib": "vite build && tsc --project tsconfig.build.json",
21
+ "build:showcase": "ads compile .",
22
+ "preview": "ads showcase",
23
+ "preview:showcase": "ads showcase",
24
+ "build:mcp-previews": "ads compile ."
25
+ },
26
+ "devDependencies": {
27
+ "@babel/preset-react": "7.29.7",
28
+ "@babel/preset-typescript": "7.29.7",
29
+ "@biomejs/biome": "2.5.15",
30
+ "@linaria/atomic": "8.0.0",
31
+ "@types/node": "25.9.4",
32
+ "@wyw-in-js/vite": "2.1.3",
33
+ "oxlint": "1.72.0",
34
+ "preact": "11.0.1",
35
+ "typescript": "5.9.3",
36
+ "vite": "6.4.3"
37
+ }
38
+ }
@@ -0,0 +1,7 @@
1
+ /// <reference types="vite/client" />
2
+
3
+ declare module "@scenario" {
4
+ import type { ComponentType } from "preact";
5
+ const Scenario: ComponentType;
6
+ export default Scenario;
7
+ }
@@ -0,0 +1,36 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2022",
4
+ "lib": [
5
+ "ES2022",
6
+ "DOM",
7
+ "DOM.Iterable"
8
+ ],
9
+ "module": "ESNext",
10
+ "moduleResolution": "bundler",
11
+ "skipLibCheck": true,
12
+ "isolatedModules": true,
13
+ "moduleDetection": "force",
14
+ "noEmit": true,
15
+ "jsx": "react-jsx",
16
+ "jsxImportSource": "preact",
17
+ "strict": true,
18
+ "noUnusedLocals": true,
19
+ "noUnusedParameters": true,
20
+ "noFallthroughCasesInSwitch": true,
21
+ "baseUrl": ".",
22
+ "paths": {
23
+ "@ds/review": [
24
+ "design-system/review/index.ts"
25
+ ],
26
+ "@ds": [
27
+ "design-system/index.ts"
28
+ ]
29
+ }
30
+ },
31
+ "include": [
32
+ "src",
33
+ "design-system",
34
+ "vite.config.ts"
35
+ ]
36
+ }
@@ -0,0 +1,23 @@
1
+ import path from "node:path";
2
+ import { defineConfig } from "vite";
3
+ import wyw from "@wyw-in-js/vite";
4
+ import { linariaTagResolver } from "@reqvire-org/ads/linaria";
5
+ import { draftImportGuard } from "@reqvire-org/ads/scenarios/vite";
6
+
7
+ export default defineConfig({
8
+ esbuild: { jsx: "automatic", jsxImportSource: "preact" },
9
+ plugins: [draftImportGuard(), wyw({ tagResolver: linariaTagResolver })],
10
+ resolve: {
11
+ alias: { "@ds/review": path.resolve(import.meta.dirname, "design-system/review/index.ts"), "@ds": path.resolve(import.meta.dirname, "design-system/index.ts") },
12
+ },
13
+ build: {
14
+ outDir: "dist",
15
+ lib: {
16
+ entry: path.resolve(import.meta.dirname, "design-system/index.ts"),
17
+ formats: ["es"],
18
+ fileName: () => "index.js",
19
+ cssFileName: "styles",
20
+ },
21
+ rollupOptions: { external: [/^preact(?:\/.*)?$/] },
22
+ },
23
+ });
@@ -1,4 +1,5 @@
1
- import { lstatSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
1
+ import { createHash } from "node:crypto";
2
+ import { existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync } from "node:fs";
2
3
  import path from "node:path";
3
4
  import { isInside, loadConfig } from "./config.mjs";
4
5
 
@@ -45,11 +46,143 @@ function ico(entries) {
45
46
  return result;
46
47
  }
47
48
 
49
+ const sha256 = bytes => createHash("sha256").update(bytes).digest("hex");
50
+ // Bump when rendering changes, so committed outputs are regenerated.
51
+ const renderer = "ads-brand-targets-1";
52
+ /** The committed record of rendered targets: what each output was made from. */
53
+ export const targetsManifest = "assets/generated.json";
54
+
55
+ /** A target's identity: its master's bytes and its settings, never the rendered pixels. */
56
+ function fingerprint(dsRoot, target) {
57
+ const { from, to, ...settings } = target;
58
+ return sha256(JSON.stringify({ renderer, to, settings, source: sha256(readFileSync(path.join(dsRoot, from))) }));
59
+ }
60
+
61
+ function readManifest(dsRoot) {
62
+ try { const value = JSON.parse(readFileSync(path.join(dsRoot, targetsManifest), "utf8")); return value?.outputs && typeof value.outputs === "object" ? value.outputs : {}; }
63
+ catch { return {}; }
64
+ }
65
+
66
+ // PNG-encoded ICNS entries by pixel size (a 1024 image is the 512@2x slot).
67
+ const icnsTypes = { 16: "icp4", 32: "icp5", 64: "icp6", 128: "ic07", 256: "ic08", 512: "ic09", 1024: "ic10" };
68
+ function icns(entries) {
69
+ const chunks = entries.map(({ size, buffer }) => {
70
+ const header = Buffer.alloc(8);
71
+ header.write(icnsTypes[size], 0, "ascii");
72
+ header.writeUInt32BE(buffer.length + 8, 4);
73
+ return Buffer.concat([header, buffer]);
74
+ });
75
+ const header = Buffer.alloc(8);
76
+ header.write("icns", 0, "ascii");
77
+ header.writeUInt32BE(8 + chunks.reduce((total, chunk) => total + chunk.length, 0), 4);
78
+ return Buffer.concat([header, ...chunks]);
79
+ }
80
+
81
+ async function renderTarget(sharp, source, target) {
82
+ const format = path.extname(target.to).toLowerCase();
83
+ if (format === ".svg") return source;
84
+ const background = target.background;
85
+ const png = async (width, height) => {
86
+ let image = sharp(source, { density: Math.max(72, Math.ceil(Math.max(width, height) * 1.5)) })
87
+ .resize(width, height, { fit: "contain", background: { r: 0, g: 0, b: 0, alpha: 0 } });
88
+ if (background) image = image.flatten({ background });
89
+ return image.png().toBuffer();
90
+ };
91
+ if (format === ".png") return png(target.width ?? target.size, target.height ?? target.size);
92
+ const sizes = [...target.sizes].sort((a, b) => a - b);
93
+ const entries = [];
94
+ for (const size of sizes) entries.push({ size, buffer: await png(size, size) });
95
+ return format === ".ico" ? ico(entries.map(entry => ({ ...entry, size: entry.size === 256 ? 0 : entry.size }))) : icns(entries);
96
+ }
97
+
98
+ /** The glyph set as its generated module, or null without one. */
99
+ export function glyphModule({ dsRoot, config }) {
100
+ const glyphs = config.assets.glyphs;
101
+ if (!glyphs) return null;
102
+ const directory = path.join(dsRoot, glyphs.source);
103
+ const aliasFile = path.join(directory, "aliases.json");
104
+ const aliases = existsSync(aliasFile) ? JSON.parse(readFileSync(aliasFile, "utf8")) : {};
105
+ const attributes = glyphs.attributes ?? {};
106
+ const map = {};
107
+ for (const name of readdirSync(directory).filter(name => name.endsWith(".svg")).sort()) {
108
+ const id = name.slice(0, -4);
109
+ if (Object.hasOwn(aliases, id)) continue;
110
+ const svg = readFileSync(path.join(directory, name), "utf8").replace(/<\?xml[\s\S]*?\?>/g, "").trim()
111
+ .replace(/<svg\b([^>]*)>/, (_match, own) => {
112
+ const missing = Object.entries(attributes).filter(([key]) => !new RegExp(`(?:^|\\s)${key}=`).test(own)).map(([key, value]) => ` ${key}="${value}"`).join("");
113
+ return `<svg${missing}${own}>`;
114
+ });
115
+ map[id] = svg;
116
+ }
117
+ for (const [alias, target] of Object.entries(aliases)) if (!Object.hasOwn(map, target)) throw new Error(`${path.join(glyphs.source, "aliases.json")}: ${alias} names a missing glyph ${target}.`);
118
+ return `// Generated by \`ads assets\` from ${glyphs.source}/. Edit the SVGs, not this file.\n`
119
+ + `export const glyphs = ${JSON.stringify(map, null, 2)} as const;\n`
120
+ + `export const glyphAliases = ${JSON.stringify(aliases, null, 2)} as const;\n`;
121
+ }
122
+
123
+ /** Committed outputs that no longer match their masters, settings or rendered bytes. */
124
+ export function staleBrandOutputs(options) {
125
+ const { root, dsRoot, config } = options;
126
+ const stale = [];
127
+ const recorded = readManifest(dsRoot);
128
+ for (const target of config.assets.targets) {
129
+ const file = path.join(root, target.to);
130
+ const entry = recorded[target.to];
131
+ let reason = null;
132
+ if (!existsSync(file)) reason = "is missing";
133
+ else if (!entry || entry.fingerprint !== fingerprint(dsRoot, target)) reason = `no longer matches ${target.from} or its settings`;
134
+ else if (entry.sha256 !== sha256(readFileSync(file))) reason = "was changed by hand";
135
+ if (reason) stale.push({ file: target.to, message: `${target.to} ${reason}. Run ads assets.` });
136
+ }
137
+ const glyphs = config.assets.glyphs;
138
+ if (glyphs) {
139
+ const file = path.join(dsRoot, glyphs.output);
140
+ let expected;
141
+ try { expected = glyphModule(options); } catch (error) { stale.push({ file: path.relative(root, file), message: error.message }); }
142
+ if (expected !== undefined && (!existsSync(file) || readFileSync(file, "utf8") !== expected)) stale.push({ file: path.relative(root, file).replaceAll("\\", "/"), message: `${glyphs.output} is out of date with ${glyphs.source}/. Run ads assets.` });
143
+ }
144
+ return stale;
145
+ }
146
+
147
+ /** Renders committed targets and the glyph module; unchanged outputs are left alone. */
148
+ async function generateCommitted(options) {
149
+ const { root, dsRoot, config } = options;
150
+ const written = [];
151
+ const recorded = readManifest(dsRoot), next = {};
152
+ let sharp;
153
+ for (const target of config.assets.targets) {
154
+ const file = path.join(root, target.to);
155
+ const print = fingerprint(dsRoot, target);
156
+ const entry = recorded[target.to];
157
+ if (entry?.fingerprint === print && existsSync(file) && entry.sha256 === sha256(readFileSync(file))) { next[target.to] = entry; continue; }
158
+ sharp ??= (await import("sharp")).default;
159
+ const bytes = await renderTarget(sharp, readFileSync(path.join(dsRoot, target.from)), target);
160
+ assertOutput(root, file);
161
+ mkdirSync(path.dirname(file), { recursive: true });
162
+ writeFileSync(file, bytes);
163
+ written.push(file);
164
+ next[target.to] = { from: target.from, fingerprint: print, sha256: sha256(bytes) };
165
+ }
166
+ const manifest = path.join(dsRoot, targetsManifest);
167
+ if (config.assets.targets.length) {
168
+ const sorted = Object.fromEntries(Object.entries(next).sort(([a], [b]) => a.localeCompare(b)));
169
+ const text = `${JSON.stringify({ schemaVersion: 1, outputs: sorted }, null, 2)}\n`;
170
+ if (!existsSync(manifest) || readFileSync(manifest, "utf8") !== text) { writeFileSync(manifest, text); written.push(manifest); }
171
+ } else if (existsSync(manifest)) { rmSync(manifest); written.push(manifest); }
172
+ const glyphs = glyphModule(options);
173
+ if (glyphs !== null) {
174
+ const file = path.join(dsRoot, config.assets.glyphs.output);
175
+ if (!existsSync(file) || readFileSync(file, "utf8") !== glyphs) { assertOutput(root, file); mkdirSync(path.dirname(file), { recursive: true }); writeFileSync(file, glyphs); written.push(file); }
176
+ }
177
+ return written;
178
+ }
179
+
48
180
  export async function generateBrandAssets(directory = process.cwd()) {
49
181
  const options = loadConfig(directory);
50
182
  const { root, dsRoot, config } = options;
51
183
  const output = path.join(root, ".ds/assets");
52
- if (!config.assets.iconSource) return { directory: output, files: [], skipped: true };
184
+ const committed = await generateCommitted(options);
185
+ if (!config.assets.iconSource) return { directory: output, files: [], committed, skipped: !committed.length && !config.assets.targets.length && !config.assets.glyphs };
53
186
  const diagnostic = brandSourceDiagnostic(options);
54
187
  if (diagnostic) throw new Error(`${diagnostic.file} [${diagnostic.rule}] ${diagnostic.message}`);
55
188
  assertOutput(root, output, { directory: true });
@@ -78,5 +211,5 @@ export async function generateBrandAssets(directory = process.cwd()) {
78
211
  mkdirSync(output, { recursive: true });
79
212
  for (const name of brandFiles) renameSync(path.join(staging, name), path.join(output, name));
80
213
  } finally { rmSync(staging, { recursive: true, force: true }); }
81
- return { directory: output, files: brandFiles.map((name) => path.join(output, name)), skipped: false };
214
+ return { directory: output, files: brandFiles.map((name) => path.join(output, name)), committed, skipped: false };
82
215
  }
package/dist/check.mjs CHANGED
@@ -54,7 +54,9 @@ export function checkProject(directory, { trackingRoot } = {}) {
54
54
  const tokenInventory = inspectTokens(root, options);
55
55
  const declaredTokens = new Set(tokenInventory.tokens.map((token) => token.name));
56
56
  diagnostics.push(...tokenInventory.diagnostics);
57
- diagnostics.push(...inspectAssets(options));
57
+ const assetFindings = inspectAssets(options);
58
+ diagnostics.push(...assetFindings.filter(finding => finding.severity !== "warning"));
59
+ const assetAdvisories = assetFindings.filter(finding => finding.severity === "warning");
58
60
  const resolveImport = importResolver(options);
59
61
  const units = inspectUnits(options);
60
62
  options.testOwner = file => units.owner(units.relative(path.relative(root,file)));
@@ -336,7 +338,7 @@ export function checkProject(directory, { trackingRoot } = {}) {
336
338
  inspectDesignAliases(layerStyles,options,report);
337
339
  // Bounded clients should see actionable warnings before source-analysis limits.
338
340
  for (const { file, css, offset } of layerStyles) layers.inspectStyles(file, css, offset);
339
- advisories.push(...(tokenInventory.advisories??[]));
341
+ advisories.push(...(tokenInventory.advisories??[]), ...assetAdvisories);
340
342
  advisories.sort((first, second) => Number(first.severity === "info") - Number(second.severity === "info"));
341
343
  const uniqueDiagnostics=[...new Map(diagnostics.map(diagnostic=>[JSON.stringify([diagnostic.file,diagnostic.rule,diagnostic.line,diagnostic.column,diagnostic.message]),diagnostic])).values()];
342
344
  return architectureEvidence({ ok: uniqueDiagnostics.length === 0, diagnostics:uniqueDiagnostics, ...(advisories.length ? { advisories } : {}) });
package/dist/config.mjs CHANGED
@@ -20,7 +20,7 @@ export const defaultConfig = {
20
20
  tokenDir: "tokens",
21
21
  inlineStyleFiles: [],
22
22
  boundaries: { styleWrites: [], componentVariables: [] },
23
- assets: { publicDirs: ["public/assets"], generatedPaths: ["dist", "dist-showcase", ".vite", ".ds"], generatedFiles: [], iconSource: null },
23
+ assets: { publicDirs: ["public/assets"], generatedPaths: ["dist", "dist-showcase", ".vite", ".ds"], generatedFiles: [], iconSource: null, targets: [], glyphs: null },
24
24
  oxlint: { plugins: [], rules: {}, overrides: [] },
25
25
  acceptance: { checks: [], behaviorChecks: false },
26
26
  validation: { checks: [], behaviorChecks: true, inputs: [] },
@@ -33,6 +33,50 @@ export function isInside(parent, file) {
33
33
  return relative === "" || (!relative.startsWith(`..${path.sep}`) && relative !== ".." && !path.isAbsolute(relative));
34
34
  }
35
35
 
36
+ const iconSizes = [16, 32, 64, 128, 256, 512, 1024];
37
+ /** Committed brand outputs: each renders one SVG master in assets/brand/ to a project path. */
38
+ function validateBrandTargets(targets, { root, dsRoot }) {
39
+ if (!Array.isArray(targets)) throw new Error("assets.targets must be an array.");
40
+ const outputs = new Set();
41
+ for (const [index, target] of targets.entries()) {
42
+ const field = `assets.targets[${index}]`;
43
+ if (!target || typeof target !== "object" || Array.isArray(target)) throw new Error(`${field} must be an object.`);
44
+ const unknown = Object.keys(target).filter(key => !["from", "to", "size", "width", "height", "sizes", "background"].includes(key));
45
+ if (unknown.length) throw new Error(`${field} has unknown keys: ${unknown.join(", ")}.`);
46
+ const source = projectPath(dsRoot, target.from, `${field}.from`);
47
+ if (!isInside(path.join(dsRoot, "assets/brand"), source) || path.extname(source).toLowerCase() !== ".svg") throw new Error(`${field}.from must name an SVG inside the ADS's assets/brand/ folder.`);
48
+ const output = projectPath(root, target.to, `${field}.to`);
49
+ if (isInside(path.join(dsRoot, "assets"), output) || isInside(path.join(root, ".ds"), output)) throw new Error(`${field}.to must be outside the ADS assets/ folder and .ds/.`);
50
+ if (outputs.has(output)) throw new Error(`${field}.to repeats an earlier target's output.`);
51
+ outputs.add(output);
52
+ const format = path.extname(output).toLowerCase();
53
+ const pixels = value => Number.isInteger(value) && value >= 1 && value <= 4096;
54
+ if (target.background !== undefined && (format === ".svg" || typeof target.background !== "string" || !/^#(?:[0-9a-f]{3}|[0-9a-f]{6}|[0-9a-f]{8})$/i.test(target.background))) throw new Error(`${field}.background must be a #RGB, #RRGGBB or #RRGGBBAA colour on a PNG, ICO or ICNS target.`);
55
+ if (format === ".svg") {
56
+ if (["size", "width", "height", "sizes"].some(key => key in target)) throw new Error(`${field} copies its SVG; it takes no sizes.`);
57
+ } else if (format === ".png") {
58
+ const square = target.size !== undefined, rectangle = target.width !== undefined || target.height !== undefined;
59
+ if (square === rectangle || target.sizes !== undefined || (square ? !pixels(target.size) : !pixels(target.width) || !pixels(target.height))) throw new Error(`${field} renders a PNG at one size (1–4096) or one width and height.`);
60
+ } else if (format === ".ico" || format === ".icns") {
61
+ const allowed = format === ".ico" ? [16, 24, 32, 48, 64, 128, 256] : iconSizes;
62
+ if (["size", "width", "height"].some(key => key in target) || !Array.isArray(target.sizes) || !target.sizes.length || new Set(target.sizes).size !== target.sizes.length || target.sizes.some(size => !allowed.includes(size))) throw new Error(`${field}.sizes must list distinct ${format.slice(1).toUpperCase()} sizes from ${allowed.join(", ")}.`);
63
+ } else throw new Error(`${field}.to must end in .svg, .png, .ico or .icns.`);
64
+ }
65
+ }
66
+ /** A glyph set: SVGs in one assets/ folder become one generated TypeScript map. */
67
+ function validateGlyphs(glyphs, { dsRoot }) {
68
+ if (glyphs === null) return;
69
+ if (!glyphs || typeof glyphs !== "object" || Array.isArray(glyphs)) throw new Error("assets.glyphs must be an object or null.");
70
+ const unknown = Object.keys(glyphs).filter(key => !["source", "output", "attributes"].includes(key));
71
+ if (unknown.length) throw new Error(`assets.glyphs has unknown keys: ${unknown.join(", ")}.`);
72
+ const source = projectPath(dsRoot, glyphs.source, "assets.glyphs.source");
73
+ if (!isInside(path.join(dsRoot, "assets"), source) || source === path.join(dsRoot, "assets")) throw new Error("assets.glyphs.source must be a folder inside the ADS's assets/ folder.");
74
+ const output = projectPath(dsRoot, glyphs.output, "assets.glyphs.output");
75
+ if (isInside(path.join(dsRoot, "assets"), output) || path.extname(output) !== ".ts") throw new Error("assets.glyphs.output must be a .ts module in the ADS, outside assets/.");
76
+ const attributes = glyphs.attributes ?? {};
77
+ if (!attributes || typeof attributes !== "object" || Array.isArray(attributes) || Object.entries(attributes).some(([name, value]) => !/^[a-z][a-z0-9-]*$/.test(name) || typeof value !== "string" || /["<>]/.test(value))) throw new Error("assets.glyphs.attributes maps SVG attribute names to plain string values.");
78
+ }
79
+
36
80
  export function projectPath(root, value, field) {
37
81
  if (typeof value !== "string" || !value.trim() || path.isAbsolute(value)) {
38
82
  throw new Error(`${field} must be a non-empty relative path.`);
@@ -124,6 +168,8 @@ export function loadConfig(directory = process.cwd()) {
124
168
  const source = projectPath(dsRoot, config.assets.iconSource, "assets.iconSource");
125
169
  if (!isInside(path.join(dsRoot, "assets/brand"), source) || path.extname(source).toLowerCase() !== ".svg") throw new Error("assets.iconSource must name an SVG inside the ADS's assets/brand/ folder.");
126
170
  }
171
+ validateBrandTargets(config.assets.targets, { root, dsRoot });
172
+ validateGlyphs(config.assets.glyphs, { dsRoot });
127
173
  for (const plugin of config.oxlint.plugins) {
128
174
  if (!plugin || Object.keys(plugin).some((key) => !["name", "path"].includes(key)) || typeof plugin.name !== "string" || !plugin.name || typeof plugin.path !== "string") {
129
175
  throw new Error("Each project Oxlint plugin needs a name and a relative path.");
@@ -259,6 +305,8 @@ export function importViolation(specifier, filename, options, resolve) {
259
305
  : specifier.startsWith(`${config.dsDir}/`) ? [path.resolve(root, specifier)] : [];
260
306
  return imported.some((file) => {
261
307
  if (!isInside(dsRoot, file)) return false;
308
+ // Previews may show the ADS's own artwork and fonts: asset files are data, not implementation.
309
+ if (isDevelopmentFile(filename, options) && isInside(path.join(dsRoot, "assets"), file.replace(/\?[^/\\]*$/, ""))) return false;
262
310
  // Review implementations can reuse local foundation helpers. Resolved public
263
311
  // UI/controller contracts are enforced by the layer inspector, as for patterns.
264
312
  if (isReviewFile(filename, options)) return false;
package/dist/init.mjs CHANGED
@@ -8,6 +8,11 @@ import { assertFrameworkCompiler } from "./ui-framework.mjs";
8
8
 
9
9
  const tool = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
10
10
  const starter = fileURLToPath(new URL("./bootstrap-ds/", import.meta.url));
11
+ /** A framework's starter file: Preact's overlay replaces the React starter's where they differ. */
12
+ const starterFile = (framework, relative) => {
13
+ const overlay = fileURLToPath(new URL(`./bootstrap-ds-${framework}/${relative}`, import.meta.url));
14
+ return framework !== "react" && existsSync(overlay) ? overlay : path.join(starter, relative);
15
+ };
11
16
 
12
17
  function dependencySpec(value) {
13
18
  if (typeof value !== "string" || !value.trim()) throw new Error("toolPackage must be a version or local tool tarball path.");
@@ -151,13 +156,14 @@ export function initProject(directory = process.cwd(), { toolPackage, packageMan
151
156
  return file;
152
157
  });
153
158
  if (!existingTokens.length) {
154
- for (const name of ["Foundation.ads.scenario.tsx", "Foundation.ads.fixture.ts"]) {
159
+ // The starter's token groups, each a scenario with its fixture. Its Brand preview needs
160
+ // the starter's artwork and review renderer, which an existing app brings itself.
161
+ for (const name of readdirSync(path.join(starter, "design-system/tokens")).filter(name => /\.ads\.(?:scenario\.tsx|fixture\.ts)$/.test(name) && !name.startsWith("Brand.")).sort()) {
155
162
  const content = readFileSync(path.join(starter, "design-system/tokens", name), "utf8").replaceAll('"@ds/review"', JSON.stringify(`${config.publicAlias}/review`)).replaceAll('"@ds"', JSON.stringify(config.publicAlias));
156
163
  addMissing(path.join(tokenRoot, name), content);
157
164
  }
158
165
  for (const name of ["TokenPreview.tsx"]) {
159
- let content = readFileSync(path.join(starter, "design-system/review/token-preview", name), "utf8");
160
- if (selectedFramework === "preact") content = content.replace('from "react"', 'from "preact/hooks"');
166
+ const content = readFileSync(starterFile(selectedFramework, `design-system/review/token-preview/${name}`), "utf8");
161
167
  addMissing(path.join(dsRoot, "review/token-preview", name), content.replaceAll('"@ds"', JSON.stringify(config.publicAlias)));
162
168
  }
163
169
  const reviewFile = path.relative(root, path.join(dsRoot, "review/token-preview/TokenPreview.tsx")).replaceAll("\\", "/");
@@ -185,7 +191,11 @@ export function initProject(directory = process.cwd(), { toolPackage, packageMan
185
191
  if (current !== readFileSync(entryFile, "utf8")) updates.set(entryFile, current);
186
192
  }
187
193
  }
188
- for (const section of ["components", "patterns", "controllers", "composition"]) addMissing(path.join(dsRoot, section, ".gitkeep"), "");
194
+ // Keeps a section folder that has nothing in it yet.
195
+ for (const section of ["components", "patterns", "controllers", "composition"]) {
196
+ const directory = path.join(dsRoot, section);
197
+ if (!existsSync(directory) || !readdirSync(directory).length) addMissing(path.join(directory, ".gitkeep"), "");
198
+ }
189
199
  addMissing(path.join(dsRoot, "assets/brand/README.md"), readFileSync(path.join(starter, "design-system/assets/brand/README.md")));
190
200
  addMissing(path.join(dsRoot, "assets/fonts/.gitkeep"), "");
191
201
  const configFile = path.join(root, "ds.config.json");
@@ -199,9 +209,8 @@ export function initProject(directory = process.cwd(), { toolPackage, packageMan
199
209
  updates.set(configFile, `${JSON.stringify({ ...saved, framework: selectedFramework, ...(nativePreviewMissing?{mcp:{...saved.mcp,previewManifest:config.mcp.previewManifest}}:{}), ...(!existingTokens.length ? { boundaries: config.boundaries } : {}) }, null, indent)}\n`);
200
210
  }
201
211
  }
202
- const mount=selectedFramework==="preact"?'import {render} from "preact";':'import {createRoot} from "react-dom/client";';
203
- const render=selectedFramework==="preact"?'render(<Scenario/>,container);return()=>render(null,container);':'const root=createRoot(container);root.render(<Scenario/>);return()=>root.unmount();';
204
- addMissing(path.join(dsRoot,"showcase/mcp/main.tsx"),`import ${JSON.stringify(config.publicAlias)};\n${mount}\nexport function mountScenario(Scenario,container){${render}}\n`);
212
+ // The framework's scenario mount, as the starter has it.
213
+ addMissing(path.join(dsRoot, "showcase/mcp/main.tsx"), readFileSync(starterFile(selectedFramework, "design-system/showcase/mcp/main.tsx"), "utf8").replaceAll('"@ds"', JSON.stringify(config.publicAlias)));
205
214
  const ignoreFile = path.join(root, ".gitignore");
206
215
  assertLocalFile(root, ignoreFile);
207
216
  const ignore = existsSync(ignoreFile) ? readFileSync(ignoreFile, "utf8") : "";
@@ -105,7 +105,7 @@ Boolean requesting whether a visible border and background is provided by the ho
105
105
  - "app": Tool callable by the app from this server only`),csp:Oc().optional(),permissions:Oc().optional()}),Rz=l({mimeTypes:h(s()).optional().describe('Array of supported MIME types for UI resources.\nMust include `"text/html;profile=mcp-app"` for MCP Apps support.')}),xz=l({method:u("ui/download-file"),params:l({contents:h(v([Zt,Dt])).describe("Resource contents to download — embedded (inline data) or linked (host fetches). Uses standard MCP resource types.")})}),Pz=l({method:u("ui/message"),params:l({role:u("user").describe('Message role, currently only "user" is supported.'),content:h(Ce).describe("Message content blocks (text, image, etc.).")})}),Tz=l({method:u("ui/notifications/sandbox-resource-ready"),params:l({html:s().describe("HTML content to load into the inner iframe."),sandbox:s().optional().describe("Optional override for the inner iframe's sandbox attribute."),csp:rl.optional().describe("CSP configuration from resource metadata."),permissions:nl.optional().describe("Sandbox permissions from resource metadata.")})}),__=l({method:u("ui/notifications/tool-result"),params:at.describe("Standard MCP tool execution result.")}),zm=l({toolInfo:l({id:Re.optional().describe("JSON-RPC id of the tools/call request."),tool:it.describe("Tool definition including name, inputSchema, etc.")}).optional().describe("Metadata of the tool call that instantiated this App."),theme:t_.optional().describe("Current color theme preference."),styles:d_.optional().describe("Style configuration for theming the app."),displayMode:Ks.optional().describe("How the UI is currently displayed."),availableDisplayModes:h(Ks).optional().describe("Display modes the host supports."),containerDimensions:v([l({height:_().describe("Fixed container height in pixels.")}),l({maxHeight:v([_(),Ic()]).optional().describe("Maximum container height in pixels.")})]).and(v([l({width:_().describe("Fixed container width in pixels.")}),l({maxWidth:v([_(),Ic()]).optional().describe("Maximum container width in pixels.")})])).optional().describe(`Container dimensions. Represents the dimensions of the iframe or other
106
106
  container holding the app. Specify either width or maxWidth, and either height or maxHeight.`),locale:s().optional().describe("User's language and region preference in BCP 47 format."),timeZone:s().optional().describe("User's timezone in IANA format."),userAgent:s().optional().describe("Host application identifier."),platform:v([u("web"),u("desktop"),u("mobile")]).optional().describe("Platform type for responsive design decisions."),deviceCapabilities:l({touch:z().optional().describe("Whether the device supports touch input."),hover:z().optional().describe("Whether the device supports hover interactions.")}).optional().describe("Device input capabilities."),safeAreaInsets:l({top:_().describe("Top safe area inset in pixels."),right:_().describe("Right safe area inset in pixels."),bottom:_().describe("Bottom safe area inset in pixels."),left:_().describe("Left safe area inset in pixels.")}).optional().describe("Mobile safe area boundaries in pixels.")}).passthrough(),y_=l({method:u("ui/notifications/host-context-changed"),params:zm.describe("Partial context update containing only changed fields.")}),Ez=l({method:u("ui/update-model-context"),params:l({content:h(Ce).optional().describe("Context content blocks (text, image, etc.)."),structuredContent:b(s(),P().describe("Structured content for machine-readable context data.")).optional().describe("Structured content for machine-readable context data.")})}),kz=l({method:u("ui/initialize"),params:l({appInfo:ke.describe("App identification (name and version)."),appCapabilities:f_.describe("Features and capabilities this app provides."),protocolVersion:s().describe("Protocol version this app supports.")})}),b_=l({protocolVersion:s().describe('Negotiated protocol version string (e.g., "2025-11-21").'),hostInfo:ke.describe("Host application identification and version."),hostCapabilities:m_.describe("Features and capabilities provided by the host."),hostContext:zm.describe("Rich context about the host environment.")}).passthrough(),v_={target:"draft-2020-12"};async function Sm(e,t){let o=e["~standard"];if(o.jsonSchema)return o.jsonSchema[t](v_);throw Error(`Schema (vendor: ${o.vendor}) does not implement Standard JSON Schema (~standard.jsonSchema). Use a library that does (zod v4, ArkType, Valibot) or wrap your schema accordingly.`)}async function _m(e,t,o=""){let r=await e["~standard"].validate(t);if(r.issues){let n=r.issues.map((i)=>{let a=i.path?.map((c)=>typeof c==="object"?c.key:c).join(".");return a?`${a}: ${i.message}`:i.message}).join("; ");throw Error(o+n)}return r.value}function z_(e,t){let o={...e,...t};if(t.experimental!==void 0)o.experimental={...e.experimental,...t.experimental};if(t.tools!==void 0)o.tools={...e.tools,...t.tools};return o}class va extends ol{_appInfo;_appCapabilities;options;_hostCapabilities;_hostInfo;_hostContext;_registeredTools={};_initializedSent=!1;_registeredEvents=new Set;_events=new ym;_methods=new bm;setRequestHandler=(...e)=>{let[t,...o]=fm("request",e)??e;this._methods.claim(t,"setRequestHandler"),super.setRequestHandler.call(this,t,...o)};setNotificationHandler=(...e)=>{let[t,...o]=fm("notification",e)??e;this._methods.claim(t,"setNotificationHandler"),super.setNotificationHandler.call(this,t,...o)};removeRequestHandler=(e)=>{this._methods.release(e),super.removeRequestHandler(e)};removeNotificationHandler=(e)=>{this._methods.release(e),super.removeNotificationHandler(e)};replaceRequestHandler=(e,...t)=>{this._methods.replace(e),super.setRequestHandler.call(this,e,...t)};_assertInitialized(e){if(this._initializedSent)return;let t=`[ext-apps] App.${e}() called before connect() completed the ui/initialize handshake. Await app.connect() before calling this method, or move data loading to an ontoolresult handler.`;if(this.options?.strict)throw Error(t);console.warn(`${t}. This will throw in a future release.`)}eventSchemas={toolinput:a_,toolinputpartial:c_,toolresult:__,toolcancelled:l_,hostcontextchanged:y_};static ONE_SHOT_EVENTS=new Set(["toolinput","toolinputpartial","toolresult","toolcancelled"]);_everHadListener=new Set;_assertHandlerTiming(e){if(!va.ONE_SHOT_EVENTS.has(e)||this._everHadListener.has(e))return;if(this._everHadListener.add(e),!this._initializedSent)return;let t=`[ext-apps] "${String(e)}" handler registered after connect() completed the ui/initialize handshake. The host may have already sent this notification. Register handlers before calling app.connect().`;if(this.options?.strict)throw Error(t);console.warn(t)}setEventHandler(e,t){if(t)this._assertHandlerTiming(e);this._ensureEventSlot(e),this._events.setHandler(e,t)}addEventListener(e,t){this._assertHandlerTiming(e),this._ensureEventSlot(e),this._events.addEventListener(e,t)}removeEventListener(e,t){this._events.removeEventListener(e,t)}_ensureEventSlot(e){if(this._registeredEvents.has(e))return;let t=this.eventSchemas[e];if(!t)throw Error(`Unknown event: ${String(e)}`);this.setNotificationHandler(t.shape.method.value,{params:t.shape.params},(o)=>{let r=o;if(e==="hostcontextchanged")this._hostContext={...this._hostContext,...r};this._events.dispatch(e,r)}),this._registeredEvents.add(e)}getEventHandler(e){return this._events.getHandler(e)}warnIfRequestHandlerReplaced(e,t,o){if(t&&o)console.warn(`[MCP Apps] ${e} handler replaced. Previous handler will no longer be called.`)}constructor(e,t={},o={autoResize:!0}){super(o);if(this._appInfo=e,this._appCapabilities=t,this.options=o,this._methods.replace("notifications/cancelled"),this._methods.replace("notifications/progress"),!o.allowUnsafeEval)le({jitless:!0});this.replaceRequestHandler("ping",(r)=>(console.log("Received ping:",r.params),{})),this.setEventHandler("hostcontextchanged",void 0)}buildContext(e){return e}registerAppCapabilities(e){if(this.transport)throw Error("Cannot register capabilities after transport is established");this._appCapabilities=z_(this._appCapabilities,e)}registerTool(e,t,o){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let r=this,n=()=>{if(r._initializedSent&&r._appCapabilities.tools?.listChanged)r.sendToolListChanged()},i=t.inputSchema!==void 0,a={title:t.title,description:t.description,inputSchema:t.inputSchema,outputSchema:t.outputSchema,annotations:t.annotations,_meta:t._meta,enabled:!0,enable(){this.enabled=!0,n()},disable(){this.enabled=!1,n()},update(c){Object.assign(this,c),n()},remove(){if(r._registeredTools[e]!==a)return;delete r._registeredTools[e],n()},handler:async(c,d)=>{if(!a.enabled)throw Error(`Tool ${e} is disabled`);let p;if(i){let m=a.inputSchema,f=m?await _m(m,c??{},`Invalid input for tool ${e}: `):c??{};p=await o(f,d)}else p=await o(d);if(a.outputSchema&&!p.isError)p.structuredContent=await _m(a.outputSchema,p.structuredContent,`Invalid output for tool ${e}: `);return p}};if(this._registeredTools[e]=a,!this._appCapabilities.tools&&!this.transport)this.registerAppCapabilities({tools:{listChanged:!0}});return this.ensureToolHandlersInitialized(),n(),a}_toolHandlersInitialized=!1;ensureToolHandlersInitialized(){if(this._toolHandlersInitialized)return;this._toolHandlersInitialized=!0,this.oncalltool=async(e,t)=>{let o=this._registeredTools[e.name];if(!o)throw Error(`Tool ${e.name} not found`);return o.handler(e.arguments,t)},this.onlisttools=async(e,t)=>({tools:await Promise.all(Object.entries(this._registeredTools).filter(([o,r])=>r.enabled).map(async([o,r])=>{let n={name:o,title:r.title,description:r.description,inputSchema:r.inputSchema?await Sm(r.inputSchema,"input"):{type:"object",properties:{}}};if(r.outputSchema)n.outputSchema=await Sm(r.outputSchema,"output");if(r.annotations)n.annotations=r.annotations;if(r._meta)n._meta=r._meta;return n}))})}async sendToolListChanged(e={}){this._assertInitialized("sendToolListChanged"),await this.notification({method:"notifications/tools/list_changed",params:e})}getHostCapabilities(){return this._hostCapabilities}getHostVersion(){return this._hostInfo}getHostContext(){return this._hostContext}get ontoolinput(){return this.getEventHandler("toolinput")}set ontoolinput(e){this.setEventHandler("toolinput",e)}get ontoolinputpartial(){return this.getEventHandler("toolinputpartial")}set ontoolinputpartial(e){this.setEventHandler("toolinputpartial",e)}get ontoolresult(){return this.getEventHandler("toolresult")}set ontoolresult(e){this.setEventHandler("toolresult",e)}get ontoolcancelled(){return this.getEventHandler("toolcancelled")}set ontoolcancelled(e){this.setEventHandler("toolcancelled",e)}get onhostcontextchanged(){return this.getEventHandler("hostcontextchanged")}set onhostcontextchanged(e){this.setEventHandler("hostcontextchanged",e)}_onteardown;get onteardown(){return this._onteardown}set onteardown(e){this.warnIfRequestHandlerReplaced("onteardown",this._onteardown,e),this._onteardown=e,this.replaceRequestHandler("ui/resource-teardown",{params:p_.shape.params,result:h_},(t,o)=>{if(!this._onteardown)throw Error("No onteardown handler set");return this._onteardown(t,o)})}_oncalltool;get oncalltool(){return this._oncalltool}set oncalltool(e){this.warnIfRequestHandlerReplaced("oncalltool",this._oncalltool,e),this._oncalltool=e,this.replaceRequestHandler("tools/call",(t,o)=>{if(!this._oncalltool)throw Error("No oncalltool handler set");return this._oncalltool(t.params,o)})}_onlisttools;get onlisttools(){return this._onlisttools}set onlisttools(e){this.warnIfRequestHandlerReplaced("onlisttools",this._onlisttools,e),this._onlisttools=e,this.replaceRequestHandler("tools/list",(t,o)=>{if(!this._onlisttools)throw Error("No onlisttools handler set");return this._onlisttools(t.params,o)})}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._hostCapabilities?.sampling)throw Error(`Host does not support sampling (required for ${e})`);break}}assertRequestHandlerCapability(e){switch(e){case"tools/call":case"tools/list":if(!this._appCapabilities.tools)throw Error(`Client does not support tool capability (required for ${e})`);return;default:return}}assertNotificationCapability(e){}async callServerTool(e,t){if(this._assertInitialized("callServerTool"),typeof e==="string")throw Error(`callServerTool() expects an object as its first argument, but received a string ("${e}"). Did you mean: callServerTool({ name: "${e}", arguments: { ... } })?`);return await this.request({method:"tools/call",params:e},{onprogress:()=>{},resetTimeoutOnProgress:!0,...t})}async readServerResource(e,t){return this._assertInitialized("readServerResource"),await this.request({method:"resources/read",params:e},t)}async listServerResources(e,t){return this._assertInitialized("listServerResources"),await this.request({method:"resources/list",params:e},t)}async createSamplingMessage(e,t){return this._assertInitialized("createSamplingMessage"),await this.request({method:"sampling/createMessage",params:e},t)}sendMessage(e,t){return this._assertInitialized("sendMessage"),this.request({method:"ui/message",params:e},i_,t)}sendLog(e){return this.notification({method:"notifications/message",params:e})}updateModelContext(e,t){return this._assertInitialized("updateModelContext"),this.request({method:"ui/update-model-context",params:e},st,t)}openLink(e,t){return this._assertInitialized("openLink"),this.request({method:"ui/open-link",params:e},n_,t)}sendOpenLink=this.openLink;downloadFile(e,t){return this._assertInitialized("downloadFile"),this.request({method:"ui/download-file",params:e},s_,t)}requestTeardown(e={}){return this.notification({method:"ui/notifications/request-teardown",params:e})}requestDisplayMode(e,t){return this._assertInitialized("requestDisplayMode"),this.request({method:"ui/request-display-mode",params:e},g_,t)}sendSizeChanged(e){return this.notification({method:"ui/notifications/size-changed",params:e})}setupSizeChangedNotifications(){let e=!1,t=0,o=0,r=()=>{if(e)return;e=!0,requestAnimationFrame(()=>{e=!1;let i=document.documentElement,a=i.style.height;i.style.height="max-content";let c=Math.ceil(i.getBoundingClientRect().height);i.style.height=a;let d=Math.ceil(window.innerWidth);if(d!==t||c!==o)t=d,o=c,this.sendSizeChanged({width:d,height:c})})};r();let n=new ResizeObserver(r);return n.observe(document.documentElement),n.observe(document.body),()=>n.disconnect()}async connect(e=new vm(window.parent,window.parent),t){if(this.transport)throw Error("App is already connected. Call close() before connecting again.");this._initializedSent=!1;try{await super.connect(e);let o=await this.request({method:"ui/initialize",params:{appCapabilities:this._appCapabilities,appInfo:this._appInfo,protocolVersion:XS}},b_,t);if(o===void 0)throw Error(`Server sent invalid initialize result: ${o}`);if(this._hostCapabilities=o.hostCapabilities,this._hostInfo=o.hostInfo,this._hostContext=o.hostContext,await this.notification({method:"ui/notifications/initialized"}),this._initializedSent=!0,this.options?.autoResize)this.setupSizeChangedNotifications()}catch(o){throw this.close(),o}}}function wm(e,t){let o=[],r=new Set;function n(i){if(r.has(i))return;r.add(i);let a=e.get(i);if(!a)throw Error(`Missing preview dependency metadata: ${i}`);for(let c of[...a.imports,...a.styles,...a.references])n(c);o.push(i)}return n(t),o}function Rm(e,t){if(!e||e.revision===t.revision)return[];let o=(r,n)=>{let i=new Map(Object.entries(r.assets));return JSON.stringify(wm(i,n.module).map((a)=>[a,i.get(a)]))};return t.scenarios.filter((r)=>{let n=e.scenarios.find((i)=>i.id===r.id);return!n||o(e,n)!==o(t,r)}).map((r)=>r.id)}class sl{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.importing=Promise.resolve(),this.generation=0,this.prefetchGeneration=0,this.closed=!1,globalThis.__dsPreviewImport=(t)=>this.importModule(t)}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.");for(let[t,o]of Object.entries(e.assets)){if(!/^ads:\/\/assets\/[a-f0-9]{64}\.[a-z0-9]+$/.test(t)||!/^sha256:[a-f0-9]{64}$/.test(o.digest)||!["imports","dynamicImports","styles","references"].every((r)=>Array.isArray(o[r])&&o[r].every((n)=>Object.hasOwn(e.assets,n))))throw Error("Invalid preview dependency graph.");if(this.records.has(t)&&this.records.get(t).digest!==o.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:t})}for(let[t,o]of Object.entries(e.assets))this.records.set(t,o)}async resource(e){if(!this.bytes.has(e)){let t=(async()=>{let o=this.records.get(e);if(!o)throw Error(`Unknown preview dependency: ${e}`);let r;try{r=await this.read(e)}catch(d){throw Object.assign(Error(`Preview resource read failed for ${e}: ${d.message}`,{cause:d}),{code:"ADS_RESOURCE_READ",category:"transport",resourceUri:e})}if(this.closed)throw Error("The preview App was closed.");let n=r.contents.find((d)=>d.uri===e);if(!n)throw Object.assign(Error(`Missing preview dependency: ${e}`),{code:"ADS_RESOURCE_CONTENT",category:"build",resourceUri:e});let i=typeof n.text==="string"?new TextEncoder().encode(n.text):Uint8Array.from(atob(n.blob),(d)=>d.charCodeAt(0)),a=await crypto.subtle.digest("SHA-256",i),c="sha256:"+[...new Uint8Array(a)].map((d)=>d.toString(16).padStart(2,"0")).join("");if(i.length!==o.size||c!==o.digest)throw Object.assign(Error("Preview resource integrity check failed. Rebuild and reopen the preview."),{code:"ADS_RESOURCE_INTEGRITY",category:"build",resourceUri:e});return i})();this.bytes.set(e,t),t.catch(()=>this.bytes.delete(e))}return this.bytes.get(e)}closure(e){return wm(this.records,e)}async prefetch(e,t){if(this.closed)return;this.register(e);let o=++this.prefetchGeneration,r=new Set,n=[],i=0;for(let p of t){let m=e.scenarios.find((S)=>S.id===p);if(!m)continue;let f=this.closure(m.module).filter((S)=>!this.bytes.has(S)&&!r.has(S)),y=f.reduce((S,w)=>S+this.records.get(w).size,0);if(i+y>16777216||r.size+f.length>256)continue;i+=y,n.push(p);for(let S of f)r.add(S)}let a=[...r],c=0,d=async()=>{while(!this.closed&&o===this.prefetchGeneration&&c<a.length)await this.resource(a[c++])};return await Promise.all(Array.from({length:Math.min(3,a.length)},d)),{scenarios:n,resources:a.length}}async materialize(e){let t=this.closure(e);await Promise.all(t.map((r)=>this.resource(r)));let o={};for(let r of t){if(this.closed)throw Error("The preview App was closed.");if(this.urls.has(r))continue;let n=this.records.get(r),i=await this.resource(r);if(n.kind==="module"||n.mimeType==="text/css"||n.mimeType==="text/javascript"){let c=new TextDecoder().decode(i);for(let d of n.references){let p=this.urls.get(d);if(!p)throw Error("Unsupported cyclic asset reference.");c=c.replaceAll(d,p)}i=c}let a=URL.createObjectURL(new Blob([i],{type:n.mimeType}));if(this.urls.set(r,a),n.kind==="module")o[r]=a}if(Object.keys(o).length){let r=document.createElement("script");r.type="importmap",r.textContent=JSON.stringify({imports:o}),document.head.append(r)}return t}async importModule(e){let t=this.importing.then(()=>this.materialize(e));this.importing=t.catch(()=>{});let o=await t;await this.attachStyles(o);try{let r=await import(e);return this.loadedModules.add(e),r}catch(r){throw Error(`Preview module import failed for ${e}: ${r.message}. Inspect the App resource bridge, browser network/CSP diagnostics and current build.`,{cause:r})}}async attachStyles(e){for(let t of e){if(this.records.get(t).mimeType!=="text/css")continue;if(this.styles.has(t)){await this.styleReady.get(t);continue}let r=document.createElement("link");r.rel="stylesheet",r.href=this.urls.get(t),this.styles.set(t,r);let n=new Promise((i,a)=>{r.onload=i,r.onerror=()=>a(Error("The host CSP blocked a preview stylesheet."))});this.styleReady.set(t,n),document.head.append(r);try{await n}catch(i){throw r.remove(),this.styles.delete(t),this.styleReady.delete(t),i}}}async refreshStyles(e,t){let o=[e],r=new Set,n=new Set;for(let i=0;i<o.length;i++){let a=o[i];if(r.has(a))continue;r.add(a);for(let c of await this.materialize(a)){n.add(c);for(let d of this.records.get(c).dynamicImports)if(this.loadedModules.has(d))o.push(d)}}if(await this.attachStyles([...n]),t!==this.generation||this.closed)return!1;for(let[i,a]of this.styles)if(!n.has(i))a.remove(),this.styles.delete(i),this.styleReady.delete(i);for(let i of n)if(this.styles.has(i))document.head.append(this.styles.get(i));return!0}async mount(e,t,o){let r=++this.generation;this.register(e);let n=e.scenarios.find((d)=>d.id===t);if(!n)throw Error("The selected scenario is no longer registered.");let i=JSON.stringify(this.closure(n.module).map((d)=>[d,this.records.get(d)]));if(this.mounted?.id===t&&this.mounted.container===o&&this.mounted.signature===i)return this.refreshStyles(n.module,r);if(this.revisions.add(n.module),this.revisions.size>20)throw Object.assign(Error("Reopen the preview to release modules retained across 20 build revisions."),{code:"ADS_PREVIEW_REOPEN"});let a=await this.importModule(n.module);if(r!==this.generation)return!1;let c=this.unmount;if(this.unmount=void 0,this.mounted=void 0,await c?.(),r!==this.generation||this.closed)return!1;if(o.replaceChildren(),!await this.refreshStyles(n.module,r))return!1;if(typeof a.mount!=="function")throw Error("The compiled scenario has no mount adapter.");if(this.unmount=a.mount(o),typeof this.unmount!=="function")throw Error("The scenario mount adapter must return an unmount callback.");return this.mounted={id:t,container:o,signature:i},!0}async dispose(){if(this.closed)return;this.closed=!0,++this.generation,++this.prefetchGeneration,await this.unmount?.(),this.mounted=void 0;for(let e of this.styles.values())e.remove();for(let e of this.urls.values())URL.revokeObjectURL(e);this.styles.clear(),this.styleReady.clear(),this.urls.clear(),this.bytes.clear(),this.records.clear(),this.revisions.clear(),this.loadedModules.clear(),delete globalThis.__dsPreviewImport}}function xm(e){return Array.isArray(e)&&e.length>0&&e.every((t)=>t&&typeof t==="object"&&typeof t.token==="string"&&/^--[\w-]+$/.test(t.token)&&typeof t.property==="string"&&/^-?[a-z][a-z0-9-]*$/.test(t.property)&&typeof t.probe==="string"&&t.probe.trim().length>0)&&new Set(e.map((t)=>`${t.token}:${t.property}`)).size===e.length}function Pm(e,t){let o=t.getComputedStyle(e),r=e.getBoundingClientRect();if(o.display==="none"||o.visibility!=="visible"||!e.getClientRects().length||!(r.width||r.height))return!1;for(let n=e;n;n=n.parentElement)if(Number(t.getComputedStyle(n).opacity)===0)return!1;return!0}function Tm(e,t){if(!xm(t))return{ok:!1,diagnostics:["Token preview needs explicit { token, property, probe } samples from the project fixture. Rebuild with the current compiler."]};let o=e.ownerDocument,{defaultView:r,documentElement:n}=o,i=[],a=[],c=[...e.querySelectorAll("[data-ads-token], [data-ads-property]")],d=new Set(t.map((p)=>`${p.token}:${p.property}`));for(let p of c)if(!d.has(`${p.dataset.adsToken}:${p.dataset.adsProperty}`))i.push(`Undeclared rendered token sample ${p.dataset.adsToken}:${p.dataset.adsProperty}.`);for(let p of t){if(!r.CSS.supports(p.property,p.probe)){i.push(`${p.token}: the fixture probe is invalid for ${p.property}.`);continue}let m=r.getComputedStyle(n).getPropertyValue(p.token).trim();if(!m||!r.CSS.supports(p.property,m)){i.push(`${p.token}: its current value is invalid for the fixture's ${p.property} binding.`);continue}let f=c.filter((S)=>S.dataset.adsToken===p.token&&S.dataset.adsProperty===p.property);if(!f.length){i.push(`${p.token} needs a rendered ${p.property} sample, not only a name/value label.`);continue}let y=!1;for(let S of f){let w=[];for(let C=S.parentElement;C&&C!==e;C=C.parentElement)if(C.tagName==="DETAILS"&&!C.open)C.open=!0,w.push(C);let x=n.getAttribute("style"),R=S.getAttribute("style");try{if(!/^(?:-[a-z]+-)?transition(?:-|$)/.test(p.property))S.style.setProperty("transition","none","important");let C=r.getComputedStyle(S).getPropertyValue(p.property),N=Pm(S,r);n.style.setProperty(p.token,p.probe,"important");let O=r.getComputedStyle(S).getPropertyValue(p.property);y=Boolean(O&&O!==C&&(N||Pm(S,r)))}finally{if(x===null)n.removeAttribute("style");else n.setAttribute("style",x);if(R===null)S.removeAttribute("style");else S.setAttribute("style",R);for(let C of w)C.open=!1}if(y)break}if(y)a.push(p);else i.push(`${p.token} has no visible ${p.property} sample that responds to its value. Hardcoded copies do not satisfy coverage.`)}return{ok:!i.length,verified:a,diagnostics:i}}function Em({container:e=document.getElementById("root"),bindings:t=[],auditResources:o=!1}={}){let r=[],n=[],i=[];if(!e||!Array.isArray(t)||t.length>100)return{ok:!1,diagnostics:["Invalid bounded paint-audit descriptor."],verified:n};let a=e.ownerDocument,c=a.defaultView,d=["color","fill","stroke","stop-color","background-color","border-top-color","border-right-color","border-bottom-color","border-left-color"];function p(f,y,S,w=new Set){if(f=f.trim(),["none","currentColor"].includes(f))return!0;let x=/^var\(\s*(--[\w-]+)\s*\)$/.exec(f);if(x){let N=x[1];if(!S.tokens.includes(N)||w.has(N))return!1;let O=c.getComputedStyle(y).getPropertyValue(N).trim();return!!O&&c.CSS.supports("color",O)}let R=/^light-dark\(\s*(var\(\s*--[\w-]+\s*\)|currentColor)\s*,\s*(var\(\s*--[\w-]+\s*\)|currentColor)\s*\)$/.exec(f);if(R)return c.CSS.supports("color",f)&&p(R[1],y,S,w)&&p(R[2],y,S,w);let C=/^url\(\s*(["']?)#([^\s"'()#\\\p{Cc}]+)\1\s*\)$/u.exec(f);if(C&&c.CSS.supports("fill",f)){let N=[...a.querySelectorAll("[id]")].filter((O)=>O.id===C[2]);return N.length===1&&["linearGradient","radialGradient","pattern"].includes(N[0].localName)&&y.contains(N[0])}return!1}for(let f of t){if(!f||typeof f.scope!=="string"||!Array.isArray(f.tokens)||typeof f.prefix!=="string"||typeof f.suffix!=="string"){r.push("Invalid paint binding metadata; rebuild previews.");continue}let y;try{y=[...e.querySelectorAll(f.scope)]}catch{r.push(`${f.owner}: invalid binding scope.`);continue}if(y.length>20)i.push(`${f.owner}: only the first 20 instances were audited; use a focused scenario for complete evidence.`);for(let S of y.slice(0,20)){let w=[S,...S.querySelectorAll("*")];if(w.length>1000){i.push(`${f.owner}: instance exceeds 1000 elements; paint effects are not established.`);continue}let x=[...S.style].filter((R)=>R.startsWith(f.prefix)&&R.endsWith(f.suffix));if(x.length>100)i.push(`${f.owner}: only the first 100 binding keys were audited.`);for(let R of x.slice(0,100)){let C=S.style.getPropertyValue(R).trim(),N=R.slice(f.prefix.length,f.suffix?-f.suffix.length:void 0);if(!/^[A-Za-z0-9_-]+$/.test(N)||!p(C,S,f)){r.push(`${f.owner}: invalid or inaccessible paint ${R}: ${C}. Use an accessible token, instance-local SVG paint server, none or currentColor.`);continue}let O=S.getAttribute("style"),q=w.map((L)=>L.getAttribute("style"));try{for(let V of w)V.style.setProperty("transition","none","important");let L=w.map((V)=>d.map((ae)=>c.getComputedStyle(V).getPropertyValue(ae)));S.style.setProperty(R,"rgb(17, 103, 211)","important");let j=w.some((V,ae)=>d.some((Y,ge)=>c.getComputedStyle(V).getPropertyValue(Y)!==L[ae][ge]));if(!j)S.style.setProperty(R,"rgb(211, 67, 23)","important"),j=w.some((V,ae)=>d.some((Y,ge)=>c.getComputedStyle(V).getPropertyValue(Y)!==L[ae][ge]));if(!j)i.push(`${f.owner}: ${R} 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:f.owner,binding:f.name,variable:R})}finally{if(w.forEach((L,j)=>{if(q[j]===null)L.removeAttribute("style");else L.setAttribute("style",q[j])}),O===null)S.removeAttribute("style");else S.setAttribute("style",O)}}for(let R of w)for(let C of["fill","stroke","stop-color"]){let N=R.getAttribute(C);if(!N)continue;let O=/^var\(\s*(--[\w-]+)\s*\)$/.exec(N);if(O&&O[1].startsWith(f.prefix)&&O[1].endsWith(f.suffix)&&!x.includes(O[1]))r.push(`${f.owner}: ${O[1]} is consumed without a value in this instance.`);if(N.startsWith("url(")&&!p(N,S,f))r.push(`${f.owner}: missing, duplicated or out-of-instance local paint resource ${N}.`)}}}let m=o?[...e.querySelectorAll("[fill], [stroke], [style]")]:[];if(m.length>1000)i.push("Only the first 1000 potential SVG paint consumers were audited.");for(let f of m.slice(0,1000))for(let y of["fill","stroke"]){let S=f.getAttribute(y)??f.style.getPropertyValue(y);if(!S?.startsWith("url("))continue;let w=/^url\(\s*(["']?)#([^\s"'()#\\\p{Cc}]+)\1\s*\)$/u.exec(S)?.[2],x=w?[...a.querySelectorAll("[id]")].filter((C)=>C.id===w):[],R=f.ownerSVGElement??(f.localName==="svg"?f:null);if(x.length!==1||!R?.contains(x[0])||!["linearGradient","radialGradient","pattern"].includes(x[0]?.localName))r.push(`Invalid, missing, duplicated or nonlocal SVG paint resource ${S}. Keep IDs isolated per rendered instance.`)}return{ok:!r.length,complete:!i.length,verified:n,diagnostics:r.slice(0,40),limits:i.slice(0,20),scope:"observed App instances and current input; repeat after updates"}}var ye=new va({name:"ADS resource preview",version:"1.0.0"},{},{autoResize:!0}),Bt=document.getElementById("root"),il=document.getElementById("ads-preview-status"),ll,pl=async(e)=>{if(!ye.getHostCapabilities()?.serverResources)throw Error("This host does not forward MCP resource reads. Open the same preview in the ADS showcase.");try{return await ye.readServerResource({uri:ll?ll+encodeURIComponent(e):e},{timeout:15000})}catch(t){if(t.code===-32601||t.message==="Method not found")throw Error("This host does not forward MCP resource reads. Open the same preview in the ADS showcase.");throw t}},ei=new sl(pl),He,$m,Gt,ul,hl,al=!1,lt=0,Ys={},_e="",Qs=!1,cl,km,Cm=new Set;function Im(e){if(ye.getHostVersion()?.name!=="ADS showcase")return;let t=km;if(km=e,!t)return;let o=Rm(t,e).filter((r)=>r!==He&&Cm.has(r));if(!o.length)return;ei.prefetch(e,o).then((r)=>ut("prefetched",{revision:e.revision,...r})).catch((r)=>console.warn("ADS preview prefetch",r.message))}function Oe(e,t=!1){il.textContent=e,il.hidden=!e||ye.getHostVersion()?.name==="ADS showcase",il.setAttribute("role",t?"alert":"status")}async function ut(e,t={}){try{if(ye.getHostCapabilities()?.logging)await ye.sendLog({level:e==="error"?"error":"info",logger:"ads-preview",data:{state:e,id:He,...t}})}catch{}}function Om(e){if(Ys={...Ys,...e,styles:{...Ys.styles,...e.styles}},["light","dark"].includes(Ys.theme))document.documentElement.dataset.theme=Ys.theme}async function dl(e="ads://preview/manifest"){let t;try{t=await pl(e)}catch(o){throw Object.assign(Error(o.message,{cause:o}),{code:"ADS_MANIFEST_READ",category:"transport"})}return JSON.parse(t.contents.find((o)=>typeof o.text==="string").text)}async function Xs(e,t,o=!1,r="",n=!1){let i=o||n;if(!r&&e===He&&t&&t===Gt&&i===Qs){Oe(_e||(i?"Checking changes…":""),Boolean(_e)),await ut(_e?"error":i?"checking":"ready",_e?{message:_e}:{revision:Gt});return}let a=++lt;++ei.generation,He=e,Cm.add(e),document.documentElement.dataset.adsScenario=e,document.documentElement.dataset.adsPreviewState="loading";for(let c of["adsPreviewErrorCategory","adsPreviewErrorCode","adsPreviewResourceUri"])delete document.documentElement.dataset[c];_e="",Oe(""),await ut(r?"reverting":"loading");try{let c=await dl(o?"ads://preview/live":"ads://preview/manifest");if(t&&c.revision!==t){if(a===lt)Oe("Updating preview…"),await ut("loading",{code:"ADS_PREVIEW_CHANGED"});return}if(a!==lt)return;if(!await ei.mount(c,e,Bt)||a!==lt)return;if(Gt=c.revision,ul=c.session,Qs=i,await new Promise((m)=>requestAnimationFrame(()=>requestAnimationFrame(m))),await document.fonts.ready,a!==lt)return;let p=c.scenarios.find((m)=>m.id===e);if(Bt.dataset.adsPaintBindings=JSON.stringify(p?.paintBindings??[]),Bt.dataset.adsPaintAudit=String(Boolean(p?.paintAudit)),Bt.dataset.adsPaintAuditComplete="not-requested",p?.paintBindings?.length||p?.paintAudit){let m=Em({container:Bt,bindings:p.paintBindings??[],auditResources:Boolean(p.paintAudit)});if(!m.ok)throw Object.assign(Error(`Paint binding verification failed:
107
107
  ${m.diagnostics.join(`
108
- `)}`),{code:"ADS_PAINT_BINDING",category:"assertion"});if(Bt.dataset.adsPaintAuditComplete=String(m.complete),!m.complete)await ut("audit-limited",{limits:m.limits})}if(p?.kind==="tokens"){let m=Tm(Bt,p.samples);if(!m.ok)throw _e=`Token preview verification failed:
108
+ `)}`),{code:"ADS_PAINT_BINDING",category:"assertion"});if(Bt.dataset.adsPaintAuditComplete=String(m.complete),!m.complete)await ut("audit-limited",{limits:m.limits})}if(p?.kind==="tokens"&&!p.brand){let m=Tm(Bt,p.samples);if(!m.ok)throw _e=`Token preview verification failed:
109
109
  ${m.diagnostics.slice(0,20).join(`
110
110
  `)}`,Object.assign(Error(_e),{code:"ADS_TOKEN_SAMPLE",category:"assertion"})}if(a===lt){if(document.documentElement.dataset.adsPreviewRevision=Gt,document.documentElement.dataset.adsPreviewState=r?"error":i?"checking":"ready",Oe(r||(i?"Checking changes…":""),Boolean(r)),await ut(r?"error":i?"checking":"ready",{revision:Gt,selectionRevision:$m,...r?{message:r}:{}}),!i&&!r)Im(c)}}catch(c){if(a===lt){if(document.documentElement.dataset.adsPreviewState="error",document.documentElement.dataset.adsPreviewErrorCategory=c.category??"runner",document.documentElement.dataset.adsPreviewErrorCode=c.code??"ADS_PREVIEW_STARTUP",c.resourceUri)document.documentElement.dataset.adsPreviewResourceUri=c.resourceUri;Oe(c.message,!0),await ut("error",{message:c.message,...c.code?{code:c.code}:{},...c.category?{category:c.category}:{},...c.resourceUri?{resourceUri:c.resourceUri}:{}})}}}async function w_(){if(!He||al||document.visibilityState==="hidden")return;al=!0;try{let e=JSON.parse((await pl("ads://project/build")).contents.find((o)=>typeof o.text==="string").text);cl=void 0;let t=e.previews.find((o)=>o.id===He);if(t?.live&&!t.current)if(t.live.revision!==Gt||e.session!==ul||!Qs)await Xs(He,t.live.revision,!0);else Oe(_e||"Checking changes…",Boolean(_e));else if(!t||!t.current){let o=t?.diagnostics?.[0]?.message;if(o&&Qs){let r=await dl();await Xs(He,r.revision,!1,`Build failed. Showing the previous preview.
111
111
  ${o}`)}Oe(o?`Build failed. Showing the previous preview.
@@ -105,7 +105,7 @@ Boolean requesting whether a visible border and background is provided by the ho
105
105
  - "app": Tool callable by the app from this server only`),csp:vc().optional(),permissions:vc().optional()}),Xz=l({mimeTypes:h(s()).optional().describe('Array of supported MIME types for UI resources.\nMust include `"text/html;profile=mcp-app"` for MCP Apps support.')}),ev=l({method:u("ui/download-file"),params:l({contents:h(z([qt,At])).describe("Resource contents to download — embedded (inline data) or linked (host fetches). Uses standard MCP resource types.")})}),tv=l({method:u("ui/message"),params:l({role:u("user").describe('Message role, currently only "user" is supported.'),content:h(Te).describe("Message content blocks (text, image, etc.).")})}),ov=l({method:u("ui/notifications/sandbox-resource-ready"),params:l({html:s().describe("HTML content to load into the inner iframe."),sandbox:s().optional().describe("Optional override for the inner iframe's sandbox attribute."),csp:Jc.optional().describe("CSP configuration from resource metadata."),permissions:Bc.optional().describe("Sandbox permissions from resource metadata.")})}),WS=l({method:u("ui/notifications/tool-result"),params:rt.describe("Standard MCP tool execution result.")}),om=l({toolInfo:l({id:ye.optional().describe("JSON-RPC id of the tools/call request."),tool:ot.describe("Tool definition including name, inputSchema, etc.")}).optional().describe("Metadata of the tool call that instantiated this App."),theme:CS.optional().describe("Current color theme preference."),styles:ZS.optional().describe("Style configuration for theming the app."),displayMode:Vs.optional().describe("How the UI is currently displayed."),availableDisplayModes:h(Vs).optional().describe("Display modes the host supports."),containerDimensions:z([l({height:g().describe("Fixed container height in pixels.")}),l({maxHeight:z([g(),zc()]).optional().describe("Maximum container height in pixels.")})]).and(z([l({width:g().describe("Fixed container width in pixels.")}),l({maxWidth:z([g(),zc()]).optional().describe("Maximum container width in pixels.")})])).optional().describe(`Container dimensions. Represents the dimensions of the iframe or other
106
106
  container holding the app. Specify either width or maxWidth, and either height or maxHeight.`),locale:s().optional().describe("User's language and region preference in BCP 47 format."),timeZone:s().optional().describe("User's timezone in IANA format."),userAgent:s().optional().describe("Host application identifier."),platform:z([u("web"),u("desktop"),u("mobile")]).optional().describe("Platform type for responsive design decisions."),deviceCapabilities:l({touch:v().optional().describe("Whether the device supports touch input."),hover:v().optional().describe("Whether the device supports hover interactions.")}).optional().describe("Device input capabilities."),safeAreaInsets:l({top:g().describe("Top safe area inset in pixels."),right:g().describe("Right safe area inset in pixels."),bottom:g().describe("Bottom safe area inset in pixels."),left:g().describe("Left safe area inset in pixels.")}).optional().describe("Mobile safe area boundaries in pixels.")}).passthrough(),GS=l({method:u("ui/notifications/host-context-changed"),params:om.describe("Partial context update containing only changed fields.")}),rv=l({method:u("ui/update-model-context"),params:l({content:h(Te).optional().describe("Context content blocks (text, image, etc.)."),structuredContent:y(s(),R().describe("Structured content for machine-readable context data.")).optional().describe("Structured content for machine-readable context data.")})}),nv=l({method:u("ui/initialize"),params:l({appInfo:xe.describe("App identification (name and version)."),appCapabilities:FS.describe("Features and capabilities this app provides."),protocolVersion:s().describe("Protocol version this app supports.")})}),KS=l({protocolVersion:s().describe('Negotiated protocol version string (e.g., "2025-11-21").'),hostInfo:xe.describe("Host application identification and version."),hostCapabilities:HS.describe("Features and capabilities provided by the host."),hostContext:om.describe("Rich context about the host environment.")}).passthrough(),YS={target:"draft-2020-12"};async function Yh(e,t){let o=e["~standard"];if(o.jsonSchema)return o.jsonSchema[t](YS);throw Error(`Schema (vendor: ${o.vendor}) does not implement Standard JSON Schema (~standard.jsonSchema). Use a library that does (zod v4, ArkType, Valibot) or wrap your schema accordingly.`)}async function Qh(e,t,o=""){let r=await e["~standard"].validate(t);if(r.issues){let n=r.issues.map((i)=>{let a=i.path?.map((c)=>typeof c==="object"?c.key:c).join(".");return a?`${a}: ${i.message}`:i.message}).join("; ");throw Error(o+n)}return r.value}function QS(e,t){let o={...e,...t};if(t.experimental!==void 0)o.experimental={...e.experimental,...t.experimental};if(t.tools!==void 0)o.tools={...e.tools,...t.tools};return o}class ua extends Fc{_appInfo;_appCapabilities;options;_hostCapabilities;_hostInfo;_hostContext;_registeredTools={};_initializedSent=!1;_registeredEvents=new Set;_events=new Xh;_methods=new em;setRequestHandler=(...e)=>{let[t,...o]=Gh("request",e)??e;this._methods.claim(t,"setRequestHandler"),super.setRequestHandler.call(this,t,...o)};setNotificationHandler=(...e)=>{let[t,...o]=Gh("notification",e)??e;this._methods.claim(t,"setNotificationHandler"),super.setNotificationHandler.call(this,t,...o)};removeRequestHandler=(e)=>{this._methods.release(e),super.removeRequestHandler(e)};removeNotificationHandler=(e)=>{this._methods.release(e),super.removeNotificationHandler(e)};replaceRequestHandler=(e,...t)=>{this._methods.replace(e),super.setRequestHandler.call(this,e,...t)};_assertInitialized(e){if(this._initializedSent)return;let t=`[ext-apps] App.${e}() called before connect() completed the ui/initialize handshake. Await app.connect() before calling this method, or move data loading to an ontoolresult handler.`;if(this.options?.strict)throw Error(t);console.warn(`${t}. This will throw in a future release.`)}eventSchemas={toolinput:AS,toolinputpartial:jS,toolresult:WS,toolcancelled:LS,hostcontextchanged:GS};static ONE_SHOT_EVENTS=new Set(["toolinput","toolinputpartial","toolresult","toolcancelled"]);_everHadListener=new Set;_assertHandlerTiming(e){if(!ua.ONE_SHOT_EVENTS.has(e)||this._everHadListener.has(e))return;if(this._everHadListener.add(e),!this._initializedSent)return;let t=`[ext-apps] "${String(e)}" handler registered after connect() completed the ui/initialize handshake. The host may have already sent this notification. Register handlers before calling app.connect().`;if(this.options?.strict)throw Error(t);console.warn(t)}setEventHandler(e,t){if(t)this._assertHandlerTiming(e);this._ensureEventSlot(e),this._events.setHandler(e,t)}addEventListener(e,t){this._assertHandlerTiming(e),this._ensureEventSlot(e),this._events.addEventListener(e,t)}removeEventListener(e,t){this._events.removeEventListener(e,t)}_ensureEventSlot(e){if(this._registeredEvents.has(e))return;let t=this.eventSchemas[e];if(!t)throw Error(`Unknown event: ${String(e)}`);this.setNotificationHandler(t.shape.method.value,{params:t.shape.params},(o)=>{let r=o;if(e==="hostcontextchanged")this._hostContext={...this._hostContext,...r};this._events.dispatch(e,r)}),this._registeredEvents.add(e)}getEventHandler(e){return this._events.getHandler(e)}warnIfRequestHandlerReplaced(e,t,o){if(t&&o)console.warn(`[MCP Apps] ${e} handler replaced. Previous handler will no longer be called.`)}constructor(e,t={},o={autoResize:!0}){super(o);if(this._appInfo=e,this._appCapabilities=t,this.options=o,this._methods.replace("notifications/cancelled"),this._methods.replace("notifications/progress"),!o.allowUnsafeEval)ce({jitless:!0});this.replaceRequestHandler("ping",(r)=>(console.log("Received ping:",r.params),{})),this.setEventHandler("hostcontextchanged",void 0)}buildContext(e){return e}registerAppCapabilities(e){if(this.transport)throw Error("Cannot register capabilities after transport is established");this._appCapabilities=QS(this._appCapabilities,e)}registerTool(e,t,o){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let r=this,n=()=>{if(r._initializedSent&&r._appCapabilities.tools?.listChanged)r.sendToolListChanged()},i=t.inputSchema!==void 0,a={title:t.title,description:t.description,inputSchema:t.inputSchema,outputSchema:t.outputSchema,annotations:t.annotations,_meta:t._meta,enabled:!0,enable(){this.enabled=!0,n()},disable(){this.enabled=!1,n()},update(c){Object.assign(this,c),n()},remove(){if(r._registeredTools[e]!==a)return;delete r._registeredTools[e],n()},handler:async(c,p)=>{if(!a.enabled)throw Error(`Tool ${e} is disabled`);let d;if(i){let f=a.inputSchema,S=f?await Qh(f,c??{},`Invalid input for tool ${e}: `):c??{};d=await o(S,p)}else d=await o(p);if(a.outputSchema&&!d.isError)d.structuredContent=await Qh(a.outputSchema,d.structuredContent,`Invalid output for tool ${e}: `);return d}};if(this._registeredTools[e]=a,!this._appCapabilities.tools&&!this.transport)this.registerAppCapabilities({tools:{listChanged:!0}});return this.ensureToolHandlersInitialized(),n(),a}_toolHandlersInitialized=!1;ensureToolHandlersInitialized(){if(this._toolHandlersInitialized)return;this._toolHandlersInitialized=!0,this.oncalltool=async(e,t)=>{let o=this._registeredTools[e.name];if(!o)throw Error(`Tool ${e.name} not found`);return o.handler(e.arguments,t)},this.onlisttools=async(e,t)=>({tools:await Promise.all(Object.entries(this._registeredTools).filter(([o,r])=>r.enabled).map(async([o,r])=>{let n={name:o,title:r.title,description:r.description,inputSchema:r.inputSchema?await Yh(r.inputSchema,"input"):{type:"object",properties:{}}};if(r.outputSchema)n.outputSchema=await Yh(r.outputSchema,"output");if(r.annotations)n.annotations=r.annotations;if(r._meta)n._meta=r._meta;return n}))})}async sendToolListChanged(e={}){this._assertInitialized("sendToolListChanged"),await this.notification({method:"notifications/tools/list_changed",params:e})}getHostCapabilities(){return this._hostCapabilities}getHostVersion(){return this._hostInfo}getHostContext(){return this._hostContext}get ontoolinput(){return this.getEventHandler("toolinput")}set ontoolinput(e){this.setEventHandler("toolinput",e)}get ontoolinputpartial(){return this.getEventHandler("toolinputpartial")}set ontoolinputpartial(e){this.setEventHandler("toolinputpartial",e)}get ontoolresult(){return this.getEventHandler("toolresult")}set ontoolresult(e){this.setEventHandler("toolresult",e)}get ontoolcancelled(){return this.getEventHandler("toolcancelled")}set ontoolcancelled(e){this.setEventHandler("toolcancelled",e)}get onhostcontextchanged(){return this.getEventHandler("hostcontextchanged")}set onhostcontextchanged(e){this.setEventHandler("hostcontextchanged",e)}_onteardown;get onteardown(){return this._onteardown}set onteardown(e){this.warnIfRequestHandlerReplaced("onteardown",this._onteardown,e),this._onteardown=e,this.replaceRequestHandler("ui/resource-teardown",{params:DS.shape.params,result:VS},(t,o)=>{if(!this._onteardown)throw Error("No onteardown handler set");return this._onteardown(t,o)})}_oncalltool;get oncalltool(){return this._oncalltool}set oncalltool(e){this.warnIfRequestHandlerReplaced("oncalltool",this._oncalltool,e),this._oncalltool=e,this.replaceRequestHandler("tools/call",(t,o)=>{if(!this._oncalltool)throw Error("No oncalltool handler set");return this._oncalltool(t.params,o)})}_onlisttools;get onlisttools(){return this._onlisttools}set onlisttools(e){this.warnIfRequestHandlerReplaced("onlisttools",this._onlisttools,e),this._onlisttools=e,this.replaceRequestHandler("tools/list",(t,o)=>{if(!this._onlisttools)throw Error("No onlisttools handler set");return this._onlisttools(t.params,o)})}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._hostCapabilities?.sampling)throw Error(`Host does not support sampling (required for ${e})`);break}}assertRequestHandlerCapability(e){switch(e){case"tools/call":case"tools/list":if(!this._appCapabilities.tools)throw Error(`Client does not support tool capability (required for ${e})`);return;default:return}}assertNotificationCapability(e){}async callServerTool(e,t){if(this._assertInitialized("callServerTool"),typeof e==="string")throw Error(`callServerTool() expects an object as its first argument, but received a string ("${e}"). Did you mean: callServerTool({ name: "${e}", arguments: { ... } })?`);return await this.request({method:"tools/call",params:e},{onprogress:()=>{},resetTimeoutOnProgress:!0,...t})}async readServerResource(e,t){return this._assertInitialized("readServerResource"),await this.request({method:"resources/read",params:e},t)}async listServerResources(e,t){return this._assertInitialized("listServerResources"),await this.request({method:"resources/list",params:e},t)}async createSamplingMessage(e,t){return this._assertInitialized("createSamplingMessage"),await this.request({method:"sampling/createMessage",params:e},t)}sendMessage(e,t){return this._assertInitialized("sendMessage"),this.request({method:"ui/message",params:e},qS,t)}sendLog(e){return this.notification({method:"notifications/message",params:e})}updateModelContext(e,t){return this._assertInitialized("updateModelContext"),this.request({method:"ui/update-model-context",params:e},tt,t)}openLink(e,t){return this._assertInitialized("openLink"),this.request({method:"ui/open-link",params:e},NS,t)}sendOpenLink=this.openLink;downloadFile(e,t){return this._assertInitialized("downloadFile"),this.request({method:"ui/download-file",params:e},MS,t)}requestTeardown(e={}){return this.notification({method:"ui/notifications/request-teardown",params:e})}requestDisplayMode(e,t){return this._assertInitialized("requestDisplayMode"),this.request({method:"ui/request-display-mode",params:e},JS,t)}sendSizeChanged(e){return this.notification({method:"ui/notifications/size-changed",params:e})}setupSizeChangedNotifications(){let e=!1,t=0,o=0,r=()=>{if(e)return;e=!0,requestAnimationFrame(()=>{e=!1;let i=document.documentElement,a=i.style.height;i.style.height="max-content";let c=Math.ceil(i.getBoundingClientRect().height);i.style.height=a;let p=Math.ceil(window.innerWidth);if(p!==t||c!==o)t=p,o=c,this.sendSizeChanged({width:p,height:c})})};r();let n=new ResizeObserver(r);return n.observe(document.documentElement),n.observe(document.body),()=>n.disconnect()}async connect(e=new tm(window.parent,window.parent),t){if(this.transport)throw Error("App is already connected. Call close() before connecting again.");this._initializedSent=!1;try{await super.connect(e);let o=await this.request({method:"ui/initialize",params:{appCapabilities:this._appCapabilities,appInfo:this._appInfo,protocolVersion:ES}},KS,t);if(o===void 0)throw Error(`Server sent invalid initialize result: ${o}`);if(this._hostCapabilities=o.hostCapabilities,this._hostInfo=o.hostInfo,this._hostContext=o.hostContext,await this.notification({method:"ui/notifications/initialized"}),this._initializedSent=!0,this.options?.autoResize)this.setupSizeChangedNotifications()}catch(o){throw this.close(),o}}}function rm(e){return Array.isArray(e)&&e.length>0&&e.every((t)=>t&&typeof t==="object"&&typeof t.token==="string"&&/^--[\w-]+$/.test(t.token)&&typeof t.property==="string"&&/^-?[a-z][a-z0-9-]*$/.test(t.property)&&typeof t.probe==="string"&&t.probe.trim().length>0)&&new Set(e.map((t)=>`${t.token}:${t.property}`)).size===e.length}function nm(e,t){let o=t.getComputedStyle(e),r=e.getBoundingClientRect();if(o.display==="none"||o.visibility!=="visible"||!e.getClientRects().length||!(r.width||r.height))return!1;for(let n=e;n;n=n.parentElement)if(Number(t.getComputedStyle(n).opacity)===0)return!1;return!0}function sm(e,t){if(!rm(t))return{ok:!1,diagnostics:["Token preview needs explicit { token, property, probe } samples from the project fixture. Rebuild with the current compiler."]};let o=e.ownerDocument,{defaultView:r,documentElement:n}=o,i=[],a=[],c=[...e.querySelectorAll("[data-ads-token], [data-ads-property]")],p=new Set(t.map((d)=>`${d.token}:${d.property}`));for(let d of c)if(!p.has(`${d.dataset.adsToken}:${d.dataset.adsProperty}`))i.push(`Undeclared rendered token sample ${d.dataset.adsToken}:${d.dataset.adsProperty}.`);for(let d of t){if(!r.CSS.supports(d.property,d.probe)){i.push(`${d.token}: the fixture probe is invalid for ${d.property}.`);continue}let f=r.getComputedStyle(n).getPropertyValue(d.token).trim();if(!f||!r.CSS.supports(d.property,f)){i.push(`${d.token}: its current value is invalid for the fixture's ${d.property} binding.`);continue}let S=c.filter((b)=>b.dataset.adsToken===d.token&&b.dataset.adsProperty===d.property);if(!S.length){i.push(`${d.token} needs a rendered ${d.property} sample, not only a name/value label.`);continue}let _=!1;for(let b of S){let P=[];for(let I=b.parentElement;I&&I!==e;I=I.parentElement)if(I.tagName==="DETAILS"&&!I.open)I.open=!0,P.push(I);let k=n.getAttribute("style"),E=b.getAttribute("style");try{if(!/^(?:-[a-z]+-)?transition(?:-|$)/.test(d.property))b.style.setProperty("transition","none","important");let I=r.getComputedStyle(b).getPropertyValue(d.property),D=nm(b,r);n.style.setProperty(d.token,d.probe,"important");let M=r.getComputedStyle(b).getPropertyValue(d.property);_=Boolean(M&&M!==I&&(D||nm(b,r)))}finally{if(k===null)n.removeAttribute("style");else n.setAttribute("style",k);if(E===null)b.removeAttribute("style");else b.setAttribute("style",E);for(let I of P)I.open=!1}if(_)break}if(_)a.push(d);else i.push(`${d.token} has no visible ${d.property} sample that responds to its value. Hardcoded copies do not satisfy coverage.`)}return{ok:!i.length,verified:a,diagnostics:i}}var st=new ua({name:"ADS preview",version:"1.0.0"},{},{autoResize:!0}),im=document.getElementById("ads-preview-seed"),cm;function am(e,t){let o=document.createElement(e);return o.textContent=t,o}function lm(e){if(e==="light"||e==="dark")document.documentElement.dataset.theme=e}st.onhostcontextchanged=(e)=>lm(e.theme);if(im){let n=function(c){let p="";if(!c||c.state==="unreported")p="Preview freshness is unverified. Check the build status before reviewing.";else if(c.state==="error"){let d=c.diagnostics?.[0];if(p=`Build failed. Showing ${e.revision===null?"an earlier preview":`build ${e.revision}`}.`,d)p+=`
107
107
  ${d.file??""}${d.line?`:${d.line}`:""}${d.file?": ":""}${d.message}`}else if(["building","idle"].includes(c.state))p="Rebuilding. This view is the previous preview.";else if(c.revision!==e.revision||c.session!==e.session)p=`Build ${c.revision} is ready. Reopen this preview to load it.`;t.textContent=[p,r].filter(Boolean).join(`
108
- `),t.hidden=!t.textContent},e=JSON.parse(im.textContent),t=am("aside","");t.id="ads-preview-build",t.setAttribute("role","status"),t.setAttribute("aria-live","polite");let o=am("style","#ads-preview-build{position:fixed;inset:12px 12px auto;z-index:2147483647;padding:10px 14px;border:1px solid GrayText;border-radius:6px;background:Canvas;color:CanvasText;font:13px system-ui;white-space:pre-wrap;overflow-wrap:anywhere;max-height:30vh;overflow:auto}#ads-preview-build[hidden]{display:none}");document.head.append(o),document.body.append(t);let r="";if(n(e),e.kind==="tokens")(async()=>{await new Promise((p)=>requestAnimationFrame(()=>requestAnimationFrame(p))),await document.fonts.ready;let c=sm(document.body,e.samples);if(!c.ok){r=`Token preview verification failed:
108
+ `),t.hidden=!t.textContent},e=JSON.parse(im.textContent),t=am("aside","");t.id="ads-preview-build",t.setAttribute("role","status"),t.setAttribute("aria-live","polite");let o=am("style","#ads-preview-build{position:fixed;inset:12px 12px auto;z-index:2147483647;padding:10px 14px;border:1px solid GrayText;border-radius:6px;background:Canvas;color:CanvasText;font:13px system-ui;white-space:pre-wrap;overflow-wrap:anywhere;max-height:30vh;overflow:auto}#ads-preview-build[hidden]{display:none}");document.head.append(o),document.body.append(t);let r="";if(n(e),e.kind==="tokens"&&!e.brand)(async()=>{await new Promise((p)=>requestAnimationFrame(()=>requestAnimationFrame(p))),await document.fonts.ready;let c=sm(document.body,e.samples);if(!c.ok){r=`Token preview verification failed:
109
109
  ${c.diagnostics.slice(0,20).join(`
110
110
  `)}`,t.setAttribute("role","alert"),n(e);try{if(st.getHostCapabilities()?.logging)await st.sendLog({level:"error",logger:"ads-preview",data:{state:"error",id:e.id,message:r}})}catch{}}})();let i=!1,a;st.onteardown=async()=>(clearInterval(a),{}),window.addEventListener("pagehide",()=>clearInterval(a),{once:!0}),cm=()=>{if(!st.getHostCapabilities()?.serverResources)return;async function c(){if(i||document.visibilityState==="hidden")return;i=!0;try{let p=await st.readServerResource({uri:"ads://project/build"},{timeout:5000}),d=JSON.parse(p.contents.find((f)=>("text"in f)).text);n(d.previews.find((f)=>f.id===e.id))}catch{t.textContent=["Build status unavailable. Reopen the preview to verify it.",r].filter(Boolean).join(`
111
111
  `),t.hidden=!1}finally{i=!1}}c(),a=setInterval(()=>{c()},2000)}}try{await st.connect(),cm?.(),lm(st.getHostContext()?.theme)}catch{}