@reqvire-org/ads 0.3.28 → 0.3.29

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 (53) hide show
  1. package/dist/atomic-composition.mjs +2 -1
  2. package/dist/behaviors.mjs +2 -2
  3. package/dist/boundaries.mjs +6 -3
  4. package/dist/check.mjs +3 -0
  5. package/dist/cli.mjs +13 -0
  6. package/dist/config.mjs +5 -3
  7. package/dist/mcp/build-status.mjs +17 -4
  8. package/dist/mcp/context.mjs +2 -1
  9. package/dist/mcp/execution-results.mjs +4 -3
  10. package/dist/mcp/mutations.mjs +5 -43
  11. package/dist/mcp/preview-watch.mjs +23 -3
  12. package/dist/mcp/preview-widget.bundle.js +16 -15
  13. package/dist/mcp/resource-loader.js +40 -12
  14. package/dist/mcp/server.mjs +74 -36
  15. package/dist/oxlint.mjs +6 -1
  16. package/dist/preview-builder.mjs +10 -4
  17. package/dist/preview-resources.mjs +11 -4
  18. package/dist/preview-scope.mjs +6 -0
  19. package/dist/preview-workers.mjs +184 -0
  20. package/dist/scenario-inspector.mjs +34 -0
  21. package/dist/scenario-trace.mjs +3 -2
  22. package/dist/scenarios-compiler.mjs +200 -25
  23. package/dist/showcase/client.bundle.js +22 -21
  24. package/dist/showcase/index.html +2 -2
  25. package/dist/showcase/style.css +2 -1
  26. package/dist/skills/ads-break-ui/SKILL.md +3 -0
  27. package/dist/skills/ads-break-ui/references/runtimes.md +31 -0
  28. package/dist/skills/ads-break-ui/references/validation.md +53 -0
  29. package/dist/skills/ads-designer/SKILL.md +3 -0
  30. package/dist/skills/ads-designer/references/runtimes.md +31 -0
  31. package/dist/skills/ads-designer/references/validation.md +53 -0
  32. package/dist/skills/ads-import/SKILL.md +3 -0
  33. package/dist/skills/ads-import/references/runtimes.md +31 -0
  34. package/dist/skills/ads-import/references/validation.md +53 -0
  35. package/dist/skills/ads-motion/SKILL.md +3 -0
  36. package/dist/skills/ads-motion/references/runtimes.md +31 -0
  37. package/dist/skills/ads-motion/references/validation.md +53 -0
  38. package/dist/skills/ads-port/SKILL.md +3 -0
  39. package/dist/skills/ads-port/references/runtimes.md +31 -0
  40. package/dist/skills/ads-port/references/validation.md +53 -0
  41. package/dist/source-symbols.mjs +11 -0
  42. package/dist/source-values.mjs +10 -3
  43. package/dist/test-boundaries.mjs +95 -0
  44. package/dist/ui-framework.mjs +2 -1
  45. package/dist/units.mjs +12 -1
  46. package/dist/validation-checks.mjs +50 -0
  47. package/dist/validation.mjs +172 -0
  48. package/dist/verification/browser.mjs +3 -1
  49. package/dist/verification.mjs +1 -0
  50. package/docs/ARCHITECTURE.md +72 -17
  51. package/docs/CHANGELOG.md +37 -0
  52. package/docs/MCP.md +68 -9
  53. package/package.json +1 -1
@@ -0,0 +1,184 @@
1
+ import { createHash } from "node:crypto";
2
+ import { existsSync, readFileSync, readdirSync } from "node:fs";
3
+ import path from "node:path";
4
+ import ts from "typescript";
5
+ import { isInside } from "./config.mjs";
6
+
7
+ const metadata = "ads:preview-workers";
8
+ const virtual = "\0ads-preview-worker:";
9
+ const digest = value => createHash("sha256").update(value).digest("hex");
10
+ function fileHash(file) { try { return digest(readFileSync(file)); } catch { return null; } }
11
+ function directoryHash(directory) {
12
+ try { return digest(JSON.stringify(readdirSync(directory, { withFileTypes: true }).map(entry => [entry.name, entry.isDirectory(), entry.isSymbolicLink()]).sort())); }
13
+ catch { return null; }
14
+ }
15
+ const filePath = id => typeof id === "string" && path.isAbsolute(id.split("?")[0]) ? id.split("?")[0] : null;
16
+
17
+ /** Cache Vite's own completed IIFE workers through public plugin hooks. No
18
+ * project-specific worker compiler, dependency list or Vite internals involved.
19
+ * Cached constructors refer to emitted assets; resource conversion still owns
20
+ * immutable URIs, byte verification and opaque-origin worker adaptation. */
21
+ export function createPreviewWorkerCache(options, isCurrent) {
22
+ const bundles = new Map(), staged = new Map(), pending = new Map();
23
+ let memo = new Map(), configuration = [], format, cycle = 0;
24
+ function valid(entry, fresh = false) {
25
+ if (!entry) return false;
26
+ if (fresh) memo.delete(entry);
27
+ if (!memo.has(entry)) memo.set(entry, [...entry.files].every(([file, hash]) => fileHash(file) === hash)
28
+ && [...entry.directories].every(([directory, hash]) => directoryHash(directory) === hash));
29
+ return memo.get(entry);
30
+ }
31
+ function directories(files) {
32
+ const result = new Map();
33
+ for (const file of files.keys()) {
34
+ let directory = path.dirname(file);
35
+ while (!result.has(directory)) {
36
+ result.set(directory, directoryHash(directory));
37
+ if (directory === options.root || path.basename(directory) === "node_modules"
38
+ || !isInside(options.root, directory) && existsSync(path.join(directory, "package.json"))) break;
39
+ const parent = path.dirname(directory);
40
+ if (parent === directory) break;
41
+ directory = parent;
42
+ }
43
+ }
44
+ return result;
45
+ }
46
+ function tracker() {
47
+ const observed = new Map();
48
+ const generation = cycle;
49
+ let nested = false;
50
+ return { name: "ads-preview-worker-inputs", enforce: "post",
51
+ buildStart() { for (const file of configuration) observed.set(file, fileHash(file)); },
52
+ load: { order: "pre", handler(id) { const file = filePath(id); if (file && !observed.has(file)) observed.set(file, fileHash(file)); } },
53
+ moduleParsed(info) {
54
+ if (/\bnew\s+(?:Worker|SharedWorker)\s*\(\s*new\s+URL\s*\(/.test(info.code ?? "")
55
+ || info.importedIds.some(id => /[?&](?:shared)?worker(?:[&=]|$)/.test(id))) nested = true;
56
+ },
57
+ generateBundle: { order: "post", handler(output, bundle) {
58
+ // Inline, nested and split ES workers retain Vite's normal path. Their
59
+ // extra parent-owned assets cannot be inferred from one worker bundle.
60
+ const chunks = Object.values(bundle).filter(item => item.type === "chunk");
61
+ if (generation !== cycle || format !== "iife" || nested || chunks.length !== 1 || chunks[0].imports.length || chunks[0].dynamicImports.length) return;
62
+ const entry = chunks[0].facadeModuleId;
63
+ if (!entry || !path.isAbsolute(entry)) return;
64
+ const files = new Map();
65
+ for (const id of [...this.getWatchFiles(), ...this.getModuleIds(), ...configuration]) {
66
+ const file = filePath(id);
67
+ if (!file) continue;
68
+ // Unobserved plugin inputs cannot establish a reusable snapshot.
69
+ const hash = observed.get(file);
70
+ if (!hash || fileHash(file) !== hash) return;
71
+ files.set(file, hash);
72
+ }
73
+ if (!files.has(entry)) return;
74
+ staged.set(entry, { entry, files, directories: directories(files), fileName: chunks[0].fileName,
75
+ assets: Object.values(bundle).map(item => ({ type: "asset", fileName: item.fileName,
76
+ source: item.type === "chunk" ? item.code : typeof item.source === "string" ? item.source : Buffer.from(item.source) })) });
77
+ } },
78
+ };
79
+ }
80
+ async function worker(context, file, query = "worker&url") {
81
+ let entry = staged.get(file) ?? bundles.get(file);
82
+ if (!valid(entry)) {
83
+ // Vite remains the compiler, including its configured worker plugins.
84
+ if (!pending.has(file)) pending.set(file, context.load({ id: file + "?" + query }));
85
+ await pending.get(file);
86
+ entry = staged.get(file);
87
+ }
88
+ if (!valid(entry)) return null;
89
+ for (const dependency of entry.files.keys()) context.addWatchFile(dependency);
90
+ return entry;
91
+ }
92
+ const plugin = { name: "ads-preview-worker-cache", enforce: "pre",
93
+ config(config) {
94
+ const original = config.worker?.plugins;
95
+ // Mutate this option: Vite merges returned worker plugin factories by
96
+ // concatenation, which would execute the project's plugins twice.
97
+ config.worker ??= {};
98
+ config.worker.plugins = (...args) => [typeof original === "function" ? original(...args) : original ?? [], tracker()];
99
+ },
100
+ configResolved(config) {
101
+ configuration = [...new Set([...(config.configFileDependencies ?? []), path.join(options.root, "package.json"), path.join(options.root, "tsconfig.json")])].filter(existsSync);
102
+ format = config.worker.format;
103
+ },
104
+ buildStart() { ++cycle; staged.clear(); pending.clear(); memo = new Map(); },
105
+ shouldTransformCachedModule({ meta }) {
106
+ // Preserve Vite's worker-importer transform lifecycle. Other plugins can
107
+ // have evaluated dependencies which no longer appear in emitted JS (for
108
+ // example extracted CSS); only the expensive worker sub-build is cached.
109
+ if (meta[metadata]?.length) return true;
110
+ return null;
111
+ },
112
+ async resolveId(source, importer) {
113
+ if (format !== "iife" || importer?.startsWith(virtual)) return null;
114
+ const index = source.indexOf("?");
115
+ if (index < 0) return null;
116
+ const query = new URLSearchParams(source.slice(index + 1));
117
+ if (!query.has("worker") || [...query].some(([key, value]) => !["worker", "url"].includes(key) || value)) return null;
118
+ const resolved = await this.resolve(source.slice(0, index), importer, { skipSelf: true });
119
+ const file = filePath(resolved?.id);
120
+ if (!file) return null;
121
+ const suffix = query.has("url") ? "worker&url" : "worker";
122
+ if (!await worker(this, file, suffix)) return { id: file + "?" + suffix };
123
+ return virtual + JSON.stringify([file, suffix]);
124
+ },
125
+ load(id) { if (id.startsWith(virtual)) return "export {};"; },
126
+ async transform(code, id) {
127
+ if (id.startsWith(virtual)) {
128
+ const [file, query] = JSON.parse(id.slice(virtual.length));
129
+ const entry = await worker(this, file, query);
130
+ if (!entry) return { code: `export {default} from ${JSON.stringify(file + "?" + query)};`, meta: { [metadata]: [] } };
131
+ const url = JSON.stringify("/" + entry.fileName);
132
+ return { code: query === "worker&url" ? `export default ${url};`
133
+ : `export default function WorkerWrapper(options){return new Worker(${url},{name:options?.name});}`,
134
+ meta: { [metadata]: [file] } };
135
+ }
136
+ const previous = this.getModuleInfo(id)?.meta[metadata];
137
+ if (format !== "iife" || !code.includes("Worker") || !code.includes("new URL")) return previous?.length ? { meta: { [metadata]: [] } } : null;
138
+ const source = ts.createSourceFile(id, code, ts.ScriptTarget.Latest, true, /\.[jt]sx(?:\?|$)/.test(id) ? ts.ScriptKind.TSX : ts.ScriptKind.TS);
139
+ const calls = [];
140
+ function visit(node) {
141
+ if (ts.isNewExpression(node) && ts.isIdentifier(node.expression) && node.expression.text === "Worker") {
142
+ const url = node.arguments?.[0];
143
+ if (url && ts.isNewExpression(url) && ts.isIdentifier(url.expression) && url.expression.text === "URL"
144
+ && url.arguments?.length === 2 && ts.isStringLiteralLike(url.arguments[0]) && url.arguments[1].getText(source) === "import.meta.url") calls.push(url);
145
+ }
146
+ ts.forEachChild(node, visit);
147
+ }
148
+ visit(source);
149
+ const replacements = [], used = new Set();
150
+ for (const url of calls) {
151
+ const value = url.arguments[0].text;
152
+ if (!value.startsWith(".") || /[?#]/.test(value)) continue;
153
+ const resolved = await this.resolve(value, id, { skipSelf: true });
154
+ const file = filePath(resolved?.id);
155
+ const entry = file && await worker(this, file);
156
+ if (!entry) continue;
157
+ used.add(entry.entry);
158
+ replacements.push([url.getStart(source), url.end, JSON.stringify("/" + entry.fileName)]);
159
+ }
160
+ for (const [start, end, value] of replacements.sort((a, b) => b[0] - a[0])) code = code.slice(0, start) + value + code.slice(end);
161
+ return replacements.length || previous?.length ? { code, map: null, meta: { [metadata]: [...used] } } : null;
162
+ },
163
+ generateBundle: { order: "post", handler(_output, bundle) {
164
+ const used = new Set();
165
+ for (const id of this.getModuleIds()) for (const file of this.getModuleInfo(id)?.meta[metadata] ?? []) used.add(file);
166
+ for (const file of used) {
167
+ const entry = staged.get(file) ?? bundles.get(file);
168
+ if (!valid(entry, true)) this.error("Worker inputs changed during preview compilation. Rebuild the current source.");
169
+ for (const asset of entry.assets) {
170
+ const existing = bundle[asset.fileName];
171
+ if (existing) {
172
+ if (existing.type !== "asset" || !Buffer.from(existing.source).equals(Buffer.from(asset.source))) this.error(`Worker asset path collision: ${asset.fileName}`);
173
+ continue;
174
+ }
175
+ this.emitFile(asset);
176
+ }
177
+ }
178
+ for (const file of bundles.keys()) if (!used.has(file) && !staged.has(file)) bundles.delete(file);
179
+ } },
180
+ writeBundle: { order: "post", handler() { if (isCurrent()) for (const [file, entry] of staged) if (valid(entry, true)) bundles.set(file, entry); staged.clear(); } },
181
+ closeWatcher() { ++cycle; bundles.clear(); staged.clear(); pending.clear(); memo.clear(); },
182
+ };
183
+ return plugin;
184
+ }
@@ -0,0 +1,34 @@
1
+ import { Worker, isMainThread, parentPort, workerData } from "node:worker_threads";
2
+ import { loadConfig } from "./config.mjs";
3
+ import { inspectScenarios } from "./scenarios.mjs";
4
+
5
+ // Discovery is semantic source analysis. Keep it off the live compiler's event
6
+ // loop; the caller fences each result against the exact project input digest.
7
+ if (!isMainThread && workerData?.adsScenarioInspector) {
8
+ parentPort.on("message", ({ id }) => {
9
+ try { parentPort.postMessage({ id, result: inspectScenarios(loadConfig(workerData.root)) }); }
10
+ catch (error) { parentPort.postMessage({ id, error: error.message }); }
11
+ });
12
+ }
13
+
14
+ export function createScenarioInspector(root) {
15
+ let worker, sequence = 0;
16
+ const pending = new Map();
17
+ function fail(error) { for (const task of pending.values()) task.reject(error); pending.clear(); }
18
+ return {
19
+ inspect() {
20
+ if (!worker) {
21
+ worker = new Worker(new URL(import.meta.url), { workerData: { adsScenarioInspector: true, root } });
22
+ worker.on("message", ({ id, result, error }) => {
23
+ const task = pending.get(id); pending.delete(id);
24
+ if (task) { if (error) task.reject(new Error(error)); else task.resolve(result); }
25
+ });
26
+ worker.on("error", fail);
27
+ worker.on("exit", () => { fail(new Error("Scenario inspector closed.")); worker = undefined; });
28
+ }
29
+ const id = ++sequence;
30
+ return new Promise((resolve, reject) => { pending.set(id, { resolve, reject }); worker.postMessage({ id }); });
31
+ },
32
+ async close() { const previous = worker; worker = undefined; fail(new Error("Scenario inspector closed.")); await previous?.terminate(); },
33
+ };
34
+ }
@@ -5,6 +5,7 @@ import { isDevelopmentFile, isInside, isReviewFile } from "./config.mjs";
5
5
  import { scenarioApi } from "./public-api.mjs";
6
6
  import { uiOperation } from "./ui-framework.mjs";
7
7
  import { inspectUnits } from "./units.mjs";
8
+ import { sourceSymbol } from "./source-symbols.mjs";
8
9
  import { createSourceValues, reference, union, isFunction } from "./source-values.mjs";
9
10
  import { inspectRuntimeContracts } from "./runtime-contracts.mjs";
10
11
  import { implementationNode } from "./unit-contracts.mjs";
@@ -18,7 +19,7 @@ export function createScenarioTrace(program, options) {
18
19
  if (!expression || seen.has(expression)) return false;
19
20
  seen.add(expression);
20
21
  const base = ts.isPropertyAccessExpression(expression) ? expression.expression : expression;
21
- const symbol = checker.getSymbolAtLocation(base);
22
+ const symbol = sourceSymbol(checker, base);
22
23
  for (const declaration of symbol?.declarations ?? []) {
23
24
  if (ts.isImportSpecifier(declaration) && (declaration.propertyName ?? declaration.name).text === name && ["@linaria/atomic", "@linaria/core"].includes(declaration.parent.parent.parent.moduleSpecifier.text)) return true;
24
25
  if (ts.isNamespaceImport(declaration) && ts.isPropertyAccessExpression(expression) && expression.name.text === name && ["@linaria/atomic", "@linaria/core"].includes(declaration.parent.parent.moduleSpecifier.text)) return true;
@@ -197,7 +198,7 @@ export function createScenarioTrace(program, options) {
197
198
  return { present: !property || value.kind !== "unknown", ok, reasons: [...reasons].slice(0, 3) };
198
199
  }
199
200
  function traceEntry(source, {exercise=false}={}) {
200
- const module=checker.getSymbolAtLocation(source),symbol=module&&checker.getExportsOfModule(module).find(symbol=>symbol.name==="default");
201
+ const module=sourceSymbol(checker, source),symbol=module&&checker.getExportsOfModule(module).find(symbol=>symbol.name==="default");
201
202
  const resolved=symbol?.flags&ts.SymbolFlags.Alias?checker.getAliasedSymbol(symbol):symbol;
202
203
  const declaration=resolved?.valueDeclaration;
203
204
  return traceRenders(declaration&&(ts.isExportAssignment(declaration)?declaration.expression:declaration.name??declaration),{entry:true,exercise});
@@ -8,6 +8,7 @@ import { cachedPreviewPublication, previewArtifactHtml, readPreviewManifest } fr
8
8
  import { previewArtifactPath, withPreviewSession } from "./preview-scope.mjs";
9
9
  import { previewSourceRevision } from "./preview-inputs.mjs";
10
10
  import { previewFileIgnored, previewWatchDirectories } from "./preview-files.mjs";
11
+ import { createScenarioInspector } from "./scenario-inspector.mjs";
11
12
 
12
13
  const digest = value => createHash("sha256").update(value).digest("hex");
13
14
  const fileDigest = file => { try { return digest(readFileSync(file)); } catch { return null; } };
@@ -16,21 +17,25 @@ const fileDigest = file => { try { return digest(readFileSync(file)); } catch {
16
17
  * Cache state is development output, never proof that a failed build is current. */
17
18
  export function createPreviewCache(options, compilerFiles = []) {
18
19
  const { root } = options;
19
- const adapterFiles = [import.meta.filename, ...["preview-builder.mjs", "preview-files.mjs", "preview-inputs.mjs", "preview-resources.mjs", "preview-scope.mjs", "scenario-groups.mjs", "scenarios-vite.mjs", "linaria.mjs", "linaria/atomic-css.cjs", "linaria/atomic-styled.cjs", "linaria/preserve-values.cjs"].map(file => path.join(import.meta.dirname, file)), ...compilerFiles,
20
+ const key = file => isInside(import.meta.dirname,file) ? `ads-tool/${path.relative(import.meta.dirname,file)}` : isInside(root,file) ? `project/${path.relative(root,file)}` : file;
21
+ const adapterFiles = [import.meta.filename, ...["preview-builder.mjs", "preview-workers.mjs", "preview-files.mjs", "preview-inputs.mjs", "preview-resources.mjs", "preview-scope.mjs", "scenario-groups.mjs", "scenario-inspector.mjs", "scenarios-vite.mjs", "linaria.mjs", "linaria/atomic-css.cjs", "linaria/atomic-styled.cjs", "linaria/preserve-values.cjs"].map(file => path.join(import.meta.dirname, file)), ...compilerFiles,
20
22
  ...["package.json", "package-lock.json", "bun.lock", "bun.lockb", "node_modules/.package-lock.json"].map(file => path.join(root, file))];
21
- const adapterDigest = () => digest(JSON.stringify(adapterFiles.map(file => [file, fileDigest(file)])));
23
+ const adapterDigest = () => digest(JSON.stringify(adapterFiles.map(file => [key(file), fileDigest(file)])));
22
24
  const loadedAdapter = adapterDigest();
23
25
  const target = path.join(root, ".ds/preview-cache.json");
24
- let value = { schemaVersion: 1, validation: null, entries: {} };
25
- try {
26
- if (realpathSync(target) === target) {
27
- const stored = JSON.parse(readFileSync(target, "utf8"));
28
- if (stored.schemaVersion === 1 && stored.entries && typeof stored.entries === "object") value = stored;
29
- }
30
- } catch { /* Missing or corrupt cache means validate and rebuild. */ }
26
+ let value = { schemaVersion: 2, validation: null, entries: {} };
27
+ function reload() {
28
+ try {
29
+ if (realpathSync(target) === target && statSync(target).size < 8*1024*1024) {
30
+ const stored = JSON.parse(readFileSync(target, "utf8"));
31
+ if (stored.schemaVersion === 2 && stored.entries && typeof stored.entries === "object") value = stored;
32
+ }
33
+ } catch { /* Missing or corrupt cache means validate and rebuild. */ }
34
+ }
35
+ reload();
31
36
  function inputs() {
32
37
  const rows = [["project-inputs",previewSourceRevision(options)],["node-runtime",`${process.version}/${process.platform}/${process.arch}`]];
33
- for (const file of compilerFiles) rows.push([file, fileDigest(file)]);
38
+ for (const file of compilerFiles) rows.push([key(file), fileDigest(file)]);
34
39
  // Tool upgrades invalidate validation even when the project's lockfile is unchanged.
35
40
  for (const name of readdirSync(import.meta.dirname).filter(name => name.endsWith(".mjs"))) {
36
41
  rows.push([`ads-tool/${name}`, fileDigest(path.join(import.meta.dirname, name))]);
@@ -39,6 +44,7 @@ export function createPreviewCache(options, compilerFiles = []) {
39
44
  return digest(JSON.stringify(rows.sort((a, b) => a[0].localeCompare(b[0]))));
40
45
  }
41
46
  function save() {
47
+ value.compilerFiles = compilerFiles.map(file => isInside(root,file) ? path.relative(root,file) : null);
42
48
  mkdirSync(path.dirname(target), { recursive: true });
43
49
  if (realpathSync(path.dirname(target)) !== path.dirname(target)) throw new Error("Preview cache cannot resolve through a symlink.");
44
50
  const temporary = `${target}.${randomUUID()}.tmp`;
@@ -47,7 +53,7 @@ export function createPreviewCache(options, compilerFiles = []) {
47
53
  }
48
54
  const compilerDigest = () => digest(JSON.stringify([
49
55
  ["adapter", adapterDigest()],
50
- ...compilerFiles.map(file => [file, fileDigest(file)]),
56
+ ...compilerFiles.map(file => [key(file), fileDigest(file)]),
51
57
  ...readdirSync(root).filter(name => !/^(?:biome|oxlint|\.oxlint)/.test(name) && (/\.(?:json|lock|lockb)$/.test(name) || /^(?:vite|babel)\.config\./.test(name))).map(name => [name, fileDigest(path.join(root, name))]),
52
58
  ["installed-packages", fileDigest(path.join(root, "node_modules/.package-lock.json"))],
53
59
  ["scheduler", fileDigest(import.meta.filename)],
@@ -58,26 +64,68 @@ export function createPreviewCache(options, compilerFiles = []) {
58
64
  if (!cached || cached.metadata !== JSON.stringify(entry) || cached.compiler !== compilerDigest()) return false;
59
65
  if (!cached.dependencies || !Object.keys(cached.dependencies).length) return false;
60
66
  if (Object.entries(cached.dependencies).some(([file, hash]) => fileDigest(path.resolve(root, file)) !== hash)) return false;
61
- if (expectedHtml !== undefined && cached.artifact !== `sha256:${digest(expectedHtml)}`) return false;
67
+ if (expectedHtml !== undefined) return cached.artifact === `sha256:${digest(expectedHtml)}`;
62
68
  const file = path.join(root, previewArtifactPath(options, entry.artifact));
63
- if (expectedHtml !== undefined && !existsSync(file)) return true;
64
69
  try { return cached.artifact === artifactDigest(file); } catch { return false; }
65
70
  }
66
- return { inputs, reusable, graphRevision: () => value.graphRevision, recordGraph(revision) { value.graphRevision = revision; save(); }, validated: stamp => value.validation === stamp,
71
+ function recordEntries(entries, dependencies) {
72
+ const compiler = compilerDigest(), hashes = new Map();
73
+ for (const entry of entries) {
74
+ const files = [...new Set([path.join(root, entry.file), ...dependencies])]
75
+ .filter(file => isInside(root, file) && !file.includes(`${path.sep}node_modules${path.sep}`));
76
+ for (const file of files) if (!hashes.has(file)) hashes.set(file, fileDigest(file));
77
+ value.entries[entry.id] = { metadata: JSON.stringify(entry), compiler,
78
+ dependencies: Object.fromEntries(files.map(file => [path.relative(root, file), hashes.get(file)])),
79
+ artifact: artifactDigest(path.join(root, previewArtifactPath(options, entry.artifact))) };
80
+ }
81
+ }
82
+ function recordGraph(revision, entries) { value.graphRevision=revision;value.graphInputs=inputs();value.registry=entries;save(); }
83
+ return { inputs, reusable, reload, snapshot: () => structuredClone(value), seed(state) { value=structuredClone(state);save(); }, graphRevision: () => value.graphRevision, recordGraph, validated: stamp => value.validation === stamp,
84
+ registry(stamp) {
85
+ if(value.validation!==stamp || value.graphInputs!==stamp || !Array.isArray(value.registry) || !value.registry.length || value.registry.length>1000)return null;
86
+ const valid=value.registry.every(entry=>typeof entry?.id==="string" && /^(?:tokens|components|patterns|composition)\/[\w./-]+$/.test(entry.id) && path.posix.normalize(entry.id)===entry.id
87
+ && typeof entry.file==="string" && isInside(options.dsRoot,path.resolve(root,entry.file))
88
+ && entry.artifact===`.ds/scenarios/${entry.id}/index.html` && reusable(entry,previewArtifactHtml(entry.id,value.graphRevision)));
89
+ return valid?structuredClone(value.registry):null;
90
+ },
67
91
  assertCompiler() {
68
92
  if (adapterDigest() !== loadedAdapter) throw Object.assign(new Error("Preview compiler code or dependencies changed. Invoke the preview again to restart the builder and load current code."), { code: "ADS_PREVIEW_RESTART" });
69
93
  },
70
94
  validate(stamp) { value.validation = stamp; save(); },
95
+ recordAll(entries, dependencies, revision) { recordEntries(entries, dependencies); recordGraph(revision,entries); },
71
96
  record(entry, dependencies) {
72
- value.entries[entry.id] = { metadata: JSON.stringify(entry), compiler: compilerDigest(),
73
- dependencies: Object.fromEntries([...new Set([path.join(root, entry.file), ...dependencies])]
74
- .filter(file => isInside(root, file) && !file.includes(`${path.sep}node_modules${path.sep}`)).map(file => [path.relative(root, file), fileDigest(file)])),
75
- artifact: artifactDigest(path.join(root, previewArtifactPath(options, entry.artifact))) };
97
+ recordEntries([entry], dependencies);
76
98
  save();
77
99
  },
78
100
  };
79
101
  }
80
102
 
103
+ /** Accepted source can carry its checked graph out of a guarded candidate.
104
+ * A cache miss is harmless: the regular watcher will prepare the preview. */
105
+ export function preparePreviewCache(candidate, target) {
106
+ if (!candidate.config.mcp.previewManifest || candidate.config.framework !== target.config.framework || !target.config.mcp.previewManifest) return false;
107
+ const file=path.join(candidate.root,".ds/preview-cache.json");
108
+ if (!existsSync(file) || realpathSync(file)!==file || statSync(file).size>8*1024*1024) return false;
109
+ const state=JSON.parse(readFileSync(file,"utf8"));
110
+ if(state.schemaVersion!==2 || !Array.isArray(state.compilerFiles) || state.compilerFiles.some(file=>typeof file!=="string"||!isInside(candidate.root,path.resolve(candidate.root,file))))return false;
111
+ const source=createPreviewCache(candidate,state.compilerFiles.map(file=>path.resolve(candidate.root,file)));
112
+ const destination=createPreviewCache(target,state.compilerFiles.map(file=>path.resolve(target.root,file)));
113
+ const stamp=source.inputs();
114
+ const entries=source.registry(stamp);
115
+ if(!entries?.length)return false;
116
+ const publication=cachedPreviewPublication(candidate,entries,state.graphRevision,target);
117
+ if(!publication || source.inputs()!==stamp)return false;
118
+ const snapshot=source.snapshot();
119
+ return () => {
120
+ if(destination.inputs()!==stamp)return false;
121
+ publication.publish("accepted-mutation");
122
+ destination.seed(snapshot);
123
+ return {revision:publication.revision,scenarios:entries.map(entry=>entry.id)};
124
+ };
125
+ }
126
+
127
+ export function promotePreviewCache(candidate,target) { const publish=preparePreviewCache(candidate,target);return publish?publish():false; }
128
+
81
129
  /** Shared scheduling and cache; the project supplies its own React/Preact build. */
82
130
  export async function runScenarioCompiler(directory, { watched = false, validate, build, buildGraph, compilerFiles = [] }) {
83
131
  const root = path.resolve(directory);
@@ -110,6 +158,8 @@ export async function runScenarioCompiler(directory, { watched = false, validate
110
158
  let validation;
111
159
  let observedSourceRevision = previewSourceRevision(options);
112
160
  let invalidation;
161
+ const inspector = watched && buildGraph ? createScenarioInspector(root) : null;
162
+ let liveCandidate, verifying = false;
113
163
  function failure(error) {
114
164
  try { reporter.failure(error); } catch (reportError) { console.error(reportError); }
115
165
  console.error(error);
@@ -134,7 +184,7 @@ export async function runScenarioCompiler(directory, { watched = false, validate
134
184
  ]);
135
185
  }
136
186
  async function compile(entry) {
137
- if (buildGraph) return compileGraph();
187
+ if (buildGraph) return watched ? compileLiveGraph() : compileGraph();
138
188
  const revision = reporter.begin(entry.id,{sourceRevision:previewSourceRevision(options)});
139
189
  const started = generation;
140
190
  try {
@@ -178,6 +228,7 @@ export async function runScenarioCompiler(directory, { watched = false, validate
178
228
  }
179
229
  }
180
230
  async function compileGraph() {
231
+ cache.reload();
181
232
  const sourceRevision = previewSourceRevision(options);
182
233
  const revisions = new Map(entries.map(entry => [entry.id, reporter.begin(entry.id,{sourceRevision})]));
183
234
  const started = generation;
@@ -214,10 +265,10 @@ export async function runScenarioCompiler(directory, { watched = false, validate
214
265
  const publication = outcomes[1].value;
215
266
  if (publication) {
216
267
  publication.publish(reporter.session);
217
- for (const entry of entries) cache.record(entry, dependencies);
218
- cache.recordGraph(publication.revision);
268
+ cache.recordAll(entries, dependencies, publication.revision);
219
269
  } else {
220
270
  cached.publish(reporter.session);
271
+ cache.recordGraph(cached.revision,entries);
221
272
  }
222
273
  for (const entry of entries) { pending.delete(entry.id); reporter.ready(entry.id, revisions.get(entry.id)); }
223
274
  publishedStamp = stamp;
@@ -230,6 +281,124 @@ export async function runScenarioCompiler(directory, { watched = false, validate
230
281
  if (!watched) process.exitCode = 1;
231
282
  }
232
283
  }
284
+ // Visual feedback and verified publication have separate lifecycles. Edits
285
+ // replace the pending candidate immediately; verification has at most one run
286
+ // in flight and coalesces intervening edits instead of queuing every keystroke.
287
+ async function compileLiveGraph() {
288
+ cache.reload();
289
+ const sourceRevision = previewSourceRevision(options), stamp = cache.inputs();
290
+ const prepared=cache.registry(stamp);
291
+ if(prepared){entries=prepared;reporter.setApps(buildApps());}
292
+ const candidate = { generation, stamp, sourceRevision, entries: [...entries], dependencies: new Set(), registryReused:!!prepared };
293
+ // One multi-entry build covers every requested scenario in this revision.
294
+ // Navigation must not enqueue the same shared graph once per visited entry.
295
+ for (const entry of candidate.entries) pending.delete(entry.id);
296
+ candidate.revisions = reporter.batch(() => new Map(entries.map(entry => [entry.id, reporter.begin(entry.id, { sourceRevision })])));
297
+ reporter.progress("validation-and-compilation");
298
+ const track = { name: "ads-live-preview-dependencies", generateBundle() {
299
+ for (const id of this.getModuleIds()) {
300
+ const file = id.split("?")[0];
301
+ if (path.isAbsolute(file) && existsSync(file)) candidate.dependencies.add(file);
302
+ }
303
+ } };
304
+ // Include non-module assets conservatively in the verified warm cache.
305
+ function assets(directory) {
306
+ for (const item of readdirSync(directory, { withFileTypes: true })) {
307
+ if (item.isSymbolicLink() || ["node_modules", ".ds", ".vite", "dist"].includes(item.name)) continue;
308
+ const file = path.join(directory, item.name);
309
+ if (item.isDirectory()) assets(file);
310
+ else if (/\.(?:css|svg|png|jpe?g|webp|gif|woff2?|ttf|otf)$/.test(file)) candidate.dependencies.add(file);
311
+ }
312
+ }
313
+ assets(options.dsRoot);
314
+ candidate.build = Promise.resolve().then(() => {
315
+ cache.assertCompiler();
316
+ const cached = cachedPreviewPublication(options, candidate.entries, cache.graphRevision());
317
+ if (cached && candidate.entries.every(entry => cache.reusable(entry, previewArtifactHtml(entry.id, cached.revision)))) { candidate.reused = true; return cached; }
318
+ return buildGraph(candidate.entries, options, track, { watched: true });
319
+ });
320
+ liveCandidate = candidate;
321
+ try {
322
+ const publication = await candidate.build;
323
+ if (stopped || candidate !== liveCandidate || candidate.generation !== generation || stamp !== cache.inputs()) return;
324
+ if (publication.publishLive) {
325
+ publication.publishLive(reporter.session);
326
+ reporter.live({ revision: publication.revision, sourceRevision });
327
+ }
328
+ reporter.progress("validation");
329
+ } catch (error) {
330
+ // Syntax/build failures should surface immediately even when an unrelated
331
+ // validation command is still running. This candidate can never publish.
332
+ if (!stopped && candidate === liveCandidate && candidate.generation === generation && stamp === cache.inputs()) rejectLive(candidate, error);
333
+ } finally { void verifyLive(); }
334
+ }
335
+ function rejectLive(candidate, error) {
336
+ candidate.failed = true;
337
+ reporter.batch(() => {
338
+ reporter.live(undefined);
339
+ for (const entry of candidate.entries) reporter.error(entry.id, candidate.revisions.get(entry.id), error);
340
+ reporter.progress("idle");
341
+ });
342
+ console.error(error);
343
+ }
344
+ async function verifyLive() {
345
+ if (verifying || stopped) return;
346
+ verifying = true;
347
+ try {
348
+ while (liveCandidate && !stopped) {
349
+ const candidate = liveCandidate;
350
+ const [compiled] = await Promise.allSettled([candidate.build]);
351
+ if (stopped) return;
352
+ if (candidate !== liveCandidate || candidate.generation !== generation || candidate.stamp !== cache.inputs()) {
353
+ if (candidate === liveCandidate) liveCandidate = undefined;
354
+ continue;
355
+ }
356
+ // Give compiled feedback priority before starting CPU-heavy validation.
357
+ // An already running check continues; later edits replace its candidate.
358
+ const inspection=candidate.reused&&candidate.registryReused?Promise.resolve({scenarios:candidate.entries,diagnostics:[]}):inspector.inspect();
359
+ const outcomes = [compiled, ...await Promise.allSettled([gate(candidate.stamp), inspection])];
360
+ if (stopped) return;
361
+ if (candidate !== liveCandidate || candidate.generation !== generation || candidate.stamp !== cache.inputs()) {
362
+ if (candidate === liveCandidate) liveCandidate = undefined;
363
+ continue;
364
+ }
365
+ try {
366
+ if (outcomes[2].status === "rejected") throw outcomes[2].reason;
367
+ const registry = outcomes[2].value;
368
+ if (registry.diagnostics.length) throw new Error(registry.diagnostics.map(item => `${item.file}: ${item.message}`).join("\n"));
369
+ if (JSON.stringify(registry.scenarios) !== JSON.stringify(candidate.entries)) {
370
+ entries = registry.scenarios;
371
+ writeFileSync(path.join(root, ".ds/scenarios/manifest.json"), JSON.stringify({ schemaVersion: 1, scenarios: entries }, null, 2));
372
+ reporter.batch(() => { reporter.setApps(buildApps()); reporter.live(undefined); reporter.progress("idle"); });
373
+ liveCandidate = undefined;
374
+ for (const id of requested) if (!entries.some(entry => entry.id === id)) requested.delete(id);
375
+ request(false);
376
+ for (const id of requested) pending.add(id);
377
+ void drain();
378
+ continue;
379
+ }
380
+ if (candidate.failed) { if (candidate === liveCandidate) liveCandidate = undefined; continue; }
381
+ const failed = outcomes.find(outcome => outcome.status === "rejected");
382
+ if (failed) throw failed.reason;
383
+ cache.assertCompiler();
384
+ const publication = outcomes[0].value;
385
+ if (stopped || candidate !== liveCandidate || candidate.generation !== generation || candidate.stamp !== cache.inputs()) continue;
386
+ publication.publish(reporter.session);
387
+ if (!candidate.reused) cache.recordAll(candidate.entries, candidate.dependencies, publication.revision);
388
+ else cache.recordGraph(publication.revision,candidate.entries);
389
+ reporter.batch(() => {
390
+ for (const entry of candidate.entries) reporter.ready(entry.id, candidate.revisions.get(entry.id));
391
+ reporter.live(undefined);
392
+ reporter.progress("idle");
393
+ });
394
+ publishedStamp = candidate.stamp;
395
+ } catch (error) {
396
+ if (!candidate.failed) rejectLive(candidate, error);
397
+ }
398
+ if (candidate === liveCandidate) liveCandidate = undefined;
399
+ }
400
+ } finally { verifying = false; }
401
+ }
233
402
  async function drain() {
234
403
  if (compiling) return;
235
404
  compiling = true;
@@ -258,7 +427,9 @@ export async function runScenarioCompiler(directory, { watched = false, validate
258
427
  const entry = entries.find(entry => entry.artifact === file);
259
428
  if (entry && !requested.has(entry.id)) {
260
429
  requested.add(entry.id);
261
- if (!buildGraph || publishedStamp !== cache.inputs()) pending.add(entry.id);
430
+ const covered = liveCandidate && !liveCandidate.failed && liveCandidate.generation === generation
431
+ && liveCandidate.stamp === cache.inputs() && liveCandidate.entries.some(item => item.id === entry.id);
432
+ if (!buildGraph || publishedStamp !== cache.inputs() && !covered) pending.add(entry.id);
262
433
  }
263
434
  }
264
435
  if (startBuild) void drain();
@@ -283,7 +454,10 @@ export async function runScenarioCompiler(directory, { watched = false, validate
283
454
  validation = undefined;
284
455
  const changes = [...changed]; changed.clear();
285
456
  try {
286
- entries = registry();
457
+ // Registry inspection for live graphs runs in the verification worker.
458
+ // Existing entry identities can compile immediately while it checks.
459
+ if (buildGraph) options = withPreviewSession(loadConfig(root), process.env.ADS_MCP_BUILD_SESSION);
460
+ else entries = registry();
287
461
  observedSourceRevision = previewSourceRevision(options);
288
462
  registryFailure = undefined;
289
463
  reporter.setApps(buildApps());
@@ -310,7 +484,7 @@ export async function runScenarioCompiler(directory, { watched = false, validate
310
484
  const stat = statSync(directory), identity = `${stat.dev}:${stat.ino}`;
311
485
  if (watchers.get(directory)?.identity === identity) return false;
312
486
  watchers.get(directory)?.watcher.close();
313
- const watcher = watch(directory, { recursive }, callback);
487
+ const watcher = watch(directory, { recursive }, (event, file) => callback(event, file, event === "rename"));
314
488
  watchers.set(directory, { watcher, identity });
315
489
  watcher.on("error", error => {
316
490
  watcher.close();
@@ -329,7 +503,7 @@ export async function runScenarioCompiler(directory, { watched = false, validate
329
503
  if (directory === root) continue;
330
504
  wanted.add(directory);
331
505
  const relative = path.relative(root, directory);
332
- if (addWatch(directory, (event, file) => sourceChanged(event, file && path.join(relative, file))) && !initial) sourceChanged("rename", relative, true);
506
+ if (addWatch(directory, (event, file, topology) => sourceChanged(event, file && path.join(relative, file), topology)) && !initial) sourceChanged("rename", relative, true);
333
507
  }
334
508
  mkdirSync(path.join(root, ".ds"), { recursive: true });
335
509
  addWatch(path.join(root, ".ds"), (_event, file) => { if (file === path.basename(process.env.ADS_MCP_REQUEST_FILE ?? "")) request(); });
@@ -355,6 +529,7 @@ export async function runScenarioCompiler(directory, { watched = false, validate
355
529
  console.log(`Scenario compiler ready: ${entries.length} entries; builds are requested on demand.`);
356
530
  for (const signal of ["SIGINT", "SIGTERM"]) process.once(signal, () => {
357
531
  stopped = true; clearTimeout(timer); clearInterval(reconcileTimer); for (const { watcher } of watchers.values()) watcher.close();
532
+ void inspector?.close();
358
533
  void buildGraph?.close?.();
359
534
  });
360
535
  }