@reqvire-org/ads 0.4.2 → 0.4.4
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 +11 -2
- package/dist/a11y.mjs +71 -65
- package/dist/analysis/helpers.mjs +5 -3
- package/dist/analysis/inputs.mjs +13 -6
- package/dist/analysis/module-resolvers.mjs +46 -0
- package/dist/analysis/service.mjs +7 -0
- package/dist/analysis/syntax.mjs +20 -5
- package/dist/assets.mjs +1 -1
- package/dist/boundaries.mjs +6 -4
- package/dist/bun-compiler.mjs +6 -5
- package/dist/check-service.mjs +8 -5
- package/dist/check.mjs +11 -46
- package/dist/component-contrast.mjs +126 -8
- package/dist/contrast-composition.mjs +80 -0
- package/dist/contrast-styles.mjs +88 -0
- package/dist/finding-rules.mjs +2 -0
- package/dist/font-rules.mjs +20 -15
- package/dist/fonts-generated.mjs +21 -14
- package/dist/foundation-views.mjs +6 -2
- package/dist/image-attributes.mjs +96 -92
- package/dist/mcp/build-status.mjs +8 -3
- package/dist/mcp/drafts.mjs +12 -5
- package/dist/mcp/mutations.mjs +11 -8
- package/dist/mcp/preview-widget.bundle.js +45 -45
- package/dist/mcp/resource-loader.js +1 -201
- package/dist/mcp/server.mjs +19 -5
- package/dist/pictogram-model.mjs +59 -0
- package/dist/pictograms.mjs +52 -0
- package/dist/preview-bun.mjs +76 -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-audit/image-shape.mjs +13 -3
- package/dist/render-audit/pictograms.mjs +88 -0
- package/dist/render-audit/worker.mjs +12 -0
- package/dist/render-audit.mjs +11 -1
- package/dist/render-composition.mjs +186 -0
- package/dist/scenario-registry.mjs +2 -2
- package/dist/scenarios-compiler.mjs +1 -1
- package/dist/showcase/client.bundle.js +23 -23
- package/dist/showcase/draft-navigation.js +5 -5
- package/dist/showcase/foundation-view.css +3 -0
- package/dist/showcase/foundation-view.mjs +3 -0
- package/dist/showcase/pictogram-view.mjs +53 -0
- package/dist/showcase/ui/ui.js +2 -0
- package/dist/skills/README.md +1 -1
- package/dist/skills/ads-designer/SKILL.md +18 -2
- package/dist/skills/ads-designer/references/accessibility.md +70 -2
- package/dist/skills/ads-designer/references/branding.md +5 -16
- package/dist/skills/ads-designer/references/performance.md +3 -2
- package/dist/skills/ads-designer/references/pictograms.md +131 -0
- package/dist/skills/ads-designer/references/runtimes.md +15 -0
- package/dist/skills/ads-import/references/runtimes.md +15 -0
- package/dist/skills/ads-migrate/SKILL.md +2 -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 +80 -0
- package/dist/skills/ads-port/SKILL.md +4 -1
- package/dist/skills/ads-port/references/runtimes.md +15 -0
- package/dist/source-values.mjs +4 -1
- package/dist/starters/react/design-system/assets/pictograms/catalog.ads.json +13 -0
- package/dist/starters/react/design-system/assets/pictograms/journey.dark.svg +7 -0
- package/dist/starters/react/design-system/assets/pictograms/journey.svg +7 -0
- package/dist/starters/react/design-system/components/Content/Pictogram/Pictogram.ads.exports.ts +1 -0
- package/dist/starters/react/design-system/components/Content/Pictogram/Pictogram.ads.fixture.ts +1 -0
- package/dist/starters/react/design-system/components/Content/Pictogram/Pictogram.ads.scenario.tsx +7 -0
- package/dist/starters/react/design-system/components/Content/Pictogram/Pictogram.tsx +26 -0
- package/dist/style-token-rules.mjs +51 -0
- package/dist/task-cache.mjs +2 -2
- package/dist/units.mjs +4 -4
- package/dist/validation-inputs.mjs +7 -3
- package/docs/ADS.md +6 -1
- package/docs/ARCHITECTURE.md +144 -16
- package/docs/CACHING.md +65 -1
- package/docs/CHANGELOG.md +86 -50
- package/docs/GUIDE.md +52 -7
- package/docs/MCP.md +47 -16
- package/docs/benchmarks/README.md +1 -1
- package/package.json +7 -4
|
@@ -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
|
+
}
|
|
@@ -6,6 +6,7 @@ import ts from "./analysis/syntax.mjs";
|
|
|
6
6
|
import valueParser from "postcss-value-parser";
|
|
7
7
|
import { isInside } from "./config.mjs";
|
|
8
8
|
import { livePreviewOptions, previewArtifactPath, previewManifestPath } from "./preview-scope.mjs";
|
|
9
|
+
import { previewManifestUpdate } from "./preview-manifest-update.mjs";
|
|
9
10
|
|
|
10
11
|
export const PREVIEW_APP_URI = "ui://ads/preview";
|
|
11
12
|
export const PREVIEW_MANIFEST_URI = "ads://preview/manifest";
|
|
@@ -102,10 +103,15 @@ function resourceUris(prepared) {
|
|
|
102
103
|
}
|
|
103
104
|
|
|
104
105
|
/** Convert compiler output to registered MCP resources without evaluating project code. */
|
|
105
|
-
export async function createPreviewResources(output, options, entries, { retain, prune = false } = {}) {
|
|
106
|
+
export async function createPreviewResources(output, options, entries, { retain, prune = false, refresh, preparedCache } = {}) {
|
|
106
107
|
const bundle = (Array.isArray(output) ? output : [output]).flatMap((result) => result.output);
|
|
107
108
|
const files = new Map(bundle.map((item) => [item.fileName, item]));
|
|
108
109
|
const original = (item) => Buffer.from(item.type === "chunk" ? item.code : item.source);
|
|
110
|
+
// One prepared rewrite per current output file. Membership matters because a
|
|
111
|
+
// formerly external string can become a graph reference. Worker bytes also
|
|
112
|
+
// participate: unchanged callers must recheck a changed worker's module form.
|
|
113
|
+
const membership = preparedCache && hash(JSON.stringify(bundle.map(item => [item.fileName, item.type,
|
|
114
|
+
item.type === "asset" && item.fileName.endsWith(".js") ? hash(original(item)) : null]).sort((a, b) => a[0].localeCompare(b[0]))));
|
|
109
115
|
const prepared = new Map();
|
|
110
116
|
const records = { ...retain?.manifest.assets };
|
|
111
117
|
const contents = new Map(retain?.contents);
|
|
@@ -117,6 +123,9 @@ export async function createPreviewResources(output, options, entries, { retain,
|
|
|
117
123
|
for (const item of bundle) {
|
|
118
124
|
const references = new Set();
|
|
119
125
|
const bytes = original(item);
|
|
126
|
+
const preparationKey = preparedCache && hash(JSON.stringify([membership, hash(bytes), item.imports, item.dynamicImports, [...(item.viteMetadata?.importedCss ?? [])]]));
|
|
127
|
+
const cachedPreparation = preparedCache?.get(item.fileName);
|
|
128
|
+
if (cachedPreparation && cachedPreparation.key === preparationKey) { prepared.set(item.fileName, cachedPreparation.value); continue; }
|
|
120
129
|
let render = () => bytes;
|
|
121
130
|
if (item.type === "chunk" || item.fileName.endsWith(".js")) {
|
|
122
131
|
const source = await ts.createSourceFile(item.fileName, bytes.toString(), ts.ScriptTarget.Latest, true, ts.ScriptKind.JS);
|
|
@@ -201,7 +210,9 @@ export async function createPreviewResources(output, options, entries, { retain,
|
|
|
201
210
|
const styles = item.type === "chunk" ? [...(item.viteMetadata?.importedCss ?? [])].filter((file) => files.has(file)) : [];
|
|
202
211
|
const links = { imports, dynamicImports, styles, references: [...references] };
|
|
203
212
|
prepared.set(item.fileName, { file: item.fileName, digest: hash(bytes), links, dependencies, render });
|
|
213
|
+
preparedCache?.set(item.fileName, { key: preparationKey, value: prepared.get(item.fileName) });
|
|
204
214
|
}
|
|
215
|
+
if (preparedCache) for (const file of preparedCache.keys()) if (!files.has(file)) preparedCache.delete(file);
|
|
205
216
|
// Bump the transform version in resourceUris whenever rewriting changes.
|
|
206
217
|
const uris = resourceUris(prepared);
|
|
207
218
|
for (const item of bundle) {
|
|
@@ -216,6 +227,7 @@ export async function createPreviewResources(output, options, entries, { retain,
|
|
|
216
227
|
kind: item.type === "chunk" ? "module" : "asset",
|
|
217
228
|
...links,
|
|
218
229
|
...(item.spatial ? { spatial: item.spatial } : {}),
|
|
230
|
+
...(item.hot ? { hot: item.hot } : {}),
|
|
219
231
|
};
|
|
220
232
|
contents.set(uri, bytes);
|
|
221
233
|
}
|
|
@@ -248,6 +260,7 @@ export async function createPreviewResources(output, options, entries, { retain,
|
|
|
248
260
|
const graph = {
|
|
249
261
|
schemaVersion: 1,
|
|
250
262
|
framework: options.config.framework,
|
|
263
|
+
...(refresh ? { refresh } : {}),
|
|
251
264
|
themes: options.config.themes,
|
|
252
265
|
...(options.config.brands?.length ? { brands: options.config.brands } : {}),
|
|
253
266
|
assets: records,
|
|
@@ -394,6 +407,20 @@ export function readPreviewManifest(options, { verify = false } = {}) {
|
|
|
394
407
|
return manifest;
|
|
395
408
|
}
|
|
396
409
|
|
|
410
|
+
/** Use only retained, validated metadata in this project's preview scope. Missing
|
|
411
|
+
* history costs a full response; it never changes current-source authorization. */
|
|
412
|
+
export function readPreviewManifestUpdate(options, current, from) {
|
|
413
|
+
if (!/^[a-f0-9]{64}$/.test(from ?? "")) throw new Error("Preview update from must be a SHA-256 revision.");
|
|
414
|
+
if (from === current.revision) return previewManifestUpdate(current, current);
|
|
415
|
+
for (const file of [path.join(path.dirname(previewManifestPath(options)), "history", `${from}.json`), previewManifestPath(cacheOptions(options, from))]) {
|
|
416
|
+
try {
|
|
417
|
+
const previous = readManifestFile(file);
|
|
418
|
+
if (previous.revision === from) return previewManifestUpdate(current, previous);
|
|
419
|
+
} catch { /* Expired/corrupt history cannot become a delta base. */ }
|
|
420
|
+
}
|
|
421
|
+
return previewManifestUpdate(current);
|
|
422
|
+
}
|
|
423
|
+
|
|
397
424
|
function readManifestFile(file) {
|
|
398
425
|
if (realpathSync(file) !== file || !statSync(file).isFile() || statSync(file).size > 2 * 1024 * 1024) throw new Error("Invalid preview manifest file.");
|
|
399
426
|
return validateManifest(JSON.parse(readFileSync(file, "utf8")));
|
|
@@ -410,6 +437,9 @@ function validateManifest(manifest) {
|
|
|
410
437
|
!Array.isArray(manifest.scenarios)
|
|
411
438
|
)
|
|
412
439
|
throw new Error("Invalid preview resource manifest. Rebuild the project previews.");
|
|
440
|
+
if (manifest.refresh && (manifest.refresh.version !== 1 || typeof manifest.refresh.epoch !== "string" || !manifest.refresh.epoch || manifest.refresh.epoch.length > 100))
|
|
441
|
+
throw new Error("Invalid preview refresh protocol.");
|
|
442
|
+
const hotIds = new Set();
|
|
413
443
|
for (const [uri, record] of Object.entries(manifest.assets)) {
|
|
414
444
|
if (
|
|
415
445
|
!record ||
|
|
@@ -420,11 +450,13 @@ function validateManifest(manifest) {
|
|
|
420
450
|
record.size < 0 ||
|
|
421
451
|
record.size > 16 * 1024 * 1024 ||
|
|
422
452
|
typeof record.mimeType !== "string" ||
|
|
453
|
+
(record.hot && (!manifest.refresh || record.kind !== "module" || typeof record.hot.id !== "string" || !record.hot.id || record.hot.id.length > 4096 || hotIds.has(record.hot.id) || !/^[a-f0-9]{64}$/.test(record.hot.source))) ||
|
|
423
454
|
!["imports", "dynamicImports", "styles", "references"].every(
|
|
424
455
|
(key) => Array.isArray(record[key]) && record[key].every((ref) => Object.hasOwn(manifest.assets, ref)),
|
|
425
456
|
)
|
|
426
457
|
)
|
|
427
458
|
throw new Error("Invalid preview asset dependency graph.");
|
|
459
|
+
if (record.hot) hotIds.add(record.hot.id);
|
|
428
460
|
}
|
|
429
461
|
if (
|
|
430
462
|
manifest.scenarios.some((entry) => !entry || typeof entry.id !== "string" || manifest.assets[entry.module]?.kind !== "module") ||
|
|
@@ -27,10 +27,20 @@ export function imageShape({ nodeLimit }) {
|
|
|
27
27
|
const width = Number(image.getAttribute("width")), height = Number(image.getAttribute("height"));
|
|
28
28
|
const attributes = width > 0 && height > 0 ? width / height : undefined;
|
|
29
29
|
if (explicit === undefined &&( attributes === undefined || style.objectFit !== "fill")) continue;
|
|
30
|
-
|
|
30
|
+
// CSS's used dimensions are untransformed: a rotated image's axis-aligned
|
|
31
|
+
// bounding rectangle has a different ratio even when the image is correct.
|
|
32
|
+
// An explicit CSS ratio applies to the box chosen by box-sizing. Attribute
|
|
33
|
+
// ratios describe the image content, never its decorative frame.
|
|
34
|
+
const insetX = [style.borderLeftWidth, style.borderRightWidth, style.paddingLeft, style.paddingRight].reduce((sum, value) => sum + parseFloat(value), 0);
|
|
35
|
+
const insetY = [style.borderTopWidth, style.borderBottomWidth, style.paddingTop, style.paddingBottom].reduce((sum, value) => sum + parseFloat(value), 0);
|
|
36
|
+
const borderBox = style.boxSizing === "border-box";
|
|
37
|
+
const measuredWidth = parseFloat(style.width) - (borderBox && explicit === undefined ? insetX : 0);
|
|
38
|
+
const measuredHeight = parseFloat(style.height) - (borderBox && explicit === undefined ? insetY : 0);
|
|
39
|
+
if (!Number.isFinite(measuredWidth) || !Number.isFinite(measuredHeight) || measuredWidth <= 0 || measuredHeight <= 0) continue;
|
|
40
|
+
const declared = explicit ?? attributes, rendered = measuredWidth / measuredHeight;
|
|
31
41
|
// Rounding moves a small box by a pixel or so; 3% and 2 px of height is not rounding.
|
|
32
|
-
if (Math.abs(rendered / declared - 1) <= 0.03 || Math.abs(
|
|
33
|
-
if (counts.shape++ < nodeLimit) issues.push({ kind: "shape", selector: selector(image), html: image.outerHTML.replace(/\s+/g, " ").slice(0, 200), rendered: `${Math.round(
|
|
42
|
+
if (Math.abs(rendered / declared - 1) <= 0.03 || Math.abs(measuredWidth / declared - measuredHeight) <= 2) continue;
|
|
43
|
+
if (counts.shape++ < nodeLimit) issues.push({ kind: "shape", selector: selector(image), html: image.outerHTML.replace(/\s+/g, " ").slice(0, 200), rendered: `${Math.round(measuredWidth)}x${Math.round(measuredHeight)}`, declared: explicit !== undefined ? `aspect-ratio ${style.aspectRatio}` : `width and height ${width}x${height}` });
|
|
34
44
|
}
|
|
35
45
|
return { issues, counts };
|
|
36
46
|
}
|