@reqvire-org/ads 0.3.33 → 0.3.34
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/behavior-libraries.mjs +93 -0
- package/dist/behaviors.mjs +0 -6
- package/dist/bootstrap-ds/ds.config.json +1 -0
- package/dist/capture.mjs +3 -3
- package/dist/check.mjs +2 -0
- package/dist/config.mjs +4 -0
- package/dist/lint-config.mjs +7 -0
- package/dist/mcp/build-status.mjs +1 -1
- package/dist/mcp/catalog.mjs +4 -2
- package/dist/mcp/draft-discovery.mjs +55 -0
- package/dist/mcp/drafts.mjs +135 -16
- package/dist/mcp/preview-watch.mjs +13 -2
- package/dist/mcp/preview-widget.bundle.js +14 -14
- package/dist/mcp/server.mjs +109 -27
- package/dist/scenario-inspector.mjs +5 -5
- package/dist/scenario-program.mjs +36 -0
- package/dist/scenario-registry.mjs +90 -0
- package/dist/scenarios-compiler.mjs +66 -22
- package/dist/scenarios.mjs +2 -1
- package/dist/showcase/client.bundle.js +39 -39
- package/dist/showcase/comparison.js +29 -5
- package/dist/showcase/draft-navigation.js +41 -0
- package/dist/showcase/index.html +1 -2
- package/dist/showcase/preview-state.js +19 -0
- package/dist/showcase/style.css +2 -2
- package/dist/skills/ads-break-ui/references/behaviors.md +10 -0
- package/dist/skills/ads-break-ui/references/drafts.md +43 -4
- package/dist/skills/ads-break-ui/references/validation.md +6 -0
- package/dist/skills/ads-designer/SKILL.md +7 -0
- package/dist/skills/ads-designer/assets/bootstrap-ds/ds.config.json +1 -0
- package/dist/skills/ads-designer/references/behaviors.md +10 -0
- package/dist/skills/ads-designer/references/drafts.md +43 -4
- package/dist/skills/ads-designer/references/validation.md +6 -0
- package/dist/skills/ads-import/SKILL.md +4 -0
- package/dist/skills/ads-import/references/behaviors.md +10 -0
- package/dist/skills/ads-import/references/drafts.md +43 -4
- package/dist/skills/ads-import/references/validation.md +6 -0
- package/dist/skills/ads-motion/references/behaviors.md +10 -0
- package/dist/skills/ads-motion/references/drafts.md +43 -4
- package/dist/skills/ads-motion/references/validation.md +6 -0
- package/dist/skills/ads-port/SKILL.md +8 -1
- package/dist/skills/ads-port/references/behaviors.md +10 -0
- package/dist/skills/ads-port/references/drafts.md +43 -4
- package/dist/skills/ads-port/references/native-implementation.md +14 -1
- package/dist/skills/ads-port/references/validation.md +6 -0
- package/dist/unit-contracts.mjs +2 -2
- package/dist/units.mjs +6 -0
- package/dist/verification/browser.d.mts +27 -0
- package/dist/verification.mjs +3 -0
- package/docs/ARCHITECTURE.md +82 -0
- package/docs/CHANGELOG.md +92 -0
- package/docs/GUIDE.md +29 -4
- package/docs/MCP.md +44 -4
- package/package.json +6 -4
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
2
|
+
import { isBuiltin } from "node:module";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import ts from "typescript";
|
|
5
|
+
import { isDevelopmentFile, isInside, sourceFiles } from "./config.mjs";
|
|
6
|
+
import { importResolver } from "./boundaries.mjs";
|
|
7
|
+
import { inspectUnits } from "./units.mjs";
|
|
8
|
+
|
|
9
|
+
const packageName = specifier => specifier.startsWith("@") ? specifier.split("/").slice(0, 2).join("/") : specifier.split("/")[0];
|
|
10
|
+
|
|
11
|
+
/** Runtime imports only; development roles retain their existing policies. */
|
|
12
|
+
function imports(source) {
|
|
13
|
+
const result = [];
|
|
14
|
+
function visit(node) {
|
|
15
|
+
if ((ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) && node.moduleSpecifier && ts.isStringLiteralLike(node.moduleSpecifier)) {
|
|
16
|
+
const bindings = ts.isImportDeclaration(node) ? node.importClause : node;
|
|
17
|
+
const named = ts.isImportDeclaration(node) ? bindings?.namedBindings : node.exportClause;
|
|
18
|
+
const typeOnly = bindings?.isTypeOnly || named && (ts.isNamedImports(named) || ts.isNamedExports(named))
|
|
19
|
+
&& named.elements.length > 0 && !bindings?.name && named.elements.every(item => item.isTypeOnly);
|
|
20
|
+
if (!typeOnly) result.push({ node, specifier: node.moduleSpecifier.text });
|
|
21
|
+
}
|
|
22
|
+
if (ts.isCallExpression(node) && (node.expression.kind === ts.SyntaxKind.ImportKeyword || ts.isIdentifier(node.expression) && node.expression.text === "require")
|
|
23
|
+
&& node.arguments[0] && ts.isStringLiteralLike(node.arguments[0])) result.push({ node, specifier: node.arguments[0].text });
|
|
24
|
+
if (ts.isImportEqualsDeclaration(node) && !node.isTypeOnly && ts.isExternalModuleReference(node.moduleReference)
|
|
25
|
+
&& node.moduleReference.expression && ts.isStringLiteralLike(node.moduleReference.expression)) result.push({ node, specifier: node.moduleReference.expression.text });
|
|
26
|
+
ts.forEachChild(node, visit);
|
|
27
|
+
}
|
|
28
|
+
visit(source);
|
|
29
|
+
return result;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function installedPackage(root, name) {
|
|
33
|
+
// Direct dependencies can be workspace-hoisted or package-manager symlinks.
|
|
34
|
+
// Read only their manifest, never execute or inspect third-party source.
|
|
35
|
+
for (let directory = root; ; directory = path.dirname(directory)) {
|
|
36
|
+
const file = path.join(directory, "node_modules", name, "package.json");
|
|
37
|
+
if (existsSync(file)) {
|
|
38
|
+
try { const pkg = JSON.parse(readFileSync(file, "utf8")); return { version: typeof pkg.version === "string" ? pkg.version : null }; } catch { return null; }
|
|
39
|
+
}
|
|
40
|
+
if (path.dirname(directory) === directory) return null;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** An explicit project allowlist, not certification of library internals. */
|
|
45
|
+
export function inspectBehaviorLibraries(options, program) {
|
|
46
|
+
const { root, dsRoot, config } = options;
|
|
47
|
+
const diagnostics = [], inventory = inspectUnits(options), resolve = importResolver(options);
|
|
48
|
+
const declared = config.behaviorLibraries ?? [], allowed = new Set(declared);
|
|
49
|
+
const usage = new Map(), edges = new Map();
|
|
50
|
+
const owner = file => inventory.owner(inventory.relative(path.relative(root, file)));
|
|
51
|
+
const runtime = file => isInside(dsRoot, file) && !isDevelopmentFile(file, options) && !/\.d\.[cm]?ts$/.test(file) && owner(file) !== "configuration";
|
|
52
|
+
const sources = program ? program.getSourceFiles().filter(source => runtime(source.fileName))
|
|
53
|
+
: sourceFiles(dsRoot).filter(file => /\.[cm]?[jt]sx?$/.test(file) && runtime(file))
|
|
54
|
+
.map(file => ts.createSourceFile(file, readFileSync(file, "utf8"), ts.ScriptTarget.Latest, true));
|
|
55
|
+
function report(file, node, rule, message, library) {
|
|
56
|
+
const location = node && file.getLineAndCharacterOfPosition(node.getStart(file));
|
|
57
|
+
diagnostics.push({ file: typeof file === "string" ? file : path.relative(root, file.fileName).replaceAll("\\", "/"), rule,
|
|
58
|
+
line: location ? location.line + 1 : 1, column: location ? location.character + 1 : 1, message, library });
|
|
59
|
+
}
|
|
60
|
+
let pkg = {};
|
|
61
|
+
try { pkg = JSON.parse(readFileSync(path.join(root, "package.json"), "utf8")); } catch { /* Missing dependencies are diagnosed below. */ }
|
|
62
|
+
const libraries = declared.map(name => {
|
|
63
|
+
if (!Object.hasOwn(pkg.dependencies ?? {}, name)) report("ds.config.json", null, "behavior-library-dependency", `${name} is in behaviorLibraries but not package.json dependencies.`, name);
|
|
64
|
+
const installed = installedPackage(root, name);
|
|
65
|
+
if (!installed) report("ds.config.json", null, "behavior-library-missing", `${name} is declared but not installed in this project. Install the project dependencies.`, name);
|
|
66
|
+
return { name, version: installed?.version ?? null, units: [] };
|
|
67
|
+
});
|
|
68
|
+
for (const source of sources) {
|
|
69
|
+
const used = new Set(), local = new Set();
|
|
70
|
+
for (const { node, specifier } of imports(source)) {
|
|
71
|
+
const name = packageName(specifier);
|
|
72
|
+
if (name === config.framework || config.framework === "react" && name === "react-dom" || name.startsWith("@linaria/") || isBuiltin(specifier)) continue;
|
|
73
|
+
const targets = resolve(specifier, source.fileName);
|
|
74
|
+
for (const target of targets) if (runtime(target) && !target.split(path.sep).includes("node_modules")) local.add(target);
|
|
75
|
+
if (specifier.startsWith(".") || path.isAbsolute(specifier) || specifier === config.publicAlias || specifier.startsWith(config.publicAlias + "/")
|
|
76
|
+
|| targets.some(target => isInside(root, target) && !target.split(path.sep).includes("node_modules") && existsSync(target))) continue;
|
|
77
|
+
used.add(name);
|
|
78
|
+
if (!allowed.has(name)) report(source, node, "behavior-library-undeclared", `Runtime import ${specifier} requires ${name} in ds.config.json behaviorLibraries and package.json dependencies.`, name);
|
|
79
|
+
}
|
|
80
|
+
usage.set(source.fileName, used); edges.set(source.fileName, local);
|
|
81
|
+
}
|
|
82
|
+
function librariesFor(file, seen = new Set()) {
|
|
83
|
+
if (seen.has(file)) return [];
|
|
84
|
+
seen.add(file);
|
|
85
|
+
return [...new Set([...(usage.get(file) ?? []), ...[...(edges.get(file) ?? [])].flatMap(target => librariesFor(target, seen))])].sort();
|
|
86
|
+
}
|
|
87
|
+
for (const source of sources) for (const name of librariesFor(source.fileName)) {
|
|
88
|
+
const library = libraries.find(item => item.name === name), unit = owner(source.fileName);
|
|
89
|
+
if (library && unit && !library.units.includes(unit)) library.units.push(unit);
|
|
90
|
+
}
|
|
91
|
+
for (const library of libraries) library.units.sort();
|
|
92
|
+
return { libraries, diagnostics, librariesFor, undeclared: [...new Set(diagnostics.filter(item => item.rule === "behavior-library-undeclared").map(item => item.library))].sort() };
|
|
93
|
+
}
|
package/dist/behaviors.mjs
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import { existsSync, readFileSync, realpathSync, statSync } from "node:fs";
|
|
2
2
|
import path from "node:path";
|
|
3
|
-
import { isBuiltin } from "node:module";
|
|
4
3
|
import ts from "typescript";
|
|
5
4
|
import { z } from "zod";
|
|
6
5
|
import { isBehaviorFile, isDevelopmentFile, isInside, sourceFiles, isReviewFile, isTestFile } from "./config.mjs";
|
|
@@ -106,8 +105,6 @@ export function inspectBehaviors(options, suppliedProgram, suppliedRegistry) {
|
|
|
106
105
|
export function inspectControllers(options, program, report, contracts = []) {
|
|
107
106
|
const { root, dsRoot, config } = options;
|
|
108
107
|
const resolve = importResolver(options);
|
|
109
|
-
const pkg = existsSync(path.join(root, "package.json")) ? JSON.parse(readFileSync(path.join(root, "package.json"), "utf8")) : {};
|
|
110
|
-
const declared = new Set(Object.keys({ ...pkg.dependencies, ...pkg.devDependencies, ...pkg.peerDependencies, ...pkg.optionalDependencies }));
|
|
111
108
|
const privateFiles = new Map();
|
|
112
109
|
for (const contract of contracts) for (const subject of Object.values(contract.subjects).filter(item => item.source&&item.role!=="implementation")) {
|
|
113
110
|
const file = path.resolve(root, path.dirname(contract.file), subject.source);
|
|
@@ -148,9 +145,6 @@ export function inspectControllers(options, program, report, contracts = []) {
|
|
|
148
145
|
if (!node.importClause?.namedBindings || ts.isNamespaceImport(node.importClause.namedBindings)) emit(node, "controller-dependency", "Use explicit behavior imports in shared controllers so dependency ownership can be checked.");
|
|
149
146
|
}
|
|
150
147
|
}
|
|
151
|
-
} else if (!isBuiltin(specifier)) {
|
|
152
|
-
const name = specifier.startsWith("@") ? specifier.split("/").slice(0, 2).join("/") : specifier.split("/")[0];
|
|
153
|
-
if (!declared.has(name)) emit(node, "controller-dependency", `Undeclared controller dependency ${name}. Register it in the project package; ADS does not install dependencies or receive them from an MCP host.`);
|
|
154
148
|
}
|
|
155
149
|
}
|
|
156
150
|
}
|
package/dist/capture.mjs
CHANGED
|
@@ -5,7 +5,7 @@ import path from "node:path";
|
|
|
5
5
|
import { fileURLToPath } from "node:url";
|
|
6
6
|
import sharp from "sharp";
|
|
7
7
|
import { loadConfig } from "./config.mjs";
|
|
8
|
-
import {
|
|
8
|
+
import { discoverScenarioRegistry } from "./scenario-registry.mjs";
|
|
9
9
|
import { previewSourceRevision } from "./preview-inputs.mjs";
|
|
10
10
|
import { executeDevelopmentCommand } from "./verification.mjs";
|
|
11
11
|
import { captureKey, captureSpec, captureLimits, createCaptureStore } from "./capture-store.mjs";
|
|
@@ -47,7 +47,7 @@ export function createCaptureController(root) {
|
|
|
47
47
|
for (const name of ["@playwright/test", "playwright"]) { try { playwright = require.resolve(name); break; } catch { /* Try the other supported project-installed entry. */ } }
|
|
48
48
|
if (!playwright) throw new Error("Screenshots require project-local @playwright/test or playwright and its installed browser. ADS installs neither. Install/configure these in the connected project, then retry; mcp.capture selects browser/channel/timeoutMs.");
|
|
49
49
|
const projects = [root, ...(candidateRoot ? [path.resolve(candidateRoot)] : [])].map(directory => {
|
|
50
|
-
const options = loadConfig(directory), registry =
|
|
50
|
+
const options = loadConfig(directory), registry = discoverScenarioRegistry(options);
|
|
51
51
|
if (registry.diagnostics.length) throw new Error(`Scenario registration failed: ${registry.diagnostics[0].message}`);
|
|
52
52
|
const apps = selections.map((selection, selectionIndex) => {
|
|
53
53
|
const scenario = registry.scenarios.find(scenario => scenario.id === selection.scenario);
|
|
@@ -109,7 +109,7 @@ export function createCaptureController(root) {
|
|
|
109
109
|
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 }));
|
|
110
110
|
if (!publish) return { records, baseRevision: projects[0].revision };
|
|
111
111
|
store.commit(records);
|
|
112
|
-
return { ok: true, captures: store.list(
|
|
112
|
+
return { ok: true, captures: store.list(discoverScenarioRegistry(loadConfig(root)).scenarios, projects[0].revision).captures.filter(record => selections.some(selection => captureKey(selection) === record.key)) };
|
|
113
113
|
} finally {
|
|
114
114
|
try { await Promise.all(ownedHosts.map(host => host?.close())); }
|
|
115
115
|
finally { clearInterval(heartbeat); try { if (temporary) rmSync(temporary, { recursive: true, force: true }); } finally { active = undefined; progress = undefined; finish(); } }
|
package/dist/check.mjs
CHANGED
|
@@ -32,6 +32,7 @@ import { propertyRegistration } from "./property-registrations.mjs";
|
|
|
32
32
|
import { createLayerBoundaries, layerSourceFiles } from "./layers.mjs";
|
|
33
33
|
import { createDesignValues, inspectDesignAliases, isColorKeyword } from "./design-values.mjs";
|
|
34
34
|
import { inspectTestBoundaries } from "./test-boundaries.mjs";
|
|
35
|
+
import { inspectBehaviorLibraries } from "./behavior-libraries.mjs";
|
|
35
36
|
|
|
36
37
|
const scenarioLayoutGuidance = "Put demo-only sizing and framing in the development-only review/ layer, imported through the separate review entry. Patterns are production UI. Keep required behavior in the runtime owner; add component props for deliberate product API needs.";
|
|
37
38
|
const inlineStyleGuidance = `Own visual styles in component/pattern Linaria. ${scenarioLayoutGuidance} Reserve inlineStyleFiles for documented measured geometry, not demo layout.`;
|
|
@@ -63,6 +64,7 @@ export function checkProject(directory, { trackingRoot } = {}) {
|
|
|
63
64
|
const compiler = projectCompilerOptions(options);
|
|
64
65
|
const program = ts.createProgram(scriptFiles, { ...compiler, paths: { ...compiler.paths, [config.publicAlias]: [path.join(dsRoot, config.publicEntry)] }, allowJs: true, noResolve: true, noLib: true, types: [], target: ts.ScriptTarget.Latest, module: ts.ModuleKind.ESNext, jsx: ts.JsxEmit.Preserve });
|
|
65
66
|
const checker = program.getTypeChecker();
|
|
67
|
+
diagnostics.push(...inspectBehaviorLibraries(options, program).diagnostics);
|
|
66
68
|
const designValues = createDesignValues(program,options);
|
|
67
69
|
const paintContracts = inspectPaintContracts(options);
|
|
68
70
|
diagnostics.push(...paintContracts.diagnostics);
|
package/dist/config.mjs
CHANGED
|
@@ -8,6 +8,7 @@ export const supportedFrameworks = ["react", "preact"];
|
|
|
8
8
|
export const defaultConfig = {
|
|
9
9
|
schemaVersion: 1,
|
|
10
10
|
framework: null,
|
|
11
|
+
behaviorLibraries: [],
|
|
11
12
|
sourceDir: "src",
|
|
12
13
|
dsDir: "design-system",
|
|
13
14
|
publicAlias: "@ds",
|
|
@@ -59,6 +60,9 @@ export function loadConfig(directory = process.cwd()) {
|
|
|
59
60
|
}
|
|
60
61
|
if (config.schemaVersion !== 1) throw new Error(`Unsupported ADS config version: ${config.schemaVersion}`);
|
|
61
62
|
if (user.framework !== undefined && !supportedFrameworks.includes(user.framework)) throw new Error("framework must be react or preact.");
|
|
63
|
+
if (!Array.isArray(config.behaviorLibraries) || config.behaviorLibraries.length > 100
|
|
64
|
+
|| new Set(config.behaviorLibraries).size !== config.behaviorLibraries.length
|
|
65
|
+
|| config.behaviorLibraries.some(name => typeof name !== "string" || name.length > 214 || !/^(?:@[a-z0-9][a-z0-9._~-]*\/)?[a-z0-9][a-z0-9._~-]*$/.test(name))) throw new Error("behaviorLibraries must contain up to 100 unique npm package names, without versions, subpaths or wildcards.");
|
|
62
66
|
if (typeof config.publicAlias !== "string" || !config.publicAlias.trim()) throw new Error("publicAlias must be a non-empty string.");
|
|
63
67
|
if (!Array.isArray(config.inlineStyleFiles)) throw new Error("inlineStyleFiles must be an array of relative paths.");
|
|
64
68
|
const sourceRoot = projectPath(root, config.sourceDir, "sourceDir");
|
package/dist/lint-config.mjs
CHANGED
|
@@ -3,6 +3,7 @@ import path from "node:path";
|
|
|
3
3
|
import { fileURLToPath } from "node:url";
|
|
4
4
|
import { loadConfig } from "./config.mjs";
|
|
5
5
|
import { configurationFiles } from "./units.mjs";
|
|
6
|
+
import { inspectBehaviorLibraries } from "./behavior-libraries.mjs";
|
|
6
7
|
|
|
7
8
|
export function createLintConfig({ root, config }) {
|
|
8
9
|
const names = new Set(["ads"]);
|
|
@@ -33,6 +34,12 @@ export function createLintConfig({ root, config }) {
|
|
|
33
34
|
|
|
34
35
|
export function generateLintConfig(directory) {
|
|
35
36
|
const project = loadConfig(directory);
|
|
37
|
+
const libraries = inspectBehaviorLibraries(project);
|
|
38
|
+
if (libraries.diagnostics.length) {
|
|
39
|
+
const suggested = [...new Set([...project.config.behaviorLibraries, ...libraries.undeclared])].sort();
|
|
40
|
+
throw new Error(libraries.diagnostics.map(item => `${item.file}:${item.line}: ${item.rule}: ${item.message}`).join("\n")
|
|
41
|
+
+ (libraries.undeclared.length ? `\nDeclare approved packages with "behaviorLibraries": ${JSON.stringify(suggested)}. ADS does not add or install them automatically.` : ""));
|
|
42
|
+
}
|
|
36
43
|
const generated = createLintConfig(project);
|
|
37
44
|
const file = path.join(project.root, ".ds", "oxlintrc.json");
|
|
38
45
|
mkdirSync(path.dirname(file), { recursive: true });
|
|
@@ -197,7 +197,7 @@ export class PreviewBuildError extends Error {
|
|
|
197
197
|
export function summarizeBuild(build) {
|
|
198
198
|
function bounded(value) {
|
|
199
199
|
const diagnostics = value.diagnostics.slice(0, 3).map((entry) => ({ ...entry, message: entry.message.slice(0, 1000) }));
|
|
200
|
-
return { ...value, diagnostics, diagnosticCount: value.diagnostics.length,
|
|
200
|
+
return { ...value, building: value.state === "building" || value.state === "idle" && value.revision > 0, diagnostics, diagnosticCount: value.diagnostics.length,
|
|
201
201
|
diagnosticsTruncated: value.diagnostics.length > 3 || value.diagnostics.some((entry) => entry.message.length > 1000) };
|
|
202
202
|
}
|
|
203
203
|
return build.previews ? { ...build, ...(build.diagnostics ? bounded(build) : {}), previews: build.previews.map(bounded) } : { ...bounded(build), resourceUri: BUILD_URI };
|
package/dist/mcp/catalog.mjs
CHANGED
|
@@ -6,6 +6,7 @@ import { projectCompilerOptions } from "../boundaries.mjs";
|
|
|
6
6
|
import { publicApi } from "../public-api.mjs";
|
|
7
7
|
import { projectDocumentFiles } from "../project-documents.mjs";
|
|
8
8
|
import { inspectUnitContracts } from "../unit-contracts.mjs";
|
|
9
|
+
import { inspectBehaviorLibraries } from "../behavior-libraries.mjs";
|
|
9
10
|
|
|
10
11
|
export const PROJECT_URI = "ads://project";
|
|
11
12
|
export const sourceUri = (file) => `${PROJECT_URI}/files/${file.split("/").map(encodeURIComponent).join("/")}`;
|
|
@@ -29,12 +30,13 @@ export function projectDocuments(options) {
|
|
|
29
30
|
});
|
|
30
31
|
}
|
|
31
32
|
|
|
32
|
-
export function inspectCatalog(options, scenarios = []) {
|
|
33
|
+
export function inspectCatalog(options, scenarios = [], libraries) {
|
|
33
34
|
const { root, dsRoot, config } = options;
|
|
34
35
|
const entry = path.join(dsRoot, config.publicEntry);
|
|
35
36
|
if (!existsSync(entry)) return [];
|
|
36
37
|
const program = inspectUnitContracts(options).program ?? ts.createProgram([entry], { ...projectCompilerOptions(options), allowJs: true });
|
|
37
38
|
const checker = program.getTypeChecker();
|
|
39
|
+
libraries ??= inspectBehaviorLibraries(options, program);
|
|
38
40
|
const source = program.getSourceFile(entry);
|
|
39
41
|
const module = source && checker.getSymbolAtLocation(source);
|
|
40
42
|
if (!module) return [];
|
|
@@ -61,7 +63,7 @@ export function inspectCatalog(options, scenarios = []) {
|
|
|
61
63
|
const declarative=relationships[0];
|
|
62
64
|
const relationship=part=>({parent:part.parentName,roots:(part.rootNames??[part.parentName]).slice(0,8),rootCount:part.rootNames?.length??1,sourceUri:sourceUri(part.consumer.source),symbol:part.consumer.symbol,checks:part.checks.slice(0,8),checkCount:part.checks.length});
|
|
63
65
|
const bindings=Object.entries(contract?.bindings??{}).filter(([,binding])=>binding.apiName===exported.name);
|
|
64
|
-
items.push({ name: exported.name, kind, apiKind: declarative ? "declarative" : ui ? "ui" : "behavior", importFrom: config.publicAlias, file: relative, line, sourceUri: sourceUri(relative), guides,
|
|
66
|
+
items.push({ name: exported.name, kind, apiKind: declarative ? "declarative" : ui ? "ui" : "behavior", importFrom: config.publicAlias, file: relative, line, sourceUri: sourceUri(relative), guides, behaviorLibraries: libraries.librariesFor(file),
|
|
65
67
|
...(contract?{contractUri:sourceUri(contract.file),paintInputCount:contract.paintInputs?.filter(input=>input.apiName===exported.name).length??0,paintInputs:contract.paintInputs?.filter(input=>input.apiName===exported.name).slice(0,8).map(input=>({property:input.property,kind:input.kind,bindings:input.bindings??[]})),...(declarative?{consumer:relationship(declarative),consumerCount:relationships.length,consumers:relationships.slice(0,4).map(relationship),evidence:"registered relationships; source and browser verification are separate"}:{})}:{}),
|
|
66
68
|
...(bindings.length?{bindingCount:bindings.length,bindings:bindings.slice(0,4).map(([id,binding])=>({id,variable:binding.variable,scope:binding.scope.selector,producer:{sourceUri:sourceUri(binding.producer.source),symbol:binding.producer.symbol},checks:binding.checks.slice(0,8),checkCount:binding.checks.length})),bindingEvidence:"registered; verify source diagnostics and current browser checks"}:{}),
|
|
67
69
|
previews: scenarios.filter(item => item.covers.includes(exported.name) || item.exercises?.includes(exported.name)).map(item => item.id) });
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { loadConfig } from "../config.mjs";
|
|
2
|
+
import { readScenarioRegistry } from "../scenario-registry.mjs";
|
|
3
|
+
import { createScenarioInspector } from "../scenario-inspector.mjs";
|
|
4
|
+
|
|
5
|
+
/** Retain preview metadata while one worker discovers the latest revisions.
|
|
6
|
+
* This cache never supplies validation/acceptance evidence. */
|
|
7
|
+
export function createDraftDiscovery(root, { inspector = createScenarioInspector(root), onChange } = {}) {
|
|
8
|
+
const entries = new Map();
|
|
9
|
+
let closed = false;
|
|
10
|
+
function start(directory, entry) {
|
|
11
|
+
const revision = entry.requested;
|
|
12
|
+
entry.pending = Promise.resolve().then(() => inspector.inspect(directory)).then(registry => {
|
|
13
|
+
if (closed || entries.get(directory) !== entry || entry.requested !== revision) return;
|
|
14
|
+
entry.registry = registry; entry.revision = revision; entry.error = undefined;
|
|
15
|
+
onChange?.();
|
|
16
|
+
}).catch(error => {
|
|
17
|
+
if (closed || entries.get(directory) !== entry || entry.requested !== revision) return;
|
|
18
|
+
entry.error = { revision, message: error.message }; onChange?.();
|
|
19
|
+
}).finally(() => {
|
|
20
|
+
entry.pending = undefined;
|
|
21
|
+
if (!closed && entries.get(directory) === entry && entry.requested !== revision) start(directory, entry);
|
|
22
|
+
});
|
|
23
|
+
}
|
|
24
|
+
function refresh(directory, revision) {
|
|
25
|
+
if (closed) throw new Error("Draft discovery is closed.");
|
|
26
|
+
let entry = entries.get(directory);
|
|
27
|
+
if (!entry) { entry = {}; entries.set(directory, entry); }
|
|
28
|
+
entry.requested = revision;
|
|
29
|
+
if (entry.revision !== revision && !entry.pending && entry.error?.revision !== revision) {
|
|
30
|
+
// A compiler/other host may already have discovered this exact source.
|
|
31
|
+
// A miss queues worker analysis; never run TypeScript on the caller.
|
|
32
|
+
const cached = readScenarioRegistry(loadConfig(directory));
|
|
33
|
+
if (cached) { entry.registry = cached; entry.revision = revision; entry.error = undefined; }
|
|
34
|
+
else start(directory, entry);
|
|
35
|
+
}
|
|
36
|
+
return entry;
|
|
37
|
+
}
|
|
38
|
+
return {
|
|
39
|
+
refresh,
|
|
40
|
+
async current(directory, revision) {
|
|
41
|
+
const entry = refresh(directory, revision);
|
|
42
|
+
while (!closed && entry.requested === revision && entry.pending) await entry.pending;
|
|
43
|
+
if (closed || entries.get(directory) !== entry) throw new Error("Draft discovery was closed.");
|
|
44
|
+
if (entry.requested !== revision) throw new Error("Draft revision changed during discovery. Reopen the current draft.");
|
|
45
|
+
if (entry.error?.revision === revision) throw new Error(entry.error.message);
|
|
46
|
+
return entry.registry;
|
|
47
|
+
},
|
|
48
|
+
status(entry, usedRevision = entry.revision) {
|
|
49
|
+
return { state: usedRevision === entry.requested ? "current" : entry.error?.revision === entry.requested ? "error" : "pending",
|
|
50
|
+
revision: usedRevision ?? null, requestedRevision: entry.requested, ...(entry.error?.revision === entry.requested ? { message: entry.error.message } : {}) };
|
|
51
|
+
},
|
|
52
|
+
remove(directory) { entries.delete(directory); },
|
|
53
|
+
async close() { closed = true; entries.clear(); await inspector.close(); },
|
|
54
|
+
};
|
|
55
|
+
}
|
package/dist/mcp/drafts.mjs
CHANGED
|
@@ -1,16 +1,17 @@
|
|
|
1
1
|
import { createHash, randomUUID } from "node:crypto";
|
|
2
|
-
import { cpSync, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { cpSync, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, symlinkSync, watch, writeFileSync } from "node:fs";
|
|
3
3
|
import path from "node:path";
|
|
4
4
|
import { z } from "zod";
|
|
5
5
|
import { loadConfig, isInside } from "../config.mjs";
|
|
6
6
|
import { DRAFT_DIRECTORY } from "../draft-boundary.mjs";
|
|
7
7
|
import { inspectUnits, validateUnitId } from "../units.mjs";
|
|
8
|
-
import { inspectScenarios } from "../scenarios.mjs";
|
|
9
8
|
import { validationInputFiles } from "../validation-inputs.mjs";
|
|
10
9
|
import { textDiff } from "./text-diff.mjs";
|
|
11
10
|
import { storePreparedPatch, preparedFileDiff } from "./edit-preparation.mjs";
|
|
12
11
|
import { mergeDraftExports, isDraftExportEntry } from "./draft-exports.mjs";
|
|
13
12
|
import { inspectTokens } from "../tokens.mjs";
|
|
13
|
+
import { previewFileIgnored, previewWatchDirectories } from "../preview-files.mjs";
|
|
14
|
+
import { createDraftDiscovery } from "./draft-discovery.mjs";
|
|
14
15
|
|
|
15
16
|
export const DRAFTS_URI = "ads://project/drafts";
|
|
16
17
|
const hash = bytes => createHash("sha256").update(bytes).digest("hex");
|
|
@@ -50,10 +51,14 @@ function atomic(file, content) {
|
|
|
50
51
|
const storedName = target => `files/${target}.ads`;
|
|
51
52
|
|
|
52
53
|
/** Tracked proposal source is separate from disposable compiler state. No Git checkout is required. */
|
|
53
|
-
export function createDraftController(directory, { edits, startPreview } = {}) {
|
|
54
|
+
export function createDraftController(directory, { edits, startPreview, prewarm = false, onChange, scenarioInspector } = {}) {
|
|
54
55
|
const root = path.resolve(directory), storage = path.join(root, DRAFT_DIRECTORY);
|
|
55
56
|
const previews = new Map();
|
|
56
57
|
let active, closed = false;
|
|
58
|
+
let changeTimer, prewarmTimer, prewarming, pendingPrewarm;
|
|
59
|
+
const watchers = new Map();
|
|
60
|
+
let discoveryVersion = 0;
|
|
61
|
+
const discovery = createDraftDiscovery(root, { inspector: scenarioInspector, onChange: () => { ++discoveryVersion; onChange?.(); } });
|
|
57
62
|
const manifestFile = id => safe(root, `${DRAFT_DIRECTORY}/${idSchema.parse(id)}/proposal.ads.draft.json`);
|
|
58
63
|
const save = manifest => atomic(manifestFile(manifest.id), JSON.stringify(manifestSchema.parse(manifest), null, 2) + "\n");
|
|
59
64
|
function read(id) {
|
|
@@ -107,7 +112,27 @@ export function createDraftController(directory, { edits, startPreview } = {}) {
|
|
|
107
112
|
const last = events().filter(event => event.draft === manifest.id).at(-1);
|
|
108
113
|
return { id: manifest.id, title: manifest.title, units: manifest.units, dependencies: manifest.dependencies, tokenGroups:manifest.tokenGroups, revision, changes: changes.length, conflicts,
|
|
109
114
|
state: active?.id === manifest.id ? "checking" : value.dependencyErrors.length ? "dependency-error" : conflicts.length ? "conflict" : last?.state === "checking" ? "interrupted" : last?.state === "failed" && last.revision === revision ? "failed" : "draft",
|
|
110
|
-
manifest: path.relative(root, manifestFile(manifest.id)).replaceAll("\\", "/") };
|
|
115
|
+
preview: previewStatus(manifest.id, revision), manifest: path.relative(root, manifestFile(manifest.id)).replaceAll("\\", "/") };
|
|
116
|
+
}
|
|
117
|
+
const scopedBuild = id => `ads://drafts/${id}/resource?uri=${encodeURIComponent("ads://project/build")}`;
|
|
118
|
+
function previewStatus(id, revision) {
|
|
119
|
+
const session = previews.get(id), build = session?.build ?? { state: "unreported", building: false, current: false, stale: null, scenarios: [], resourceUri: scopedBuild(id) };
|
|
120
|
+
if (revision && session?.revision !== revision && build.scenarios.length) return { ...build, state: "queued", building: true, current: false, stale: true,
|
|
121
|
+
scenarios: build.scenarios.map(item => ({ ...item, state: "queued", building: true, current: false, stale: true })) };
|
|
122
|
+
return build;
|
|
123
|
+
}
|
|
124
|
+
function recordBuild(id, session, report) {
|
|
125
|
+
if (closed || previews.get(id) !== session) return;
|
|
126
|
+
const scenarios = report.previews.filter(item => item.revision > 0 || item.live || item.state === "error").map(item => ({ id: item.id, state: item.live ? "checking" : item.state,
|
|
127
|
+
building: ["idle", "building"].includes(item.state), current: item.current, stale: item.stale, revision: item.revision,
|
|
128
|
+
...(item.live ? { live: item.live } : {}), diagnosticCount: item.diagnostics.length }));
|
|
129
|
+
const building = scenarios.some(item => item.building);
|
|
130
|
+
const state = scenarios.some(item => item.state === "error") ? "error" : building ? scenarios.some(item => item.live) ? "checking" : "building" : scenarios.some(item => item.current) ? "ready" : report.state;
|
|
131
|
+
const build = { state, building, current: state === "ready", stale: state === "ready" ? false : scenarios.length ? true : null,
|
|
132
|
+
session: report.session, sequence: report.sequence, ...(report.progress ? { phase: report.progress.phase } : {}),
|
|
133
|
+
scenarios: scenarios.slice(0, 32), scenarioCount: scenarios.length, resourceUri: scopedBuild(id) };
|
|
134
|
+
if (JSON.stringify(build) === JSON.stringify(session.build)) return;
|
|
135
|
+
session.build = build; ++discoveryVersion; onChange?.();
|
|
111
136
|
}
|
|
112
137
|
function list({ id, unit, query = "", offset = 0, limit = 20 } = {}) {
|
|
113
138
|
const diagnostics = [], all = [];
|
|
@@ -154,6 +179,7 @@ export function createDraftController(directory, { edits, startPreview } = {}) {
|
|
|
154
179
|
for (const file of manifest.files) atomic(safe(path.dirname(manifestFile(id)), file.source), bytes(safe(root, file.target)));
|
|
155
180
|
save(manifest);
|
|
156
181
|
const value = inspect(id); event(id, value.revision, "created");
|
|
182
|
+
reconcileWatches(); queuePrewarm(id);
|
|
157
183
|
return { ...summary(value), directory: `${DRAFT_DIRECTORY}/${id}`, next: "Edit the marked source files, or register new/deleted files with ads_update_draft. Use ads_show_draft, review the rendered result, then ads_accept with its exact revision. Do not finish a design change with unaccepted drafts." };
|
|
158
184
|
}
|
|
159
185
|
function update({ id, revision, changes = [], dependencies }) {
|
|
@@ -174,6 +200,7 @@ export function createDraftController(directory, { edits, startPreview } = {}) {
|
|
|
174
200
|
}
|
|
175
201
|
}
|
|
176
202
|
save(manifest);
|
|
203
|
+
changed();
|
|
177
204
|
return summary(inspect(id));
|
|
178
205
|
}
|
|
179
206
|
function prepare(id) {
|
|
@@ -185,7 +212,7 @@ export function createDraftController(directory, { edits, startPreview } = {}) {
|
|
|
185
212
|
const workspace = path.join(root, ".ds/draft-previews", id, "project");
|
|
186
213
|
mkdirSync(workspace, { recursive: true });
|
|
187
214
|
if (realpathSync(workspace) !== workspace) throw new Error("Draft preview workspace cannot be a symlink.");
|
|
188
|
-
session = { workspace, inputs: new Map() }; previews.set(id, session);
|
|
215
|
+
session = { workspace, inputs: new Map() }; previews.set(id, session); reconcileWatches();
|
|
189
216
|
}
|
|
190
217
|
const inputs = validationInputFiles(loadConfig(root)), desired = new Map();
|
|
191
218
|
let size = 0;
|
|
@@ -221,7 +248,13 @@ export function createDraftController(directory, { edits, startPreview } = {}) {
|
|
|
221
248
|
cpSync(path.join(root,"dist"),path.join(session.workspace,"dist"),{recursive:true,filter(file){const stat=lstatSync(file);if(stat.isSymbolicLink())throw new Error("Generated runtime copies cannot contain symlinks.");if(stat.isFile()){count++;total+=stat.size;}if(count>100000||total>2*1024**3)throw new Error("Generated runtime exceeds the preview limit.");return true;}});
|
|
222
249
|
}
|
|
223
250
|
atomic(path.join(session.workspace, ".ds/draft-preview.json"), JSON.stringify({ previewOnly: true }));
|
|
251
|
+
if (session.revision && session.revision !== value.revision && session.runtime && session.build?.scenarios.length) {
|
|
252
|
+
const before = previewStatus(id);
|
|
253
|
+
session.build = { ...before, state: "queued", building: true, current: false, stale: true,
|
|
254
|
+
scenarios: before.scenarios.map(item => ({ ...item, state: "queued", building: true, current: false, stale: true })) };
|
|
255
|
+
}
|
|
224
256
|
session.revision = value.revision;
|
|
257
|
+
session.projectRevision = hash(JSON.stringify(inputs));
|
|
225
258
|
session.error=undefined;
|
|
226
259
|
const watched=new Set();
|
|
227
260
|
for(const target of Object.keys(inputs)){
|
|
@@ -235,19 +268,65 @@ export function createDraftController(directory, { edits, startPreview } = {}) {
|
|
|
235
268
|
if (closed) throw new Error("Draft controller is closed.");
|
|
236
269
|
if(!previews.has(id)&&[...previews.values()].filter(session=>session.starting).length>=4){const oldest=[...previews].find(([,session])=>session.starting);if(oldest)await retire(oldest[0]);}
|
|
237
270
|
const value = prepare(id), { session } = value;
|
|
238
|
-
|
|
239
|
-
const
|
|
271
|
+
session.opened = true;
|
|
272
|
+
const options = loadConfig(session.workspace), units = inspectUnits(options);
|
|
273
|
+
const metadata = discovery.refresh(session.workspace, value.revision);
|
|
274
|
+
let registry = metadata.registry;
|
|
275
|
+
const known = scenario ? registry?.scenarios.find(item => item.id === scenario)
|
|
276
|
+
: registry?.scenarios.find(item => value.manifest.units.includes(units.owner(units.relative(item.file))));
|
|
277
|
+
if (!registry || !known || !existsSync(path.join(session.workspace, known.file)) || registry.diagnostics.length) registry = await discovery.current(session.workspace, value.revision);
|
|
278
|
+
const metadataRevision = metadata.revision;
|
|
279
|
+
const scenarios = registry.scenarios.map(({ id, title, kind, group, file }) => ({ id, title, kind, ...(group ? { group } : {}), unit: units.owner(units.relative(file)) }));
|
|
280
|
+
const owned = scenarios.find(item => value.manifest.units.includes(item.unit))?.id;
|
|
240
281
|
if(!scenario&&!owned&&value.manifest.units.some(unit=>/^(?:components|patterns|composition)\//.test(unit)))throw new Error("Draft has no independently mountable owner scenario yet. Add its scenario/fixture or select an explicit existing context scenario.");
|
|
241
282
|
const selected = scenario ?? owned ?? registry.scenarios[0]?.id;
|
|
283
|
+
session.selected = selected;
|
|
242
284
|
if (scenario && !registry.scenarios.some(item => item.id === scenario)) throw new Error("Unknown draft scenario. Read ads_show_draft without scenario to discover it.");
|
|
243
|
-
|
|
244
|
-
|
|
285
|
+
await startSession(id, session);
|
|
286
|
+
if (metadata.revision === value.revision) session.runtime.primeRegistry?.(registry);
|
|
245
287
|
const url = new URL(session.runtime.url); if (selected) url.searchParams.set("scenario", selected);
|
|
246
|
-
const
|
|
288
|
+
const accepted = await discovery.current(root, session.projectRevision);
|
|
289
|
+
const acceptedExists = accepted.scenarios.some(item => item.id === selected);
|
|
247
290
|
const previewResult=selected&&session.runtime.callTool?await session.runtime.callTool("ads_show_scenario",{id:selected,waitFor:"compiled"}):undefined;
|
|
248
|
-
|
|
291
|
+
if (session.runtime.buildStatus) recordBuild(id, session, session.runtime.buildStatus());
|
|
292
|
+
return { ...summary(value), scenario: selected, scenarios, diagnostics: registry.diagnostics, discovery: discovery.status(metadata, metadataRevision), build: previewResult?.structuredContent?.build ?? previewStatus(id), showcaseUrl: url.href, acceptedExists, previewOnly: true, previewResult,draftScope:`ads://drafts/${id}/resource?uri=`, next: "Inspect the actual rendered draft and its build freshness. Catalogue metadata may refresh in the background. Subscribe to ads://project/build and ads://project/drafts for updates. Reopen after edits; accept only the revision you reviewed. Full acceptance checks have not run." };
|
|
293
|
+
}
|
|
294
|
+
async function startSession(id, session) {
|
|
295
|
+
session.starting ??= (async () => {
|
|
296
|
+
if ([...previews.values()].filter(item => item !== session && item.starting).length >= 4) {
|
|
297
|
+
const oldest = [...previews].find(([other, item]) => other !== id && item.starting);
|
|
298
|
+
if (oldest) await retire(oldest[0]);
|
|
299
|
+
}
|
|
300
|
+
if (closed || previews.get(id) !== session) throw new Error("Draft preview was closed before startup.");
|
|
301
|
+
const runtime = await startPreview(session.workspace);
|
|
302
|
+
if (closed || previews.get(id) !== session) { await runtime.close(); throw new Error("Draft preview startup was cancelled."); }
|
|
303
|
+
session.unsubscribeBuild = runtime.onBuildChange?.(report => recordBuild(id, session, report));
|
|
304
|
+
return session.runtime = runtime;
|
|
305
|
+
})().catch(error => { session.starting = undefined; throw error; });
|
|
306
|
+
return session.starting;
|
|
307
|
+
}
|
|
308
|
+
async function retire(id) { const session = previews.get(id); previews.delete(id); if (session) { discovery.remove(session.workspace); try { await session.starting; } catch { /* Failed prewarming remains retryable. */ } session.unsubscribeBuild?.(); await session.runtime?.close(); if (!previews.has(id)) rmSync(path.dirname(session.workspace), { recursive: true, force: true }); } }
|
|
309
|
+
function queuePrewarm(id) {
|
|
310
|
+
if (!prewarm || !startPreview || !loadConfig(root).config.mcp.previewWatch) return;
|
|
311
|
+
pendingPrewarm = id;
|
|
312
|
+
clearTimeout(prewarmTimer);
|
|
313
|
+
prewarmTimer = setTimeout(warmNext, 50); prewarmTimer.unref();
|
|
314
|
+
}
|
|
315
|
+
function warmNext() {
|
|
316
|
+
if (closed || prewarming || !pendingPrewarm) return;
|
|
317
|
+
const id = pendingPrewarm; pendingPrewarm = undefined;
|
|
318
|
+
prewarming = (async () => {
|
|
319
|
+
if (!existsSync(manifestFile(id))) return;
|
|
320
|
+
for (const [other, session] of previews) if (other !== id && session.prewarmed && !session.opened) await retire(other);
|
|
321
|
+
const { session } = prepare(id);
|
|
322
|
+
session.prewarmed = true;
|
|
323
|
+
await startSession(id, session);
|
|
324
|
+
await session.runtime.prewarm?.();
|
|
325
|
+
})().catch(() => { /* A malformed/incomplete draft can be edited and retried through show(). */ }).finally(() => {
|
|
326
|
+
prewarming = undefined;
|
|
327
|
+
if (!closed && pendingPrewarm) { prewarmTimer = setTimeout(warmNext, 0); prewarmTimer.unref(); }
|
|
328
|
+
});
|
|
249
329
|
}
|
|
250
|
-
async function retire(id) { const session = previews.get(id); previews.delete(id); if (session) { await session.starting; await session.runtime?.close(); rmSync(path.dirname(session.workspace), { recursive: true, force: true }); } }
|
|
251
330
|
async function drop({ id, revision }) {
|
|
252
331
|
if (active) throw new Error("Wait for acceptance before dropping a draft.");
|
|
253
332
|
const value = inspect(id);
|
|
@@ -313,15 +392,55 @@ export function createDraftController(directory, { edits, startPreview } = {}) {
|
|
|
313
392
|
walk(storage);if(existsSync(eventFile))rows.push(bytes(eventFile)?.toString());return hash(JSON.stringify(rows));
|
|
314
393
|
}
|
|
315
394
|
function watchStamp(session){return hash(JSON.stringify((session.watchFiles??[]).map(file=>{try{const stat=lstatSync(file);return[file,stat.mtimeMs,stat.ctimeMs,stat.ino,stat.size];}catch{return[file,null];}})));}
|
|
316
|
-
|
|
395
|
+
function syncPreviews() {
|
|
317
396
|
let tracked;try{tracked=draftStamp();}catch{return;}
|
|
318
397
|
for (const [id,session] of previews) {
|
|
319
398
|
if(session.observed===watchStamp(session)+tracked)continue;
|
|
320
399
|
try { prepare(id); } catch(error) { session.error=error.message; }
|
|
321
400
|
}
|
|
322
|
-
}
|
|
401
|
+
}
|
|
402
|
+
function changed() {
|
|
403
|
+
if (closed) return;
|
|
404
|
+
clearTimeout(changeTimer);
|
|
405
|
+
changeTimer = setTimeout(() => {
|
|
406
|
+
if (closed) return;
|
|
407
|
+
reconcileWatches(); syncPreviews(); onChange?.();
|
|
408
|
+
}, 16);
|
|
409
|
+
changeTimer.unref();
|
|
410
|
+
}
|
|
411
|
+
function reconcileWatches() {
|
|
412
|
+
if (closed) return;
|
|
413
|
+
const wanted = new Set([root]);
|
|
414
|
+
function draftDirectories(folder) {
|
|
415
|
+
if (!existsSync(folder) || realpathSync(folder) !== folder) return;
|
|
416
|
+
wanted.add(folder);
|
|
417
|
+
for (const entry of readdirSync(folder, { withFileTypes: true })) if (entry.isDirectory() && !entry.isSymbolicLink()) draftDirectories(path.join(folder, entry.name));
|
|
418
|
+
}
|
|
419
|
+
try {
|
|
420
|
+
draftDirectories(storage);
|
|
421
|
+
const options = loadConfig(root);
|
|
422
|
+
if (previews.size) for (const folder of previewWatchDirectories(options)) wanted.add(folder);
|
|
423
|
+
for (const folder of wanted) {
|
|
424
|
+
const stat = lstatSync(folder), identity = `${stat.dev}:${stat.ino}`;
|
|
425
|
+
if (watchers.get(folder)?.identity === identity) continue;
|
|
426
|
+
watchers.get(folder)?.watcher.close();
|
|
427
|
+
const watcher = watch(folder, (event, file) => {
|
|
428
|
+
if (!file) return;
|
|
429
|
+
const target = path.join(folder, String(file));
|
|
430
|
+
if (!isInside(storage, target) && previewFileIgnored(options, target)) return;
|
|
431
|
+
if (isInside(storage, target) || event === "rename" || /\.(?:[cm]?[jt]sx?|css|html|json|md|svg|png|jpe?g|webp|gif|woff2?|ttf|otf|lock|lockb)$/.test(target)) changed();
|
|
432
|
+
});
|
|
433
|
+
watcher.unref(); watcher.on("error", () => { watcher.close(); watchers.delete(folder); });
|
|
434
|
+
watchers.set(folder, { identity, watcher });
|
|
435
|
+
}
|
|
436
|
+
for (const [folder, item] of watchers) if (!wanted.has(folder) || !existsSync(folder)) { item.watcher.close(); watchers.delete(folder); }
|
|
437
|
+
} catch { /* Reconciliation retries removed/replaced directories. */ }
|
|
438
|
+
}
|
|
439
|
+
const timer = setInterval(() => { if (!closed) { reconcileWatches(); syncPreviews(); } }, 5000);
|
|
323
440
|
timer.unref();
|
|
441
|
+
reconcileWatches();
|
|
324
442
|
return { list, create, update, show, drop, accept, prepare, events, inspect, tokenGroups,
|
|
443
|
+
previewStatuses: () => [...previews].map(([id, session]) => ({ id, revision: session.revision, ...previewStatus(id) })),
|
|
325
444
|
readFile(file,{offset=0,limit=12000}={}){
|
|
326
445
|
const parts=file.split("/");
|
|
327
446
|
if(parts[0]!==DRAFT_DIRECTORY||parts.length<3)throw new Error("Use a tracked draft path from ads_drafts.");
|
|
@@ -335,7 +454,7 @@ export function createDraftController(directory, { edits, startPreview } = {}) {
|
|
|
335
454
|
return{path:file,draft:parts[1],unit:mapping?.unit??null,digest:`sha256:${hash(content)}`,bytes:content.length,binary,content:binary?null:text.slice(offset,end),offset,nextOffset:!binary&&end<text.length?end:null,totalChars:binary?null:text.length,startLine:text.slice(0,offset).split("\n").length};
|
|
336
455
|
},
|
|
337
456
|
async readResource(id,uri,signal){const session=previews.get(id);if(!session?.starting)throw new Error("Draft preview is not active. Reopen ads_show_draft.");if(session.error)throw new Error(`Draft preview is stale: ${session.error}`);await session.starting;return session.runtime.readResource(uri,signal);},
|
|
338
|
-
fingerprint:draftStamp
|
|
339
|
-
async close() { closed = true; clearInterval(timer); active?.abort.abort(); await Promise.allSettled([...previews.keys()].map(retire)); },
|
|
457
|
+
fingerprint:()=>`${draftStamp()}:${discoveryVersion}`,
|
|
458
|
+
async close() { closed = true; clearInterval(timer); clearTimeout(changeTimer); clearTimeout(prewarmTimer); pendingPrewarm = undefined; for (const { watcher } of watchers.values()) watcher.close(); watchers.clear(); active?.abort.abort(); await Promise.allSettled([discovery.close(), ...[...previews.keys()].map(retire)]); await prewarming; },
|
|
340
459
|
};
|
|
341
460
|
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { spawn } from "node:child_process";
|
|
2
2
|
import { randomUUID } from "node:crypto";
|
|
3
|
-
import { statSync, mkdirSync, writeFileSync, renameSync, rmSync, realpathSync } from "node:fs";
|
|
3
|
+
import { statSync, mkdirSync, readFileSync, writeFileSync, renameSync, rmSync, realpathSync } from "node:fs";
|
|
4
4
|
import path from "node:path";
|
|
5
5
|
import { fileURLToPath } from "node:url";
|
|
6
6
|
import { Writable } from "node:stream";
|
|
@@ -201,7 +201,17 @@ export function createPreviewWatch(root, config, { log = process.stderr, buildTi
|
|
|
201
201
|
})();
|
|
202
202
|
return stopping;
|
|
203
203
|
}
|
|
204
|
-
return { start, ensure,
|
|
204
|
+
return { start, ensure, async initialize() {
|
|
205
|
+
if (disposed || !command) return;
|
|
206
|
+
if (state === "failed" || restarting || stalled) await restart();
|
|
207
|
+
start();
|
|
208
|
+
const deadline = Date.now() + buildTimeout;
|
|
209
|
+
while (!disposed && state === "running" && Date.now() < deadline) {
|
|
210
|
+
try { if (JSON.parse(readFileSync(reportFile, "utf8")).session === session) return; } catch { /* Waiting for compiler initialization, without requesting a graph. */ }
|
|
211
|
+
await new Promise(resolve => setTimeout(resolve, 20));
|
|
212
|
+
}
|
|
213
|
+
if (!disposed) throw new Error(error ?? "Preview compiler initialization timed out.");
|
|
214
|
+
}, invalidate() { invalidation = randomUUID(); if (active) request(active,true); }, async warm(files) {
|
|
205
215
|
if (disposed || !command || !files.length) return;
|
|
206
216
|
const selected=active;
|
|
207
217
|
if (state === "failed" || restarting || stalled) await restart();
|
|
@@ -227,6 +237,7 @@ export function createReconfigurablePreviewWatch(root, config, options) {
|
|
|
227
237
|
let pending = Promise.resolve(), replacing = false, stopped = false;
|
|
228
238
|
return {
|
|
229
239
|
start() { if (!stopped && !replacing) current.start(); },
|
|
240
|
+
async initialize() { await pending; if (!stopped) return current.initialize(); },
|
|
230
241
|
async ensure(file, signal, options) { await pending; if (stopped) throw new Error("Preview watcher is stopped."); return current.ensure(file, signal, options); },
|
|
231
242
|
status() { return replacing ? { state: "reconfiguring" } : current.status(); },
|
|
232
243
|
resourceSession() { return current.resourceSession(); },
|