@reqvire-org/ads 0.4.5 → 0.4.7

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.
@@ -110,8 +110,20 @@ export async function inspectBehaviorLibraries(options, program) {
110
110
  `${name} is declared but not installed in this project. Install the project dependencies.`,
111
111
  name,
112
112
  );
113
- return { name, version: installed?.version ?? null, units: [] };
113
+ const pinned = config.packageVersions?.[name];
114
+ if (installed && pinned && installed.version !== pinned)
115
+ report("ds.config.json", null, "behavior-library-version", `${name}@${pinned} is pinned in ds.config.json but ${installed.version ?? "an unknown version"} is installed. Install the pinned version or update the pin.`, name);
116
+ return { name, version: installed?.version ?? null, ...(pinned ? { pinned } : {}), units: [] };
114
117
  });
118
+ // The framework pin is checked the same way (preact or react).
119
+ const frameworkPin = config.framework && config.packageVersions?.[config.framework];
120
+ if (frameworkPin) {
121
+ const installed = installedPackage(root, config.framework);
122
+ if (!installed)
123
+ report("ds.config.json", null, "behavior-library-missing", `${config.framework} is the configured framework but not installed in this project. Install the project dependencies.`, config.framework);
124
+ else if (installed.version !== frameworkPin)
125
+ report("ds.config.json", null, "behavior-library-version", `${config.framework}@${frameworkPin} is pinned in ds.config.json but ${installed.version ?? "an unknown version"} is installed. Install the pinned version or update the pin.`, config.framework);
126
+ }
115
127
  for (const source of sources) {
116
128
  const used = new Set(),
117
129
  local = new Set();
package/dist/capture.mjs CHANGED
@@ -112,7 +112,7 @@ export function createCaptureController(root) {
112
112
  const project = projects[app.projectIndex];
113
113
  images.set(`${app.projectIndex}:${app.selectionIndex}`, { mimeType: "image/png", blob: bytes.toString("base64"), digest: `sha256:${createHash("sha256").update(bytes).digest("hex")}`, width: metadata.width, height: metadata.height, bytes: bytes.length, capturedAt: value.images[index].capturedAt, sourceRevision: project.revision, buildRevision: hosts[app.projectIndex].previewRevision(), settings: { theme: app.theme, ...(app.brand ? { brand: app.brand } : {}), viewport: app.viewport, animations: app.animations, guides: app.guides, browser: settings.browser, ...(settings.channel ? { channel: settings.channel } : {}), scale: "css" }, scenarioFile: app.scenarioFile, fixtureFile: app.fixtureFile });
114
114
  }
115
- for (const project of projects) if ((await previewSourceRevision(loadConfig(project.options.root)))!==project.revision)throw new Error("Project inputs changed while capturing. No capture slots were replaced; retry against current source.");
115
+ for (const project of projects) if ((await previewSourceRevision(loadConfig(project.options.root),[],{fresh:true}))!==project.revision)throw new Error("Project inputs changed while capturing. No capture slots were replaced; retry against current source.");
116
116
  if (signal.aborted) throw new Error("Screenshot capture cancelled before publication.");
117
117
  update("publishing", apps.length, apps.length);
118
118
  const records = selections.map((selection, index) =>( { schemaVersion: 1, key: captureKey(selection), scenario: selection.scenario, ...(selection.target ? { target: selection.target } : {}), current: images.get(`0:${index}`) ?? null, ...(!images.has(`0:${index}`) ? { proposedTarget: true } : {}), candidate: candidateRoot ? { ...images.get(`1:${index}`), baseRevision: projects[0].revision, proposal } : null }));
package/dist/config.mjs CHANGED
@@ -301,14 +301,28 @@ export function loadConfig(directory = process.cwd()) {
301
301
  throw new Error("validation.inputs must name canonical source paths below the project root, excluding dependency and metadata directories.");
302
302
  }
303
303
  if (config.schemaVersion !== 1) throw new Error(`Unsupported ADS config version: ${config.schemaVersion}`);
304
- if (user.framework !== undefined && !supportedFrameworks.includes(user.framework)) throw new Error("framework must be react or preact.");
305
- if (
306
- !Array.isArray(config.behaviorLibraries) ||
307
- config.behaviorLibraries.length > 100 ||
308
- new Set(config.behaviorLibraries).size !== config.behaviorLibraries.length ||
309
- config.behaviorLibraries.some((name) => typeof name !== "string" || name.length > 214 || !/^(?:@[a-z0-9][a-z0-9._~-]*\/)?[a-z0-9][a-z0-9._~-]*$/.test(name))
310
- )
311
- throw new Error("behaviorLibraries must contain up to 100 unique npm package names, without versions, subpaths or wildcards.");
304
+ // Packages may pin an exact installed version: "preact@10.27.2", "elkjs@0.9.3".
305
+ // The rest of ADS sees plain names; packageVersions keeps the pins.
306
+ const packageVersions = {};
307
+ const pinned = (value) => {
308
+ const match = typeof value === "string" ? /^((?:@[a-z0-9][a-z0-9._~-]*\/)?[a-z0-9][a-z0-9._~-]*)(?:@(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?))?$/.exec(value) : null;
309
+ if (match?.[2]) packageVersions[match[1]] = match[2];
310
+ return match?.[1];
311
+ };
312
+ if (user.framework !== undefined) {
313
+ const name = pinned(user.framework);
314
+ if (!supportedFrameworks.includes(name)) throw new Error("framework must be react or preact, optionally pinned to an exact version such as preact@10.27.2.");
315
+ config.framework = name;
316
+ }
317
+ if (!Array.isArray(config.behaviorLibraries) || config.behaviorLibraries.length > 100)
318
+ throw new Error("behaviorLibraries must contain up to 100 npm package names, optionally pinned to an exact version (name@1.2.3).");
319
+ const libraries = config.behaviorLibraries.map((value) => (typeof value === "string" && value.length <= 230 ? pinned(value) : undefined));
320
+ if (libraries.some((name) => !name || name.length > 214) || new Set(libraries).size !== libraries.length)
321
+ throw new Error("behaviorLibraries must contain up to 100 unique npm package names, optionally pinned to an exact version (name@1.2.3), without subpaths, ranges or wildcards.");
322
+ config.behaviorLibraries = libraries;
323
+ // Not a ds.config.json field: kept off enumeration so a serialized config
324
+ // never gains it; the pins themselves stay in the saved name@version strings.
325
+ Object.defineProperty(config, "packageVersions", { value: packageVersions, enumerable: false });
312
326
  const sourceRoot = projectPath(root, config.sourceDir, "sourceDir");
313
327
  const dsRoot = projectPath(root, config.dsDir, "dsDir");
314
328
  for (const field of ["publicDirs", "generatedPaths", "generatedFiles"]) {
package/dist/init.mjs CHANGED
@@ -229,7 +229,9 @@ export async function initProject(directory = process.cwd(), { toolPackage, fram
229
229
  const saved = JSON.parse(original);
230
230
  if (saved.framework === undefined || !existingTokens.length) {
231
231
  const indent = original.match(/\n([\t ]+)"/)?.[1] ?? " ";
232
- updates.set(configFile, `${JSON.stringify({ ...saved, framework: selectedFramework }, null, indent)}\n`);
232
+ // Keep a pinned "preact@1.2.3" when it already names the selected framework.
233
+ const keep = typeof saved.framework === "string" && saved.framework.split("@")[0] === selectedFramework;
234
+ updates.set(configFile, `${JSON.stringify({ ...saved, framework: keep ? saved.framework : selectedFramework }, null, indent)}\n`);
233
235
  }
234
236
  }
235
237
  // The framework's scenario mount, as the starter has it.
@@ -0,0 +1,270 @@
1
+ import { createHash } from "node:crypto";
2
+ import { lstatSync, readFileSync, statSync, watch } from "node:fs";
3
+ import path from "node:path";
4
+ import { outsideInputRequestScope } from "./input-scope.mjs";
5
+
6
+ // An incrementally maintained content-digest map for one input-set definition.
7
+ // A full walk seeds it; file events name what to re-read and re-hash. Equal size
8
+ // or modification time never counts as "unchanged": every reported file is read
9
+ // again, and a periodic full walk remains the safety net for missed events.
10
+ //
11
+ // An input set describes membership, so later narrower sets (for example only
12
+ // the design system) reuse the same map, watcher and fallbacks:
13
+ // load() -> options for the current configuration
14
+ // key(options) -> identity of the membership definition
15
+ // capture(options, { onFile }) -> full walk: { relative: "sha256:…" | null }
16
+ // signature(file, bytes, rev) -> what a file's content adds to membership
17
+ // structural(relative, options)-> a change here can alter membership itself
18
+ // ignored(relative, options) -> never an input (generated output, metadata)
19
+ // directories(options) -> directories (or single files) to watch
20
+
21
+ const digestOf = (content) => `sha256:${createHash("sha256").update(content).digest("hex")}`;
22
+ const slash = (file) => file.replaceAll("\\", "/");
23
+
24
+ /** `onUpdate(digests)` receives each changed map, so the owning process can publish
25
+ * it; `onPending()` fires synchronously when an event makes the map provisional
26
+ * (before any re-read), so readers never treat the old map as current meanwhile. */
27
+ export function createInputDigests(root, inputSet, { watchFiles = true, fallbackMs = 30000, onError, onUpdate, onPending } = {}) {
28
+ let options,
29
+ key,
30
+ digests = new Map(),
31
+ signatures = new Map(),
32
+ ready = false,
33
+ structural = true, // Membership must be (re)established by a full walk.
34
+ background, // A periodic safety-net walk that requests need not wait for.
35
+ closed = false,
36
+ lastWalk = 0,
37
+ fullWalks = 0,
38
+ incrementalReads = 0,
39
+ version = 0,
40
+ published = -1,
41
+ provisional = false;
42
+ // Called on every event that may change the map (dirty file or structural change).
43
+ const markPending = () => {
44
+ if (provisional) return;
45
+ provisional = true;
46
+ try {
47
+ onPending?.();
48
+ } catch (error) {
49
+ onError?.(error);
50
+ }
51
+ };
52
+ const dirty = new Set();
53
+ const watchers = new Map();
54
+ const collectors = new Set(); // Events observed while each walk was reading files.
55
+ let lock = Promise.resolve();
56
+ const serialized = (work) => {
57
+ const run = lock.then(work);
58
+ lock = run.catch(() => {});
59
+ return run;
60
+ };
61
+
62
+ function notify(relative, kind = "change") {
63
+ if (closed) return;
64
+ if (relative === null || relative === undefined || relative === "") {
65
+ // Coalesced or unnamed events (for example on macOS): rescan.
66
+ structural = true;
67
+ markPending();
68
+ for (const events of collectors) events.add("*");
69
+ return;
70
+ }
71
+ relative = slash(path.normalize(relative));
72
+ if (relative.startsWith("../") || path.isAbsolute(relative)) return;
73
+ for (const events of collectors) events.add(relative);
74
+ if (options && inputSet.ignored(relative, options)) {
75
+ if (inputSet.structural(relative, options)) {
76
+ structural = true;
77
+ markPending();
78
+ }
79
+ return;
80
+ }
81
+ if (digests.has(relative)) {
82
+ dirty.add(relative);
83
+ markPending();
84
+ }
85
+ // A new or renamed path may be a new input (or a directory of them).
86
+ else if (kind === "rename" || !options || inputSet.structural(relative, options)) {
87
+ structural = true;
88
+ markPending();
89
+ }
90
+ }
91
+
92
+ // Watch handles outlive the request that happened to trigger a walk.
93
+ const reconcileWatches = () => outsideInputRequestScope(watchDirectories);
94
+ function watchDirectories() {
95
+ if (!watchFiles || closed) return;
96
+ const wanted = new Set(inputSet.directories(options));
97
+ for (const [directory, watcher] of watchers)
98
+ if (!wanted.has(directory)) {
99
+ watcher.close();
100
+ watchers.delete(directory);
101
+ }
102
+ for (const directory of wanted) {
103
+ if (watchers.has(directory)) continue;
104
+ try {
105
+ const relative = path.relative(root, directory);
106
+ // A single file (such as ds.config.json) is watched directly; an editor that
107
+ // replaces it ends that watch, so drop it and re-add it after the next walk.
108
+ const single = statSync(directory).isFile();
109
+ const watcher = watch(directory, (event, file) => {
110
+ if (!single) return notify(file ? path.join(relative, file.toString()) : null, event);
111
+ notify(relative, event);
112
+ if (event === "rename") {
113
+ watcher.close();
114
+ if (watchers.get(directory) === watcher) watchers.delete(directory);
115
+ }
116
+ });
117
+ watcher.on("error", (error) => {
118
+ watcher.close();
119
+ if (watchers.get(directory) === watcher) watchers.delete(directory);
120
+ structural = true; // A lost watch is a missed-event risk: walk again.
121
+ onError?.(error);
122
+ });
123
+ watchers.set(directory, watcher);
124
+ } catch (error) {
125
+ structural = true;
126
+ onError?.(error);
127
+ }
128
+ }
129
+ }
130
+
131
+ /** Read everything without touching the map; `apply` installs the result. */
132
+ async function walkInputs() {
133
+ const next = inputSet.load(),
134
+ seen = new Map(),
135
+ pending = [],
136
+ events = new Set();
137
+ collectors.add(events);
138
+ try {
139
+ const result = await inputSet.capture(next, {
140
+ onFile(relative, content, revision) {
141
+ pending.push(Promise.resolve(inputSet.signature(path.resolve(root, relative), content, revision)).then((value) => seen.set(relative, value)));
142
+ },
143
+ });
144
+ await Promise.all(pending);
145
+ return { next, result, seen, events };
146
+ } finally {
147
+ collectors.delete(events);
148
+ }
149
+ }
150
+ function apply({ next, result, seen, events }) {
151
+ options = next;
152
+ key = inputSet.key(next);
153
+ digests = new Map(Object.entries(result));
154
+ signatures = seen;
155
+ ready = true;
156
+ structural = false;
157
+ lastWalk = Date.now();
158
+ fullWalks++;
159
+ version++;
160
+ dirty.clear();
161
+ // The walk may have read a file before an event for it: read those again.
162
+ for (const relative of events) notify(relative === "*" ? null : relative, "change");
163
+ reconcileWatches();
164
+ }
165
+ async function fullWalk() {
166
+ try {
167
+ apply(await walkInputs());
168
+ } catch (error) {
169
+ structural = true; // Never answer from a partial or failed walk.
170
+ throw error;
171
+ }
172
+ }
173
+
174
+ async function refreshDirty() {
175
+ for (const relative of dirty) {
176
+ dirty.delete(relative);
177
+ const previous = digests.get(relative);
178
+ if (previous === null || inputSet.structural(relative, options)) return (structural = true);
179
+ let content;
180
+ try {
181
+ const stat = lstatSync(path.join(root, relative));
182
+ if (!stat.isFile()) return (structural = true); // Deleted, replaced by a directory or symlink.
183
+ content = readFileSync(path.join(root, relative));
184
+ } catch {
185
+ return (structural = true);
186
+ }
187
+ incrementalReads++;
188
+ const revision = digestOf(content);
189
+ if (revision === previous) continue;
190
+ const signature = await inputSet.signature(path.join(root, relative), content, revision);
191
+ if (signature !== signatures.get(relative)) return (structural = true); // References changed: membership may differ.
192
+ digests.set(relative, revision);
193
+ version++;
194
+ }
195
+ return false;
196
+ }
197
+
198
+ /** The current digest map. Queued events are applied first; a structural
199
+ * change (or no map yet) waits for a full walk, never an older answer. */
200
+ function current() {
201
+ return serialized(async () => {
202
+ if (closed) throw new Error("The input digest map is closed.");
203
+ // Let already delivered watcher callbacks run before answering.
204
+ await new Promise((resolve) => setImmediate(resolve));
205
+ for (let attempt = 0; attempt < 5; attempt++) {
206
+ if (!ready || structural || inputSet.key(inputSet.load()) !== key) {
207
+ await fullWalk();
208
+ continue;
209
+ }
210
+ if (await refreshDirty()) continue;
211
+ if (!structural) {
212
+ const result = Object.fromEntries([...digests].sort(([a], [b]) => a.localeCompare(b)));
213
+ const settled = provisional;
214
+ provisional = false;
215
+ if (onUpdate && (version !== published || settled)) {
216
+ published = version;
217
+ try {
218
+ onUpdate(result);
219
+ } catch (error) {
220
+ onError?.(error);
221
+ }
222
+ }
223
+ return result;
224
+ }
225
+ }
226
+ throw new Error("Project inputs kept changing while their digests were read. Retry against the current source.");
227
+ });
228
+ }
229
+
230
+ // Periodic safety net: a full walk replaces the map only if no structural
231
+ // change is pending; requests keep answering from the map meanwhile.
232
+ const timer =
233
+ fallbackMs > 0
234
+ ? setInterval(() => {
235
+ if (closed || background || !ready || Date.now() - lastWalk < fallbackMs) return;
236
+ // Read outside the lock; install only if nothing structural happened meanwhile.
237
+ background = walkInputs()
238
+ .then((walk) =>
239
+ serialized(() => {
240
+ if (!closed && !structural) apply(walk);
241
+ }),
242
+ )
243
+ .catch((error) => onError?.(error))
244
+ .finally(() => {
245
+ background = undefined;
246
+ });
247
+ }, Math.min(fallbackMs, 5000))
248
+ : null;
249
+ timer?.unref?.();
250
+
251
+ return {
252
+ root,
253
+ matches: (candidate) => ready && !structural && inputSet.key(candidate) === key,
254
+ key: (candidate) => inputSet.key(candidate),
255
+ current,
256
+ notify,
257
+ /** Force the next answer to come from a full walk (for example after a watcher restart). */
258
+ invalidate() {
259
+ structural = true;
260
+ },
261
+ stats: () => ({ fullWalks, incrementalReads, watched: watchers.size, ready, pending: dirty.size, structural }),
262
+ close() {
263
+ closed = true;
264
+ if (timer) clearInterval(timer);
265
+ for (const watcher of watchers.values()) watcher.close();
266
+ watchers.clear();
267
+ },
268
+ };
269
+ }
270
+
@@ -0,0 +1,57 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+
3
+ // One read-only request (tool call, resource read or preview wait) captures the
4
+ // project's inputs once. Digests stay content-based: the scope only removes
5
+ // repeated walks within that request and is discarded with it.
6
+ const scope = new AsyncLocalStorage();
7
+
8
+ /** Run read-only work in one input revision; nested calls join the outer request.
9
+ * `own` starts a separate revision even inside a request: background passes
10
+ * (polling, refresh loops) must not inherit the walk of the request that
11
+ * happened to start them. */
12
+ let scopes = 0;
13
+ export function withInputRequestScope(run, { own = false, label = "request" } = {}) {
14
+ return scope.getStore() && !own ? run() : scope.run({ inputs: new Map(), id: `${label}#${++scopes}` }, run);
15
+ }
16
+
17
+ /** Profiling label of the current request scope, if any. */
18
+ export const inputRequestScopeId = () => scope.getStore()?.id;
19
+
20
+ /** Long-lived work (child processes, timers, shared tasks) started during a
21
+ * request must not keep that request's revision alive or answer from it later. */
22
+ export function outsideInputRequestScope(run) {
23
+ return scope.getStore() ? scope.exit(run) : run();
24
+ }
25
+
26
+ const omitted = new Set(["signal"]);
27
+ /** Every serializable option can affect membership; functions/signals cannot. */
28
+ export function inputScopeKey(options) {
29
+ return JSON.stringify(options, (key, value) => (omitted.has(key) || typeof value === "function" ? undefined : value));
30
+ }
31
+
32
+ /**
33
+ * Reuse this request's walk for `key`. `fresh` re-walks and replaces it (a
34
+ * content fence after long work). `observed` names external evidence, such as
35
+ * the build report bytes: a different value than the walk was paired with means
36
+ * something changed since, so the inputs are walked again.
37
+ * `contents` asks for file bytes to replay to an onFile consumer.
38
+ */
39
+ export function scopedInputs(key, walk, { fresh = false, observed, contents = false } = {}) {
40
+ const store = scope.getStore();
41
+ if (!store) return walk(contents);
42
+ let entry = store.inputs.get(key);
43
+ const changed = observed !== undefined && entry?.observed !== undefined && entry.observed !== observed;
44
+ if (!entry || fresh || changed || (contents && !entry.contents)) {
45
+ entry = { promise: walk(contents), contents };
46
+ store.inputs.set(key, entry);
47
+ // A failed walk must not answer later reads in the same request.
48
+ entry.promise.catch(() => {
49
+ if (store.inputs.get(key) === entry) store.inputs.delete(key);
50
+ });
51
+ }
52
+ if (observed !== undefined) entry.observed = observed;
53
+ return entry.promise;
54
+ }
55
+
56
+ /** Test/profiling hook: whether the caller runs inside a request scope. */
57
+ export const inInputRequestScope = () => scope.getStore() !== undefined;
@@ -5,6 +5,8 @@ import { z } from "zod";
5
5
  import { isInside, projectPath, loadConfig } from "../config.mjs";
6
6
  import { previewSourceRevision } from "../preview-inputs.mjs";
7
7
  import { readPreviewManifest } from "../preview-resources.mjs";
8
+ import timing from "../stage-timing.cjs";
9
+ import { compilerChannel } from "./compiler-channel.mjs";
8
10
  import { livePreviewOptions, previewArtifactPath, withPreviewSession } from "../preview-scope.mjs";
9
11
 
10
12
  import { previewFailureTitle, previewDiagnosticText } from "../preview-failure.mjs";
@@ -105,12 +107,15 @@ function normalizedDiagnostics(root, value) {
105
107
  return errors.slice(0, 20).map((error) => normalizeDiagnostic(root, error));
106
108
  }
107
109
 
108
- /** One publisher per project compiler; no dependency on a UI framework. */
110
+ /** One publisher per project compiler; no dependency on a UI framework. A compiler
111
+ * managed by MCP reports over its channel; standalone compilation (or an explicit
112
+ * `file`) keeps a durable status file. */
109
113
  export function createBuildReporter(
110
114
  directory,
111
115
  { apps, session = process.env.ADS_MCP_BUILD_SESSION ?? randomUUID(), file = process.env.ADS_MCP_BUILD_STATUS } = {},
112
116
  ) {
113
117
  const root = path.resolve(directory);
118
+ const channel = file === undefined ? compilerChannel() : null;
114
119
  const target = file ?? buildStatusFile(root);
115
120
  if (!isInside(root, target)) throw new Error("Build status must stay inside the project.");
116
121
  const entries = new Map(
@@ -153,6 +158,10 @@ export function createBuildReporter(
153
158
  text = JSON.stringify(snapshot.parse({ ...value, previews, diagnosticSets }));
154
159
  }
155
160
  if (Buffer.byteLength(text) > maxBytes) throw new Error("Build status exceeds 256 KiB. Keep diagnostics bounded.");
161
+ if (channel) {
162
+ channel.send({ type: "report", session, report: JSON.parse(text) });
163
+ return;
164
+ }
156
165
  mkdirSync(path.dirname(target), { recursive: true });
157
166
  if (realpathSync(path.dirname(target)) !== path.dirname(target)) throw new Error("Build status cannot resolve through a symlink.");
158
167
  const temporary = `${target}.${randomUUID()}.tmp`;
@@ -255,15 +264,37 @@ export function createBuildReporter(
255
264
  }
256
265
 
257
266
  /** Read durable build events; a running process alone never means a fresh build. */
258
- export async function inspectBuildStatus(root, config, { session, previewSession, processState, file = buildStatusFile(root) } = {}) {
267
+ export function inspectBuildStatus(root, config, options) {
268
+ return timing.timeStage("build-status", () => readBuildStatus(root, config, options));
269
+ }
270
+ async function readBuildStatus(root, config, { session, previewSession, processState, file = buildStatusFile(root), ...supplied } = {}) {
259
271
  const options = withPreviewSession({ root, config: { mcp: config } }, previewSession);
260
272
  let report;
261
273
  let reportError;
262
- try {
274
+ // The report's exact bytes pair with the input walk: within one request the
275
+ // inputs are walked again only after the compiler reported something new.
276
+ let observed = "absent";
277
+ // A managed compiler's latest report arrives over its channel (`report`, possibly
278
+ // null before the first one); standalone compilation reads its durable file.
279
+ if (Object.hasOwn(supplied, "report")) {
280
+ try {
281
+ if (supplied.report) {
282
+ const text = JSON.stringify(supplied.report);
283
+ if (Buffer.byteLength(text) > maxBytes) throw new Error("Build status must be under 256 KiB.");
284
+ observed = createHash("sha256").update(text).digest("hex");
285
+ report = snapshot.parse(supplied.report);
286
+ if (session && report.session !== session) report = undefined;
287
+ }
288
+ } catch (error) {
289
+ reportError = `Invalid preview build status: ${error.message.slice(0, 500)}`;
290
+ }
291
+ } else try {
263
292
  if (!isInside(root, path.resolve(file))) throw new Error("Build status must stay inside the project.");
264
293
  if (existsSync(file)) {
265
294
  if (realpathSync(file) !== file || statSync(file).size > maxBytes) throw new Error("Build status must be a real project file under 256 KiB.");
266
- report = snapshot.parse(JSON.parse(readFileSync(file, "utf8")));
295
+ const text = readFileSync(file, "utf8");
296
+ observed = createHash("sha256").update(text).digest("hex");
297
+ report = snapshot.parse(JSON.parse(text));
267
298
  if (session && report.session !== session) report = undefined;
268
299
  }
269
300
  } catch (error) {
@@ -276,7 +307,7 @@ export async function inspectBuildStatus(root, config, { session, previewSession
276
307
  let sourceRevision, sourceError;
277
308
  if (report?.live || report?.previews.some((entry) => entry.state === "ready")) {
278
309
  try {
279
- sourceRevision = await previewSourceRevision(loadConfig(root), config.apps ?? []);
310
+ sourceRevision = await previewSourceRevision(loadConfig(root), config.apps ?? [], { observed });
280
311
  } catch (error) {
281
312
  sourceError = `Cannot verify preview inputs: ${error.message}`;
282
313
  }
@@ -0,0 +1,145 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { mkdtempSync, rmSync } from "node:fs";
3
+ import net from "node:net";
4
+ import os from "node:os";
5
+ import path from "node:path";
6
+
7
+ // Direct coordination between an MCP preview watcher and its compiler process:
8
+ // requests, draft control, change notices, build reports and digests travel as
9
+ // newline-delimited JSON over a private local socket (a Unix socket in a 0700
10
+ // directory, or a named pipe on Windows) with a per-launch token. Unlike an
11
+ // inherited IPC descriptor, the address survives any configured compiler command
12
+ // or wrapper because it travels in the environment. Source files, preview
13
+ // artifacts and resources are not on this channel.
14
+
15
+ const maxLine = 16 * 1024 * 1024;
16
+
17
+ function lines(connection, onLine) {
18
+ let buffer = "";
19
+ connection.setEncoding("utf8");
20
+ connection.on("data", (chunk) => {
21
+ buffer += chunk;
22
+ if (buffer.length > maxLine) return connection.destroy(new Error("Compiler channel message exceeds 16 MiB."));
23
+ for (let index = buffer.indexOf("\n"); index >= 0; index = buffer.indexOf("\n")) {
24
+ const line = buffer.slice(0, index);
25
+ buffer = buffer.slice(index + 1);
26
+ if (!line) continue;
27
+ let message;
28
+ try {
29
+ message = JSON.parse(line);
30
+ } catch {
31
+ return connection.destroy(new Error("Malformed compiler channel message."));
32
+ }
33
+ if (message && typeof message === "object" && typeof message.type === "string") onLine(message);
34
+ }
35
+ });
36
+ }
37
+
38
+ /** MCP side. `state(key, message)` keeps the latest message per key and replays
39
+ * it when a (re)started compiler connects; `send` is fire-and-forget. */
40
+ export function createCompilerChannel({ onMessage, onConnect } = {}) {
41
+ const token = randomUUID();
42
+ const directory = process.platform === "win32" ? null : mkdtempSync(path.join(os.tmpdir(), "ads-ch-"));
43
+ const address = directory ? path.join(directory, "s") : `\\\\.\\pipe\\ads-${randomUUID()}`;
44
+ const latest = new Map();
45
+ let peer,
46
+ closed = false;
47
+ const write = (message) => {
48
+ if (peer && !peer.destroyed) peer.write(`${JSON.stringify(message)}\n`);
49
+ };
50
+ const server = net.createServer((connection) => {
51
+ let trusted = false;
52
+ connection.on("error", () => {});
53
+ connection.on("close", () => {
54
+ if (peer === connection) peer = undefined;
55
+ });
56
+ lines(connection, (message) => {
57
+ if (!trusted) {
58
+ if (message.type !== "hello" || message.token !== token) return connection.destroy();
59
+ trusted = true;
60
+ if (peer && peer !== connection) peer.destroy();
61
+ peer = connection;
62
+ for (const value of latest.values()) write(value);
63
+ onConnect?.();
64
+ return;
65
+ }
66
+ onMessage?.(message);
67
+ });
68
+ });
69
+ server.on("error", () => {});
70
+ server.listen(address);
71
+ server.unref();
72
+ return {
73
+ env: { ADS_MCP_CHANNEL: address, ADS_MCP_CHANNEL_TOKEN: token },
74
+ state(key, message) {
75
+ latest.set(key, message);
76
+ write(message);
77
+ },
78
+ forget(key) {
79
+ latest.delete(key);
80
+ },
81
+ send: write,
82
+ connected: () => !!peer,
83
+ close() {
84
+ if (closed) return;
85
+ closed = true;
86
+ peer?.destroy();
87
+ server.close();
88
+ if (directory) rmSync(directory, { recursive: true, force: true });
89
+ },
90
+ };
91
+ }
92
+
93
+ let shared;
94
+ /** Compiler side: the process-wide connection named by the environment, or
95
+ * null for standalone compilation (which keeps its durable status file). */
96
+ export function compilerChannel() {
97
+ if (shared !== undefined) return shared;
98
+ const address = process.env.ADS_MCP_CHANNEL,
99
+ token = process.env.ADS_MCP_CHANNEL_TOKEN;
100
+ if (!address || !token) return (shared = null);
101
+ const handlers = new Map(),
102
+ queue = [],
103
+ // The latest message per type and session, for handlers registered after it
104
+ // arrived (the watcher replays its state as soon as the connection opens).
105
+ last = new Map();
106
+ let connection,
107
+ ready = false,
108
+ attempts = 0;
109
+ const deliver = (message) => {
110
+ last.set(`${message.type}\0${message.session ?? ""}`, message);
111
+ for (const handler of handlers.get(message.type) ?? []) handler(message);
112
+ };
113
+ function connect() {
114
+ connection = net.connect(address);
115
+ connection.on("connect", () => {
116
+ ready = true;
117
+ connection.write(`${JSON.stringify({ type: "hello", token })}\n`);
118
+ for (const line of queue.splice(0)) connection.write(line);
119
+ });
120
+ connection.on("error", () => {});
121
+ connection.on("close", () => {
122
+ ready = false;
123
+ // The MCP process listens before it launches the compiler; retry briefly
124
+ // for a slow start, then give up (the ownership guard ends this process).
125
+ if (++attempts <= 50) setTimeout(connect, 100).unref();
126
+ });
127
+ lines(connection, deliver);
128
+ connection.unref();
129
+ }
130
+ connect();
131
+ shared = {
132
+ send(message) {
133
+ const line = `${JSON.stringify(message)}\n`;
134
+ if (ready) connection.write(line);
135
+ else queue.push(line);
136
+ },
137
+ on(type, handler) {
138
+ if (!handlers.has(type)) handlers.set(type, new Set());
139
+ handlers.get(type).add(handler);
140
+ for (const [key, message] of last) if (key.startsWith(`${type}\0`)) handler(message);
141
+ return () => handlers.get(type)?.delete(handler);
142
+ },
143
+ };
144
+ return shared;
145
+ }