@reqvire-org/ads 0.4.3 → 0.4.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +12 -9
- package/dist/bun-compiler.mjs +6 -5
- package/dist/check.mjs +3 -43
- package/dist/cli.mjs +1 -1
- package/dist/contrast-composition.mjs +6 -60
- package/dist/contrast-styles.mjs +88 -0
- package/dist/mcp/apps.mjs +7 -1
- package/dist/mcp/build-status.mjs +8 -3
- package/dist/mcp/drafts.mjs +13 -1
- package/dist/mcp/preview-http.bundle.js +7 -0
- package/dist/mcp/preview-http.mjs +148 -0
- package/dist/mcp/preview-widget.bundle.js +47 -47
- package/dist/mcp/resource-loader.js +1 -201
- package/dist/mcp/sandbox-host.mjs +6 -1
- package/dist/mcp/server.mjs +35 -4
- package/dist/mcp/showcase-host.mjs +55 -5
- package/dist/mcp/showcase-http.mjs +66 -0
- package/dist/preview-bun.mjs +75 -60
- package/dist/preview-incremental.mjs +358 -0
- package/dist/preview-manifest-update.mjs +70 -0
- package/dist/preview-resources.mjs +33 -1
- package/dist/render-composition.mjs +27 -5
- package/dist/scenarios-compiler.mjs +19 -1
- package/dist/showcase/client.bundle.js +54 -54
- package/dist/showcase/comparison.js +15 -12
- package/dist/showcase/connection.js +10 -0
- package/dist/showcase/http-client.bundle.js +9 -0
- package/dist/showcase/http-connection.js +86 -0
- package/dist/showcase/http-preview.js +81 -0
- package/dist/showcase-http-routes.mjs +31 -0
- package/dist/skills/README.md +3 -3
- package/dist/skills/ads-designer/SKILL.md +5 -1
- package/dist/skills/ads-designer/references/accessibility.md +6 -2
- package/dist/skills/ads-designer/references/captures.md +1 -1
- package/dist/skills/ads-designer/references/runtimes.md +31 -0
- package/dist/skills/ads-designer/references/workflows.md +16 -0
- package/dist/skills/ads-import/references/captures.md +1 -1
- package/dist/skills/ads-import/references/runtimes.md +31 -0
- package/dist/skills/ads-import/references/workflows.md +16 -0
- package/dist/skills/ads-migrate/SKILL.md +3 -1
- package/dist/skills/ads-migrate/references/0.4.1-to-0.4.2.md +2 -3
- package/dist/skills/ads-migrate/references/0.4.3-to-0.4.4.md +89 -0
- package/dist/skills/ads-migrate/references/0.4.4-to-0.4.5.md +72 -0
- package/dist/skills/ads-port/references/captures.md +1 -1
- package/dist/skills/ads-port/references/runtimes.md +31 -0
- package/dist/skills/ads-port/references/workflows.md +16 -0
- package/dist/style-token-rules.mjs +51 -0
- package/dist/verification/browser.mjs +2 -2
- package/docs/ADS.md +9 -7
- package/docs/ARCHITECTURE.md +109 -48
- package/docs/CACHING.md +40 -1
- package/docs/CHANGELOG.md +100 -22
- package/docs/GUIDE.md +37 -10
- package/docs/HTTP-SHOWCASE-POC.md +397 -0
- package/docs/MCP.md +104 -25
- package/docs/benchmarks/README.md +1 -1
- package/docs/benchmarks/http-showcase-optimized.json +1879 -0
- package/docs/benchmarks/http-showcase-profile.json +308 -0
- package/docs/benchmarks/http-showcase.json +3069 -0
- package/package.json +6 -4
package/dist/preview-bun.mjs
CHANGED
|
@@ -62,7 +62,7 @@ function buildFailure(logs) {
|
|
|
62
62
|
// Linaria's class merger is pure, but its published implementation does not
|
|
63
63
|
// annotate calls. Mark only direct module-level calls to that imported binding;
|
|
64
64
|
// a project function named cx (or a shadowed parameter) gets no exemption.
|
|
65
|
-
async function pureClassComposition(code, file) {
|
|
65
|
+
export async function pureClassComposition(code, file) {
|
|
66
66
|
const tree = await ts.createSourceFile(file, code, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX),
|
|
67
67
|
names = new Set(),
|
|
68
68
|
offsets = [];
|
|
@@ -85,7 +85,7 @@ async function pureClassComposition(code, file) {
|
|
|
85
85
|
|
|
86
86
|
// Preview-only identity survives atom sharing: identical generated classes can
|
|
87
87
|
// belong to different owners. Production builds never receive these markers.
|
|
88
|
-
async function previewIdentities(code, file, options) {
|
|
88
|
+
export async function previewIdentities(code, file, options) {
|
|
89
89
|
const relative = slash(path.relative(options.dsRoot, file));
|
|
90
90
|
if (!/^(?:components|patterns|review)\//.test(relative)) return code;
|
|
91
91
|
const source = slash(path.relative(options.root, file));
|
|
@@ -101,14 +101,80 @@ async function previewIdentities(code, file, options) {
|
|
|
101
101
|
return code;
|
|
102
102
|
}
|
|
103
103
|
|
|
104
|
+
/** Shared source extraction for full Bun builds and watched incremental graphs.
|
|
105
|
+
* One result per file; input/dependency bytes and spatial membership govern reuse.
|
|
106
|
+
* Callers supply their input adapter and own publication/revision fencing. */
|
|
107
|
+
export function createPreviewTransforms() {
|
|
108
|
+
const cache = new TransformCacheCollection(), transformed = new Map();
|
|
109
|
+
return {
|
|
110
|
+
values: transformed,
|
|
111
|
+
async transform(file, original, { options, resolve, sourceRevision, readSpatial }) {
|
|
112
|
+
const previous = transformed.get(file);
|
|
113
|
+
let value = previous;
|
|
114
|
+
const spatialChanged = previous?.spatialRevision !== undefined && previous.spatialRevision !== (readSpatial()?.revision ?? null);
|
|
115
|
+
if (!value || value.source !== hash(original) || spatialChanged || value.dependencies.some(([dependency, digest]) => fileHash(dependency) !== digest)) {
|
|
116
|
+
// Membership changes (a new token sheet) are not in the previous file
|
|
117
|
+
// dependency list. Invalidate this extraction, even with identical TS.
|
|
118
|
+
if (spatialChanged) cache.invalidateForFile(file);
|
|
119
|
+
if (previous) for (const [dependency, digest, imported] of previous.dependencies) if (fileHash(dependency) !== digest) {
|
|
120
|
+
cache.invalidateForFile(dependency);
|
|
121
|
+
if (imported) cache.invalidateForFile(imported);
|
|
122
|
+
if (existsSync(dependency)) cache.invalidateIfChanged(dependency, readFileSync(dependency, "utf8"));
|
|
123
|
+
}
|
|
124
|
+
cache.invalidateIfChanged(file, original);
|
|
125
|
+
let usedSpatial = false;
|
|
126
|
+
const result = await timing.timeStage("linaria-transform", () => spatialInputs.withSpatialInputs(() => {
|
|
127
|
+
usedSpatial = true;
|
|
128
|
+
return readSpatial();
|
|
129
|
+
}, () => transform(
|
|
130
|
+
{ cache, asyncResolveKey: sourceRevision, options: { filename: file, root: options.root, pluginOptions: { configFile: false, tagResolver: linariaTagResolver } } },
|
|
131
|
+
original,
|
|
132
|
+
async (specifier, importer) => resolve(specifier, importer),
|
|
133
|
+
)));
|
|
134
|
+
const classes = new Set(
|
|
135
|
+
Object.values(result.rules ?? {})
|
|
136
|
+
.map((rule) => rule.className)
|
|
137
|
+
.filter(Boolean),
|
|
138
|
+
);
|
|
139
|
+
if (result.cssText)
|
|
140
|
+
postcss.parse(result.cssText).walkRules((rule) => {
|
|
141
|
+
if (!keyframeRule(rule)) for (const name of selectorClasses(rule.selector)) classes.add(name);
|
|
142
|
+
});
|
|
143
|
+
// A computed interpolation can introduce a layout without @ads- in
|
|
144
|
+
// this source. Record the processor's actual use, not a source regex.
|
|
145
|
+
const spatial = usedSpatial || previous?.spatialRevision !== undefined ? readSpatial() : undefined;
|
|
146
|
+
value = {
|
|
147
|
+
source: hash(original),
|
|
148
|
+
code: await pureClassComposition(result.code, file),
|
|
149
|
+
css: result.cssText,
|
|
150
|
+
classes: [...classes],
|
|
151
|
+
...(spatial !== undefined ? { spatialRevision: spatial?.revision ?? null } : {}),
|
|
152
|
+
// The shared spatial revision already checks every sheet once per
|
|
153
|
+
// build. Keep watcher membership without rehashing them per owner.
|
|
154
|
+
spatialInputs: spatial?.inputs ?? [],
|
|
155
|
+
dependencies: [...new Set([file, ...(result.dependencies ?? [])])].map((dependency) => {
|
|
156
|
+
const imported = path.isAbsolute(dependency) ? dependency : path.resolve(path.dirname(file), dependency);
|
|
157
|
+
const absolute = existsSync(imported) ? imported : resolve(dependency, file);
|
|
158
|
+
return [absolute, fileHash(absolute), imported];
|
|
159
|
+
}),
|
|
160
|
+
};
|
|
161
|
+
transformed.set(file, value);
|
|
162
|
+
}
|
|
163
|
+
return value;
|
|
164
|
+
},
|
|
165
|
+
reset() { transformed.clear(); disposeEvalBroker(cache); cache.clear("all"); },
|
|
166
|
+
async close() { transformed.clear(); cache.clear("all"); await disposeEvalBroker(cache); },
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
|
|
104
170
|
/** ADS owns compilation; consuming applications keep their own build pipeline.
|
|
105
171
|
* Only the current transform for each source file is retained between builds.
|
|
106
172
|
* Publication, source fencing and verification remain the shared scheduler's job. */
|
|
107
173
|
export function createBunPreviewBuilder() {
|
|
108
174
|
assertBunRuntime();
|
|
109
175
|
process.env.WYW_NODE_BINARY = process.execPath;
|
|
110
|
-
const
|
|
111
|
-
transformed =
|
|
176
|
+
const transforms = createPreviewTransforms(),
|
|
177
|
+
transformed = transforms.values,
|
|
112
178
|
workerResults = new Map();
|
|
113
179
|
let directory,
|
|
114
180
|
context,
|
|
@@ -120,10 +186,8 @@ export function createBunPreviewBuilder() {
|
|
|
120
186
|
if (closed) throw new Error("Preview compiler is closed.");
|
|
121
187
|
const signature = JSON.stringify([options.root, options.config, watched]);
|
|
122
188
|
if (context !== signature) {
|
|
123
|
-
|
|
189
|
+
transforms.reset();
|
|
124
190
|
workerResults.clear();
|
|
125
|
-
disposeEvalBroker(cache);
|
|
126
|
-
cache.clear("all");
|
|
127
191
|
previous = undefined;
|
|
128
192
|
context = signature;
|
|
129
193
|
}
|
|
@@ -219,57 +283,7 @@ export function createBunPreviewBuilder() {
|
|
|
219
283
|
inputs.add(file);
|
|
220
284
|
let code = original;
|
|
221
285
|
if (!file.includes(`${path.sep}node_modules${path.sep}`) && /@linaria\//.test(original)) {
|
|
222
|
-
const
|
|
223
|
-
let value = previous;
|
|
224
|
-
const spatialChanged = previous?.spatialRevision !== undefined && previous.spatialRevision !== (readSpatial()?.revision ?? null);
|
|
225
|
-
if (!value || value.source !== hash(original) || spatialChanged || value.dependencies.some(([dependency, digest]) => fileHash(dependency) !== digest)) {
|
|
226
|
-
// Membership changes (a new token sheet) are not in the previous file
|
|
227
|
-
// dependency list. Invalidate this extraction, even with identical TS.
|
|
228
|
-
if (spatialChanged) cache.invalidateForFile(file);
|
|
229
|
-
if (previous) for (const [dependency, digest, imported] of previous.dependencies) if (fileHash(dependency) !== digest) {
|
|
230
|
-
cache.invalidateForFile(dependency);
|
|
231
|
-
if (imported) cache.invalidateForFile(imported);
|
|
232
|
-
if (existsSync(dependency)) cache.invalidateIfChanged(dependency, readFileSync(dependency, "utf8"));
|
|
233
|
-
}
|
|
234
|
-
cache.invalidateIfChanged(file, original);
|
|
235
|
-
let usedSpatial = false;
|
|
236
|
-
const result = await timing.timeStage("linaria-transform", () => spatialInputs.withSpatialInputs(() => {
|
|
237
|
-
usedSpatial = true;
|
|
238
|
-
return readSpatial();
|
|
239
|
-
}, () => transform(
|
|
240
|
-
{ cache, asyncResolveKey: sourceRevision, options: { filename: file, root: options.root, pluginOptions: { configFile: false, tagResolver: linariaTagResolver } } },
|
|
241
|
-
original,
|
|
242
|
-
async (specifier, importer) => resolve(specifier, importer),
|
|
243
|
-
)));
|
|
244
|
-
const classes = new Set(
|
|
245
|
-
Object.values(result.rules ?? {})
|
|
246
|
-
.map((rule) => rule.className)
|
|
247
|
-
.filter(Boolean),
|
|
248
|
-
);
|
|
249
|
-
if (result.cssText)
|
|
250
|
-
postcss.parse(result.cssText).walkRules((rule) => {
|
|
251
|
-
if (!keyframeRule(rule)) for (const name of selectorClasses(rule.selector)) classes.add(name);
|
|
252
|
-
});
|
|
253
|
-
// A computed interpolation can introduce a layout without @ads- in
|
|
254
|
-
// this source. Record the processor's actual use, not a source regex.
|
|
255
|
-
const spatial = usedSpatial || previous?.spatialRevision !== undefined ? readSpatial() : undefined;
|
|
256
|
-
value = {
|
|
257
|
-
source: hash(original),
|
|
258
|
-
code: await pureClassComposition(result.code, file),
|
|
259
|
-
css: result.cssText,
|
|
260
|
-
classes: [...classes],
|
|
261
|
-
...(spatial !== undefined ? { spatialRevision: spatial?.revision ?? null } : {}),
|
|
262
|
-
// The shared spatial revision already checks every sheet once per
|
|
263
|
-
// build. Keep watcher membership without rehashing them per owner.
|
|
264
|
-
spatialInputs: spatial?.inputs ?? [],
|
|
265
|
-
dependencies: [...new Set([file, ...(result.dependencies ?? [])])].map((dependency) => {
|
|
266
|
-
const imported = path.isAbsolute(dependency) ? dependency : path.resolve(path.dirname(file), dependency);
|
|
267
|
-
const absolute = existsSync(imported) ? imported : resolve(dependency, file);
|
|
268
|
-
return [absolute, fileHash(absolute), imported];
|
|
269
|
-
}),
|
|
270
|
-
};
|
|
271
|
-
transformed.set(file, value);
|
|
272
|
-
}
|
|
286
|
+
const value = await transforms.transform(file, original, { options, resolve, sourceRevision, readSpatial });
|
|
273
287
|
code = value.code;
|
|
274
288
|
for (const [dependency] of value.dependencies) inputs.add(dependency);
|
|
275
289
|
for (const dependency of value.spatialInputs) inputs.add(dependency);
|
|
@@ -567,12 +581,13 @@ export function createBunPreviewBuilder() {
|
|
|
567
581
|
previous = undefined;
|
|
568
582
|
transformed.clear();
|
|
569
583
|
workerResults.clear();
|
|
570
|
-
|
|
571
|
-
await disposeEvalBroker(cache);
|
|
584
|
+
await transforms.close();
|
|
572
585
|
if (directory) rmSync(directory, { recursive: true, force: true });
|
|
573
586
|
};
|
|
574
587
|
const measured = (...args) => timing.timeStage("preview-build", () => builder(...args));
|
|
575
588
|
measured.warmBatch = builder.warmBatch;
|
|
576
589
|
measured.close = builder.close;
|
|
590
|
+
// Benchmark inspection: before preview-only provenance and import pruning.
|
|
591
|
+
measured.transformedModules = () => new Map(transformed);
|
|
577
592
|
return measured;
|
|
578
593
|
}
|
|
@@ -0,0 +1,358 @@
|
|
|
1
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
2
|
+
import { createServer as createHttpServer } from "node:http";
|
|
3
|
+
import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { fileURLToPath } from "node:url";
|
|
6
|
+
import { createServer } from "vite";
|
|
7
|
+
import react from "@vitejs/plugin-react";
|
|
8
|
+
import prefresh from "@prefresh/vite";
|
|
9
|
+
import { init, parse } from "es-module-lexer";
|
|
10
|
+
import valueParser from "postcss-value-parser";
|
|
11
|
+
import { createBunPreviewBuilder, createPreviewTransforms, previewFrameFiles, previewIdentities } from "./preview-bun.mjs";
|
|
12
|
+
import { createPreviewImportOptimizer } from "./preview-imports.mjs";
|
|
13
|
+
import { createPreviewResources } from "./preview-resources.mjs";
|
|
14
|
+
import { spatialMetadata } from "./spatial-metadata.mjs";
|
|
15
|
+
import spatialInputs from "./linaria/spatial-inputs.cjs";
|
|
16
|
+
|
|
17
|
+
const hash = value => createHash("sha256").update(value).digest("hex");
|
|
18
|
+
const slash = value => value.replaceAll("\\", "/");
|
|
19
|
+
const fingerprint = file => { try { return hash(readFileSync(file)); } catch { return null; } };
|
|
20
|
+
const cleanUrl = value => value.replace(/([?&])(?:t|v)=[^&]+&?/g, "$1").replace(/[?&]$/, "");
|
|
21
|
+
const clientId = "/@vite/client";
|
|
22
|
+
const bootstrapId = "/@ads/refresh-bootstrap";
|
|
23
|
+
const clientCode = `export const createHotContext=id=>globalThis.__adsPreviewHot.context(id);
|
|
24
|
+
export function injectQuery(url,query){if(!url.startsWith('.')&&!url.startsWith('/'))return url;const parsed=new URL(url,'http://ads');return url.split(/[?#]/)[0]+'?'+query+(parsed.search?'&'+parsed.search.slice(1):'')+parsed.hash;}`;
|
|
25
|
+
|
|
26
|
+
/** A development module graph, never a public dev server. The shared compiler
|
|
27
|
+
* scheduler fences and publishes its immutable output through MCP resources.
|
|
28
|
+
* Complete verification builds retain the existing Bun compiler. */
|
|
29
|
+
export function createIncrementalPreviewBuilder() {
|
|
30
|
+
const complete = createBunPreviewBuilder();
|
|
31
|
+
let state, closed = false, running = Promise.resolve();
|
|
32
|
+
async function build(entries, options, track, context = {}) {
|
|
33
|
+
if (closed) throw new Error("Preview compiler is closed.");
|
|
34
|
+
if (!context.watched) return complete(entries, options, track, context);
|
|
35
|
+
const configuration = JSON.stringify([options.root, options.config,
|
|
36
|
+
...["package.json", "package-lock.json", "bun.lock", "bun.lockb", "tsconfig.json"].map(file => fingerprint(path.join(options.root, file)))]);
|
|
37
|
+
if (state?.configuration !== configuration || state?.exhausted || state?.dependenciesChanged || state?.membershipChanged) {
|
|
38
|
+
await state?.close();
|
|
39
|
+
state = await createGraph(options, configuration);
|
|
40
|
+
}
|
|
41
|
+
return state.build(entries, track, context.sourceRevision);
|
|
42
|
+
}
|
|
43
|
+
// The scheduler is serial, but own the lifetime here too: disposal must not
|
|
44
|
+
// close native extraction or the module graph underneath an in-flight build.
|
|
45
|
+
const builder = (...args) => {
|
|
46
|
+
const task = running.then(() => build(...args));
|
|
47
|
+
running = task.catch(() => {});
|
|
48
|
+
return task;
|
|
49
|
+
};
|
|
50
|
+
builder.close = async () => { closed = true; await running; await state?.close(); await complete.close(); };
|
|
51
|
+
builder.transformedModules = () => new Map(state?.transforms.values);
|
|
52
|
+
builder.stats = () => state?.stats;
|
|
53
|
+
// Preserve the scheduler's existing background batching. Publishing each
|
|
54
|
+
// unvisited root separately can keep the selected view pending for the whole
|
|
55
|
+
// warm-up catalogue, despite its own build and checks already completing.
|
|
56
|
+
builder.warmBatch = true;
|
|
57
|
+
return builder;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
async function createGraph(options, configuration) {
|
|
61
|
+
await init;
|
|
62
|
+
process.env.WYW_NODE_BINARY = process.execPath;
|
|
63
|
+
const directory = path.join(options.root, ".ds/incremental", randomUUID());
|
|
64
|
+
mkdirSync(directory, { recursive: true });
|
|
65
|
+
const transforms = createPreviewTransforms(), sheets = new Map(), inputs = new Set(), digests = new Map();
|
|
66
|
+
const lowered = new Map(), generated = new Map(), workerCache = new Map(), preparedCache = new Map();
|
|
67
|
+
const optimizedInputs = new Set();
|
|
68
|
+
const workerBuilder = createBunPreviewBuilder();
|
|
69
|
+
const epoch = randomUUID(), socketHost = createHttpServer();
|
|
70
|
+
const refreshInclude = new RegExp("^" + slash(options.dsRoot).replace(/[.*+?^${}()|[\]\\]/g, "\\$&") + "/");
|
|
71
|
+
let revision, spatial, optimizer, server, membership, active = Promise.resolve(), stats;
|
|
72
|
+
const frame = path.dirname(previewFrameFiles[0]);
|
|
73
|
+
const alias = specifier => specifier === options.config.publicAlias ? path.join(options.dsRoot, options.config.publicEntry)
|
|
74
|
+
: specifier === options.config.publicAlias + "/review" ? path.join(options.dsRoot, options.config.reviewEntry)
|
|
75
|
+
: specifier === "@reqvire-org/ads/preview" ? previewFrameFiles[0] : specifier;
|
|
76
|
+
const resolve = (specifier, importer) => Bun.resolveSync(alias(specifier), path.dirname(importer));
|
|
77
|
+
const readSpatial = () => spatial ??= spatialInputs.captureSpatial(options);
|
|
78
|
+
function inputMembership() {
|
|
79
|
+
const directories = new Map();
|
|
80
|
+
function inspect(directory, recursive = false) {
|
|
81
|
+
if (directories.has(directory)) return;
|
|
82
|
+
let entries;
|
|
83
|
+
try { entries = readdirSync(directory, { withFileTypes: true }); }
|
|
84
|
+
catch (error) { if (error.code !== "ENOENT") throw error; directories.set(directory, null); return; }
|
|
85
|
+
directories.set(directory, entries.map(entry => [entry.name, entry.isDirectory(), entry.isSymbolicLink()]).sort());
|
|
86
|
+
if (recursive) for (const entry of entries) if (entry.isDirectory()) inspect(path.join(directory, entry.name), true);
|
|
87
|
+
}
|
|
88
|
+
// A newly added sibling can outrank a previously resolved import without
|
|
89
|
+
// changing any recorded file bytes. Observe membership, not only contents.
|
|
90
|
+
inspect(options.dsRoot, true);
|
|
91
|
+
for (const file of inputs) {
|
|
92
|
+
if (file.startsWith(options.dsRoot + path.sep) || file.startsWith(directory + path.sep)) continue;
|
|
93
|
+
let parent = path.dirname(file);
|
|
94
|
+
inspect(parent);
|
|
95
|
+
while (parent.startsWith(options.root + path.sep)) { parent = path.dirname(parent); inspect(parent); }
|
|
96
|
+
}
|
|
97
|
+
return hash(JSON.stringify([...directories].sort()));
|
|
98
|
+
}
|
|
99
|
+
const sourceUrl = file => file.startsWith(options.root + path.sep) ? "/" + slash(path.relative(options.root, file)) : "/@fs" + slash(file);
|
|
100
|
+
function sourceFile(url) {
|
|
101
|
+
const pathname = decodeURI(url.split("?")[0]);
|
|
102
|
+
return pathname.startsWith("/@fs/") ? pathname.slice(4) : path.join(options.root, pathname);
|
|
103
|
+
}
|
|
104
|
+
async function lower(code, file) {
|
|
105
|
+
inputs.add(file);
|
|
106
|
+
const previous = lowered.get(file);
|
|
107
|
+
if (previous && previous.revision === revision && previous.source === code) return previous.code;
|
|
108
|
+
const original = code;
|
|
109
|
+
let value;
|
|
110
|
+
if (/@linaria\//.test(code)) {
|
|
111
|
+
const before = transforms.values.get(file);
|
|
112
|
+
value = await transforms.transform(file, code, { options, resolve, sourceRevision: revision, readSpatial });
|
|
113
|
+
if (before !== value) stats.extracted.push(file);
|
|
114
|
+
code = value.code;
|
|
115
|
+
for (const [dependency] of value.dependencies) inputs.add(dependency);
|
|
116
|
+
for (const dependency of value.spatialInputs) inputs.add(dependency);
|
|
117
|
+
sheets.set(file + ".ads-incremental.css", value.css ?? "");
|
|
118
|
+
}
|
|
119
|
+
optimizer ??= createPreviewImportOptimizer(options, resolve, inputs);
|
|
120
|
+
code = await (await optimizer)(code, file);
|
|
121
|
+
code = await previewIdentities(code, file, options);
|
|
122
|
+
if (value?.css) code += `\nimport ${JSON.stringify(file + ".ads-incremental.css")};\n`;
|
|
123
|
+
lowered.set(file, { revision, source: original, code });
|
|
124
|
+
stats.transformed.push(file);
|
|
125
|
+
return code;
|
|
126
|
+
}
|
|
127
|
+
const plugin = {
|
|
128
|
+
name: "ads-preview-source", enforce: "pre",
|
|
129
|
+
resolveId(id) { if (sheets.has(id) || id === bootstrapId) return id; },
|
|
130
|
+
load(id) {
|
|
131
|
+
if (sheets.has(id)) return sheets.get(id);
|
|
132
|
+
if (id === bootstrapId) return options.config.framework === "react"
|
|
133
|
+
? 'import {injectIntoGlobalHook} from "/@react-refresh";injectIntoGlobalHook(globalThis);globalThis.$RefreshReg$=()=>{};globalThis.$RefreshSig$=()=>type=>type;'
|
|
134
|
+
: "export {};";
|
|
135
|
+
},
|
|
136
|
+
async transform(code, id) {
|
|
137
|
+
if (!id.startsWith(options.dsRoot + path.sep) || !/\.[cm]?[jt]sx?$/.test(id)) return;
|
|
138
|
+
const task = active.then(() => lower(code, id));
|
|
139
|
+
active = task.catch(() => {});
|
|
140
|
+
return { code: await task, map: null };
|
|
141
|
+
},
|
|
142
|
+
};
|
|
143
|
+
try {
|
|
144
|
+
server = await createServer({
|
|
145
|
+
configFile: false, envFile: false, root: options.root, publicDir: false,
|
|
146
|
+
cacheDir: path.join(directory, "deps"), logLevel: "silent",
|
|
147
|
+
// Preserve original artwork bytes and the resource bridge's fetch policy.
|
|
148
|
+
// Vite otherwise minifies small SVGs into data URLs during development.
|
|
149
|
+
build: { assetsInlineLimit: 0 },
|
|
150
|
+
plugins: [plugin, ...(options.config.framework === "react" ? [react({ include: refreshInclude })] : [prefresh({ include: refreshInclude })])],
|
|
151
|
+
esbuild: { jsx: "automatic", jsxImportSource: options.config.framework },
|
|
152
|
+
resolve: { dedupe: ["react", "react-dom", "preact"], alias: [
|
|
153
|
+
{ find: options.config.publicAlias + "/review", replacement: path.join(options.dsRoot, options.config.reviewEntry) },
|
|
154
|
+
{ find: options.config.publicAlias, replacement: path.join(options.dsRoot, options.config.publicEntry) },
|
|
155
|
+
{ find: "@reqvire-org/ads/preview", replacement: previewFrameFiles[0] },
|
|
156
|
+
] },
|
|
157
|
+
optimizeDeps: { noDiscovery: true, esbuildOptions: { plugins: [{
|
|
158
|
+
name: "ads-preview-dependency-inputs",
|
|
159
|
+
setup(build) { build.onLoad({ filter: /./ }, args => {
|
|
160
|
+
if (path.isAbsolute(args.path)) { optimizedInputs.add(args.path); inputs.add(args.path); }
|
|
161
|
+
}); },
|
|
162
|
+
}] }, include: [
|
|
163
|
+
...(options.config.framework === "react" ? ["react", "react-dom/client", "react/jsx-runtime", "react/jsx-dev-runtime"] : ["preact", "preact/hooks", "preact/jsx-runtime", "preact/jsx-dev-runtime"]),
|
|
164
|
+
"@linaria/atomic", ...options.config.behaviorLibraries,
|
|
165
|
+
] },
|
|
166
|
+
server: { middlewareMode: true, hmr: { server: socketHost }, watch: null, preTransformRequests: false,
|
|
167
|
+
fs: { allow: [options.root, path.dirname(fileURLToPath(import.meta.url)), path.dirname(Bun.resolveSync(options.config.framework, options.root)),
|
|
168
|
+
...["@prefresh/core", "@prefresh/utils"].map(name => path.dirname(Bun.resolveSync(name + "/package.json", import.meta.dirname)))] } },
|
|
169
|
+
});
|
|
170
|
+
} catch (error) { await transforms.close(); rmSync(directory, { recursive: true, force: true }); throw error; }
|
|
171
|
+
|
|
172
|
+
async function invalidate(nextRevision) {
|
|
173
|
+
revision = nextRevision; spatial = undefined; optimizer = undefined;
|
|
174
|
+
const changed = new Set([...digests].filter(([file, digest]) => fingerprint(file) !== digest).map(([file]) => file));
|
|
175
|
+
for (const [file, value] of transforms.values) {
|
|
176
|
+
if (value.dependencies.some(([dependency]) => changed.has(dependency)) ||
|
|
177
|
+
(value.spatialRevision !== undefined && value.spatialRevision !== (readSpatial()?.revision ?? null))) changed.add(file);
|
|
178
|
+
}
|
|
179
|
+
// Import optimization reads public barrels/package side-effect policy.
|
|
180
|
+
// Recheck those consumers when their captured resolver inputs change.
|
|
181
|
+
if ([...changed].some(file => !lowered.has(file))) for (const [file, value] of lowered)
|
|
182
|
+
if (value.source.includes(options.config.publicAlias)) changed.add(file);
|
|
183
|
+
for (const file of changed) {
|
|
184
|
+
lowered.delete(file);
|
|
185
|
+
if (sheets.has(file + ".ads-incremental.css")) {
|
|
186
|
+
// Vite's CSS node has its own transform cache.
|
|
187
|
+
for (const node of server.moduleGraph.getModulesByFile(file + ".ads-incremental.css") ?? []) server.moduleGraph.invalidateModule(node);
|
|
188
|
+
}
|
|
189
|
+
for (const node of server.moduleGraph.getModulesByFile(file) ?? []) server.moduleGraph.invalidateModule(node);
|
|
190
|
+
}
|
|
191
|
+
stats.changed = [...changed];
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
async function snapshot(entries) {
|
|
195
|
+
const output = new Map(), queued = new Map();
|
|
196
|
+
const moduleName = url => "module-" + hash(cleanUrl(url)) + ".js";
|
|
197
|
+
async function asset(url) {
|
|
198
|
+
const file = sourceFile(url), bytes = readFileSync(file);
|
|
199
|
+
inputs.add(file);
|
|
200
|
+
const name = "asset-" + hash(bytes) + path.extname(file);
|
|
201
|
+
output.set(name, { type: "asset", fileName: name, source: bytes });
|
|
202
|
+
return name;
|
|
203
|
+
}
|
|
204
|
+
async function worker(url) {
|
|
205
|
+
const file = sourceFile(url), previous = workerCache.get(file);
|
|
206
|
+
let value = previous;
|
|
207
|
+
if (!value || value.inputs.some(([input, digest]) => fingerprint(input) !== digest)) {
|
|
208
|
+
const result = await workerBuilder([], options, { generateBundle() {} }, { watched: true, workerEntry: file, sourceRevision: revision });
|
|
209
|
+
const main = result.outputs.find(item => item.kind === "entry-point"), bytes = Buffer.from(main.bytes, "base64");
|
|
210
|
+
value = { name: "worker-" + hash(bytes) + ".js", inputs: result.inputs.map(input => [input, fingerprint(input)]),
|
|
211
|
+
assets: [...result.assets.map(item => ({ ...item, source: Buffer.from(item.source, "base64") })),
|
|
212
|
+
...result.outputs.filter(item => item !== main).map(item => ({ type: "asset", fileName: item.path.replace(/^\.\//, ""), source: Buffer.from(item.bytes, "base64") }))], bytes };
|
|
213
|
+
workerCache.set(file, value);
|
|
214
|
+
}
|
|
215
|
+
for (const [input] of value.inputs) inputs.add(input);
|
|
216
|
+
for (const item of value.assets) output.set(item.fileName, item);
|
|
217
|
+
output.set(value.name, { type: "asset", fileName: value.name, source: value.bytes });
|
|
218
|
+
return value.name;
|
|
219
|
+
}
|
|
220
|
+
function queue(url) {
|
|
221
|
+
url = cleanUrl(url);
|
|
222
|
+
if (!queued.has(url)) queued.set(url, undefined);
|
|
223
|
+
return moduleName(url);
|
|
224
|
+
}
|
|
225
|
+
async function cssAsset(code, url) {
|
|
226
|
+
const parsed = valueParser(code), targets = [];
|
|
227
|
+
parsed.walk(node => {
|
|
228
|
+
if (node.type !== "function" || node.value !== "url") return;
|
|
229
|
+
const value = valueParser.stringify(node.nodes).replace(/^["']|["']$/g, "");
|
|
230
|
+
if (value.startsWith("/") && !value.startsWith("//")) targets.push([node, value]);
|
|
231
|
+
});
|
|
232
|
+
for (const [node, value] of targets) {
|
|
233
|
+
const [target, fragment] = value.split("#");
|
|
234
|
+
node.nodes = [{ type: "string", quote: '"', value: "./" + await asset(target) + (fragment ? "#" + fragment : "") }];
|
|
235
|
+
}
|
|
236
|
+
const source = parsed.toString(), name = "style-" + hash(cleanUrl(url)) + ".css";
|
|
237
|
+
const owner = sourceFile(url).replace(/\.ads-incremental\.css$/, "");
|
|
238
|
+
output.set(name, { type: "asset", fileName: name, source, spatial: spatialMetadata(source, slash(path.relative(options.root, owner))) });
|
|
239
|
+
return name;
|
|
240
|
+
}
|
|
241
|
+
const roots = entries.map((entry, index) => {
|
|
242
|
+
const file = path.join(directory, hash(entry.id) + ".tsx");
|
|
243
|
+
const mount = entry.foundation
|
|
244
|
+
? `import {mountFoundation} from ${JSON.stringify(path.join(frame, "foundation-view.mjs"))};export const mount=container=>mountFoundation(container,${JSON.stringify(entry.foundation)});`
|
|
245
|
+
: `import {mountScenario} from ${JSON.stringify(path.join(options.dsRoot, "showcase/mcp/main.ads.mount.tsx"))};import Scenario from ${JSON.stringify(path.join(options.root, entry.file))};export const mount=container=>mountScenario(Scenario,container);`;
|
|
246
|
+
// The configured design-system sheet belongs to every preview, including
|
|
247
|
+
// tool-generated foundations which do not import a project mount adapter.
|
|
248
|
+
const code = `import ${JSON.stringify(path.join(options.dsRoot, options.config.stylesEntry))};\nimport ${JSON.stringify(bootstrapId)};\n` + mount;
|
|
249
|
+
if (generated.get(file) !== code) {
|
|
250
|
+
writeFileSync(file, code); generated.set(file, code);
|
|
251
|
+
for (const node of server.moduleGraph.getModulesByFile(file) ?? []) server.moduleGraph.invalidateModule(node);
|
|
252
|
+
}
|
|
253
|
+
const url = sourceUrl(file); queue(url);
|
|
254
|
+
return [moduleName(url), index];
|
|
255
|
+
});
|
|
256
|
+
for (const [url] of queued) {
|
|
257
|
+
if (queued.size > 4096) throw new Error("Preview module graph exceeds 4096 modules.");
|
|
258
|
+
const transformed = url === clientId ? { code: clientCode } : await server.transformRequest(url);
|
|
259
|
+
if (!transformed) throw new Error("Missing preview module: " + url);
|
|
260
|
+
const node = await server.moduleGraph.getModuleByUrl(url);
|
|
261
|
+
if (node?.file && existsSync(node.file)) inputs.add(node.file);
|
|
262
|
+
let code = transformed.code.replace(/\n\/\/# sourceMappingURL=.*$/gm, "");
|
|
263
|
+
// Prefresh owns hook signatures/replacement. Unlike React Refresh it does
|
|
264
|
+
// not validate mixed exports itself; keep changed non-component exports
|
|
265
|
+
// from being silently accepted with stale importer bindings.
|
|
266
|
+
if (options.config.framework === "preact" && node?.file?.startsWith(options.dsRoot + path.sep) && code.includes("import.meta.hot")) {
|
|
267
|
+
const utils = sourceUrl(Bun.resolveSync("@prefresh/utils", import.meta.dirname));
|
|
268
|
+
code += `\nimport {isComponent as __adsIsComponent} from ${JSON.stringify(utils)};globalThis.__adsPreviewHot.observe(${JSON.stringify(node.url)},import.meta.url,__adsIsComponent);\n`;
|
|
269
|
+
}
|
|
270
|
+
const styles = [];
|
|
271
|
+
// Vite compiles @imports/assets/CSS modules. ADS owns stylesheet attachment
|
|
272
|
+
// and removal, so its snapshot carries the CSS as an ordinary graph asset.
|
|
273
|
+
if (/\.css(?:\?|$)/.test(url) && !/[?&](?:inline|raw)(?:&|$)/.test(url)) {
|
|
274
|
+
const match = code.match(/(?:const|let|var) __vite__css = ("(?:[^"\\]|\\.)*")/);
|
|
275
|
+
if (match) {
|
|
276
|
+
styles.push(await cssAsset(JSON.parse(match[1]), url));
|
|
277
|
+
code = code.replace(match[0], 'const __vite__css = ""').replace(/^import .*from ["']\/@vite\/client["'];?\s*$/gm, "")
|
|
278
|
+
.replace(/^__vite__updateStyle\([^\n]*\)\s*;?$/gm, "")
|
|
279
|
+
.replace(/^import\.meta\.hot\.[^\n]*$/gm, "")
|
|
280
|
+
.replace(/^import\.meta\.hot\s*=.*$/gm, "");
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
const imports = [], dynamicImports = [], edits = [];
|
|
284
|
+
for (const item of parse(code)[0]) {
|
|
285
|
+
if (item.d === -2) continue;
|
|
286
|
+
// React Refresh's self-import receives the already materialized module
|
|
287
|
+
// URL. Authored dynamic imports still need a finite registered closure.
|
|
288
|
+
if (!item.n && url === "/@react-refresh") continue;
|
|
289
|
+
if (!item.n) throw new Error("Preview dynamic imports must resolve to registered local modules: " + url);
|
|
290
|
+
if (/^(?:https?:|data:|blob:)/.test(item.n)) throw new Error("Preview modules must use registered local resources: " + item.n);
|
|
291
|
+
const resolved = new URL(item.n, "http://ads" + url);
|
|
292
|
+
const targetUrl = resolved.pathname + resolved.search;
|
|
293
|
+
const target = queue(targetUrl);
|
|
294
|
+
(item.d < 0 ? imports : dynamicImports).push(target);
|
|
295
|
+
edits.push([item.s, item.e, item.d < 0 ? "./" + target : JSON.stringify("./" + target)]);
|
|
296
|
+
}
|
|
297
|
+
// Asset wrappers and worker constructors contain compiler-generated URLs.
|
|
298
|
+
for (const match of code.matchAll(/"(\/(?:[^"\\\r\n]|\\.)*)"/g)) {
|
|
299
|
+
const value = JSON.parse(match[0]);
|
|
300
|
+
// Static import spans exclude their quotes, while this match includes
|
|
301
|
+
// them. Any overlap means the module rewrite already owns this string.
|
|
302
|
+
if (edits.some(([start, end]) => start < match.index + match[0].length && end > match.index)) continue;
|
|
303
|
+
if (/[?&]worker_file(?:&|=|$)/.test(value)) edits.push([match.index, match.index + match[0].length, JSON.stringify("./" + await worker(value))]);
|
|
304
|
+
else {
|
|
305
|
+
const file = sourceFile(value);
|
|
306
|
+
const urlImport = /[?&]url(?:&|$)/.test(url) && node?.file === file;
|
|
307
|
+
const urlConstructor = /new URL\(\s*(?:\/\* @vite-ignore \*\/\s*)?$/.test(code.slice(0, match.index));
|
|
308
|
+
if ((server.config.assetsInclude(file) || urlImport || urlConstructor) && existsSync(file))
|
|
309
|
+
edits.push([match.index, match.index + match[0].length, JSON.stringify("./" + await asset(value))]);
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
for (const [start, end, replacement] of edits.sort((a, b) => b[0] - a[0])) code = code.slice(0, start) + replacement + code.slice(end);
|
|
313
|
+
const name = moduleName(url);
|
|
314
|
+
output.set(name, { type: "chunk", fileName: name, code, imports, dynamicImports,
|
|
315
|
+
viteMetadata: { importedCss: new Set(styles) }, hot: { id: url, source: hash(code) } });
|
|
316
|
+
queued.set(url, name);
|
|
317
|
+
}
|
|
318
|
+
for (const [file, index] of roots) output.get(file).facadeModuleId = "\0ads-preview-entry:" + index;
|
|
319
|
+
return { output: [...output.values()] };
|
|
320
|
+
}
|
|
321
|
+
return {
|
|
322
|
+
configuration, transforms, get stats() { return stats; },
|
|
323
|
+
// Optimized modules live in the private temporary directory. Their original
|
|
324
|
+
// inputs still belong to cache evidence, including transitive CJS requires.
|
|
325
|
+
// Recreate the optimizer when those bytes change; invalidating a source node
|
|
326
|
+
// alone cannot invalidate an already optimized dependency bundle.
|
|
327
|
+
get dependenciesChanged() {
|
|
328
|
+
return [...optimizedInputs].some(file => digests.has(file) && fingerprint(file) !== digests.get(file));
|
|
329
|
+
},
|
|
330
|
+
// Vite owns resolution caches in addition to transforms. Renew the graph
|
|
331
|
+
// on additions/deletions rather than reusing an old resolved module ID.
|
|
332
|
+
get membershipChanged() { return membership === undefined || inputMembership() !== membership; },
|
|
333
|
+
// Vite retains graph nodes for deleted/renamed files; extraction also owns
|
|
334
|
+
// reusable evaluations. Bound this session without dropping input evidence
|
|
335
|
+
// from a still-live cache. A new epoch gives the browser a clean renderer.
|
|
336
|
+
get exhausted() {
|
|
337
|
+
return inputs.size > 4096 || server.moduleGraph.idToModuleMap.size > 4096 ||
|
|
338
|
+
[...lowered.values()].reduce((size, value) => size + Buffer.byteLength(value.source) + Buffer.byteLength(value.code), 0) > 64 * 1024 * 1024;
|
|
339
|
+
},
|
|
340
|
+
async build(entries, track, nextRevision) {
|
|
341
|
+
stats = { transformed: [], extracted: [], changed: [] };
|
|
342
|
+
await invalidate(nextRevision);
|
|
343
|
+
const output = await snapshot(entries);
|
|
344
|
+
// PostCSS inlines CSS imports. Vite records these as file-only graph nodes,
|
|
345
|
+
// so they must join byte fingerprints even though no JS import queues them.
|
|
346
|
+
for (const file of server.moduleGraph.fileToModulesMap.keys()) inputs.add(file);
|
|
347
|
+
const sourceInputs = [...inputs].filter(file => !file.startsWith(directory + path.sep));
|
|
348
|
+
track.generateBundle.call({ getModuleIds: () => sourceInputs });
|
|
349
|
+
for (const file of sourceInputs) digests.set(file, fingerprint(file));
|
|
350
|
+
membership = inputMembership();
|
|
351
|
+
return createPreviewResources(output, options, entries, { prune: true, refresh: { version: 1, epoch }, preparedCache });
|
|
352
|
+
},
|
|
353
|
+
async close() {
|
|
354
|
+
await active; await server.close(); await transforms.close(); await workerBuilder.close();
|
|
355
|
+
socketHost.close(); rmSync(directory, { recursive: true, force: true });
|
|
356
|
+
},
|
|
357
|
+
};
|
|
358
|
+
}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
const revisionPattern = /^[a-f0-9]{64}$/;
|
|
2
|
+
const assetPattern = /^ads:\/\/assets\/[a-f0-9]{64}\.[a-z0-9]+$/;
|
|
3
|
+
const equal = (left, right) => JSON.stringify(left) === JSON.stringify(right);
|
|
4
|
+
const metadata = ({ assets: _assets, scenarios: _scenarios, ...header }) => header;
|
|
5
|
+
|
|
6
|
+
/** Internal UI transport only. Existing full-manifest resources stay unchanged. */
|
|
7
|
+
export function previewManifestUpdate(current, previous) {
|
|
8
|
+
const full = { version: 1, type: "full", manifest: current };
|
|
9
|
+
if (!previous) return full;
|
|
10
|
+
const header = metadata(current), baseRevision = previous.revision;
|
|
11
|
+
if (baseRevision === current.revision) return { version: 1, type: "unchanged", baseRevision, header };
|
|
12
|
+
const oldScenarios = new Map(previous.scenarios.map(item => [item.id, item]));
|
|
13
|
+
const order = current.scenarios.map(item => item.id);
|
|
14
|
+
const patch = {
|
|
15
|
+
version: 1, type: "delta", baseRevision, header,
|
|
16
|
+
assets: {
|
|
17
|
+
upsert: Object.fromEntries(Object.entries(current.assets).filter(([uri, record]) => !equal(record, previous.assets[uri]))),
|
|
18
|
+
remove: Object.keys(previous.assets).filter(uri => !Object.hasOwn(current.assets, uri)),
|
|
19
|
+
},
|
|
20
|
+
scenarios: {
|
|
21
|
+
upsert: current.scenarios.filter(item => !equal(item, oldScenarios.get(item.id))),
|
|
22
|
+
remove: previous.scenarios.filter(item => !order.includes(item.id)).map(item => item.id),
|
|
23
|
+
...(!equal(order, previous.scenarios.map(item => item.id)) ? { order } : {}),
|
|
24
|
+
},
|
|
25
|
+
};
|
|
26
|
+
return JSON.stringify(patch).length < JSON.stringify(full).length ? patch : full;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function validate(graph) {
|
|
30
|
+
if (graph?.schemaVersion !== 1 || !["react", "preact"].includes(graph.framework) || !revisionPattern.test(graph.revision) ||
|
|
31
|
+
!graph.assets || typeof graph.assets !== "object" || Array.isArray(graph.assets) || !Array.isArray(graph.scenarios)) throw new Error("Invalid preview manifest update.");
|
|
32
|
+
const ids = new Set();
|
|
33
|
+
for (const scenario of graph.scenarios) {
|
|
34
|
+
if (!scenario || typeof scenario.id !== "string" || ids.has(scenario.id) || graph.assets[scenario.module]?.kind !== "module") throw new Error("Invalid updated preview scenarios.");
|
|
35
|
+
ids.add(scenario.id);
|
|
36
|
+
}
|
|
37
|
+
for (const [uri, record] of Object.entries(graph.assets)) {
|
|
38
|
+
if (!assetPattern.test(uri) || !record || !["imports", "dynamicImports", "styles", "references"].every(key =>
|
|
39
|
+
Array.isArray(record[key]) && record[key].every(target => Object.hasOwn(graph.assets, target)))) throw new Error("Invalid updated preview dependencies.");
|
|
40
|
+
}
|
|
41
|
+
return graph;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Reconstruct without mutating a cached revision or trusting a different base. */
|
|
45
|
+
export function applyPreviewManifestUpdate(update, previous) {
|
|
46
|
+
if (update?.version !== 1) throw new Error("Unsupported preview manifest update.");
|
|
47
|
+
if (update.type === "full") return validate(update.manifest);
|
|
48
|
+
if (!previous || update.baseRevision !== previous.revision) throw new Error("Preview manifest update base does not match.");
|
|
49
|
+
const header = update.header;
|
|
50
|
+
if (!header || Object.hasOwn(header, "assets") || Object.hasOwn(header, "scenarios") || !revisionPattern.test(header.revision)) throw new Error("Invalid preview manifest update header.");
|
|
51
|
+
if (update.type === "unchanged") {
|
|
52
|
+
if (header.revision !== previous.revision) throw new Error("Unchanged preview revision does not match.");
|
|
53
|
+
return validate({ ...header, assets: previous.assets, scenarios: previous.scenarios });
|
|
54
|
+
}
|
|
55
|
+
if (update.type !== "delta" || !update.assets?.upsert || !Array.isArray(update.assets.remove) ||
|
|
56
|
+
!Array.isArray(update.scenarios?.upsert) || !Array.isArray(update.scenarios.remove)) throw new Error("Invalid preview manifest delta.");
|
|
57
|
+
const assets = new Map(Object.entries(previous.assets)), scenarios = new Map(previous.scenarios.map(item => [item.id, item]));
|
|
58
|
+
for (const uri of update.assets.remove) if (!assets.delete(uri)) throw new Error("Unknown removed preview asset.");
|
|
59
|
+
for (const [uri, record] of Object.entries(update.assets.upsert)) assets.set(uri, record);
|
|
60
|
+
for (const id of update.scenarios.remove) if (!scenarios.delete(id)) throw new Error("Unknown removed preview scenario.");
|
|
61
|
+
const changed = new Set();
|
|
62
|
+
for (const item of update.scenarios.upsert) {
|
|
63
|
+
if (!item || changed.has(item.id)) throw new Error("Duplicate updated preview scenario.");
|
|
64
|
+
changed.add(item.id); scenarios.set(item.id, item);
|
|
65
|
+
}
|
|
66
|
+
const order = update.scenarios.order ?? previous.scenarios.map(item => item.id);
|
|
67
|
+
if (!Array.isArray(order) || order.length !== scenarios.size || new Set(order).size !== order.length || order.some(id => !scenarios.has(id)))
|
|
68
|
+
throw new Error("Invalid updated preview scenario order.");
|
|
69
|
+
return validate({ ...header, assets: Object.fromEntries(assets), scenarios: order.map(id => scenarios.get(id)) });
|
|
70
|
+
}
|