diff --git a/apps/web/package.json b/apps/web/package.json
index 77afe14..c5adebc 100644
--- a/apps/web/package.json
+++ b/apps/web/package.json
@@ -9,7 +9,8 @@
"dev": "vite",
"build": "vite build",
"check": "svelte-check --tsconfig ./tsconfig.json --fail-on-warnings",
- "test": "vitest run"
+ "test": "vitest run",
+ "shots": "node scripts/shots.mjs"
},
"dependencies": {
"@ianitor/ui": "workspace:*"
diff --git a/apps/web/scripts/shots.mjs b/apps/web/scripts/shots.mjs
new file mode 100644
index 0000000..e5f0a07
--- /dev/null
+++ b/apps/web/scripts/shots.mjs
@@ -0,0 +1,418 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at https://mozilla.org/MPL/2.0/.
+
+// The release's screenshots of the web UI (docs/release.md):
+// node apps/web/scripts/shots.mjs [--out
] (default: /target/aula)
+// Builds the UI, serves it on 127.0.0.1 with /api/v1 answered by the demo control plane
+// (tests/demo.ts: invented data only), photographs each shot of demo.ts's SHOTS in headless Edge
+// or Chrome over DevTools, and writes aula-.png and aula.json in the format of Fabrica's
+// core docs/FORMATS.md ("Fabrica: the Aula page"). On every way out the browser's process tree
+// and the server are stopped and the temporary folder is removed.
+// Exit codes: 0 done, 1 a problem, 130 cancelled.
+
+import { spawn, spawnSync } from "node:child_process";
+import { createHash } from "node:crypto";
+import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
+import { createServer as createHttpServer } from "node:http";
+import { tmpdir } from "node:os";
+import { basename, delimiter, dirname, extname, join, normalize, resolve, sep } from "node:path";
+import { fileURLToPath } from "node:url";
+import { build, createServer as createViteServer } from "vite";
+
+const web = resolve(dirname(fileURLToPath(import.meta.url)), "..");
+const repo = resolve(web, "../..");
+const WAIT_MS = 20_000;
+
+function usage(msg) {
+ console.error(`shots: ${msg}\nusage: node apps/web/scripts/shots.mjs [--out ]`);
+ process.exit(1);
+}
+
+let out = join(repo, "target", "aula");
+for (let i = 2; i < process.argv.length; i++) {
+ const a = process.argv[i];
+ if (a === "--out" && process.argv[i + 1]) out = resolve(process.argv[++i]);
+ else usage(`unknown argument ${a}`);
+}
+
+const log = (m) => console.log(`shots: ${m}`);
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+
+// ---------- cleanup on every way out ----------
+
+const cleanups = [];
+let cleaning = false;
+async function cleanup() {
+ if (cleaning) return;
+ cleaning = true;
+ for (const f of cleanups.reverse()) {
+ try {
+ await f();
+ } catch (e) {
+ console.error(`shots: cleanup: ${e?.message ?? e}`);
+ }
+ }
+}
+process.on("SIGINT", () => void cleanup().then(() => process.exit(130)));
+process.on("SIGTERM", () => void cleanup().then(() => process.exit(130)));
+
+// ---------- the output folder ----------
+
+function clearOutput() {
+ mkdirSync(out, { recursive: true });
+ for (const n of readdirSync(out)) {
+ if (n === "aula.json" || (n.startsWith("aula-") && n.endsWith(".png"))) rmSync(join(out, n), { force: true });
+ }
+}
+
+/** Width and height from the PNG's IHDR, not assumed. */
+function pngSize(png) {
+ const sig = "89504e470d0a1a0a";
+ if (png.length < 24 || png.subarray(0, 8).toString("hex") !== sig || png.subarray(12, 16).toString("latin1") !== "IHDR") {
+ throw new Error("the browser's capture is not a PNG");
+ }
+ return { width: png.readUInt32BE(16), height: png.readUInt32BE(20) };
+}
+
+// ---------- the demo control plane and the built UI on 127.0.0.1 ----------
+
+const TYPES = {
+ ".html": "text/html; charset=utf-8",
+ ".js": "text/javascript; charset=utf-8",
+ ".css": "text/css; charset=utf-8",
+ ".json": "application/json",
+ ".svg": "image/svg+xml",
+ ".png": "image/png",
+ ".ico": "image/x-icon",
+ ".woff": "font/woff",
+ ".woff2": "font/woff2",
+ ".txt": "text/plain; charset=utf-8",
+};
+
+function serve(dist, api) {
+ const index = readFileSync(join(dist, "index.html"));
+ const server = createHttpServer((req, res) => {
+ const url = new URL(req.url ?? "/", "http://127.0.0.1");
+ if (url.pathname.startsWith("/api/v1/") || url.pathname === "/api/v1") {
+ const chunks = [];
+ req.on("data", (c) => chunks.push(c));
+ req.on("end", () => {
+ let body = {};
+ try {
+ body = chunks.length ? JSON.parse(Buffer.concat(chunks).toString("utf8")) : {};
+ } catch {
+ body = {};
+ }
+ const a = api(req.method ?? "GET", url.pathname.slice("/api/v1".length) + url.search, body);
+ res.writeHead(a.status, { "Content-Type": "application/json", "Cache-Control": "no-store" });
+ res.end(a.text ?? undefined);
+ });
+ return;
+ }
+ // The built files; any other path is the app's own route, answered with index.html.
+ const file = normalize(join(dist, decodeURIComponent(url.pathname)));
+ if (file.startsWith(dist + sep) && existsSync(file) && statSync(file).isFile()) {
+ res.writeHead(200, { "Content-Type": TYPES[extname(file)] ?? "application/octet-stream" });
+ res.end(readFileSync(file));
+ return;
+ }
+ res.writeHead(200, { "Content-Type": TYPES[".html"], "Cache-Control": "no-store" });
+ res.end(index);
+ });
+ return new Promise((ok, fail) => {
+ server.once("error", fail);
+ server.listen(0, "127.0.0.1", () => ok(server));
+ });
+}
+
+// ---------- the browser ----------
+
+function findBrowser() {
+ const named = process.env.IANITOR_SHOTS_BROWSER;
+ if (named) {
+ if (!existsSync(named)) throw new Error(`IANITOR_SHOTS_BROWSER: ${named} does not exist`);
+ return named;
+ }
+ const candidates = [];
+ if (process.platform === "win32") {
+ for (const base of [process.env["ProgramFiles(x86)"], process.env.ProgramFiles, process.env.LOCALAPPDATA].filter(Boolean)) {
+ candidates.push(join(base, "Microsoft", "Edge", "Application", "msedge.exe"), join(base, "Google", "Chrome", "Application", "chrome.exe"));
+ }
+ } else {
+ for (const dir of (process.env.PATH ?? "").split(delimiter).filter(Boolean)) {
+ for (const n of ["chromium", "chromium-browser", "google-chrome", "google-chrome-stable", "microsoft-edge"]) candidates.push(join(dir, n));
+ }
+ candidates.push("/Applications/Google Chrome.app/Contents/MacOS/Google Chrome");
+ }
+ const found = candidates.find((c) => existsSync(c));
+ if (!found) throw new Error("no Microsoft Edge or Chrome found; set IANITOR_SHOTS_BROWSER to a Chromium browser");
+ return found;
+}
+
+/** Only what a program needs to run, the user folders in the temporary folder, nothing of the runner's. */
+function cleanEnv(home) {
+ const keep = /^(SystemRoot|SystemDrive|windir|ComSpec|PATH|PATHEXT|OS|PROCESSOR_.*|NUMBER_OF_PROCESSORS|ProgramFiles.*|ProgramW6432|CommonProgramFiles.*|CommonProgramW6432|ProgramData|ALLUSERSPROFILE|PUBLIC|LANG|TZ)$/i;
+ const env = {};
+ for (const [k, v] of Object.entries(process.env)) if (keep.test(k) && v !== undefined) env[k] = v;
+ for (const d of ["home", "appdata", "local", "temp"]) mkdirSync(join(home, d), { recursive: true });
+ Object.assign(env, {
+ HOME: join(home, "home"),
+ USERPROFILE: join(home, "home"),
+ APPDATA: join(home, "appdata"),
+ LOCALAPPDATA: join(home, "local"),
+ TEMP: join(home, "temp"),
+ TMP: join(home, "temp"),
+ TMPDIR: join(home, "temp"),
+ });
+ return env;
+}
+
+/** Edge may start its browser again as a new process, outside the tree: on Windows, anything still
+ * running with a profile in the temporary folder is stopped by its command line. */
+function sweep(exe, tmp) {
+ if (process.platform !== "win32") return;
+ const script = "Get-CimInstance Win32_Process -Filter \"Name='$env:SHOTS_EXE'\" | Where-Object { $_.CommandLine -and $_.CommandLine.Contains($env:SHOTS_TMP) } | ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }";
+ spawnSync("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", script], {
+ stdio: "ignore",
+ windowsHide: true,
+ env: { ...cleanEnv(join(tmp, "sweep")), SHOTS_EXE: basename(exe), SHOTS_TMP: tmp },
+ });
+}
+
+function killTree(child) {
+ if (!child.pid || child.exitCode !== null) return;
+ if (process.platform === "win32") {
+ spawnSync("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore", windowsHide: true });
+ } else {
+ try {
+ process.kill(-child.pid, "SIGKILL");
+ } catch {
+ child.kill("SIGKILL");
+ }
+ }
+}
+
+/** Starts the browser; one that has not opened DevTools after 20 s is killed and started again, twice. */
+async function startBrowser(exe, tmp, size) {
+ for (let attempt = 1; ; attempt++) {
+ try {
+ return await launch(exe, join(tmp, `profile-${attempt}`), join(tmp, `user-${attempt}`), size);
+ } catch (e) {
+ if (attempt === 3 || e.fatal) throw e;
+ log(`${e.message}; starting it again`);
+ }
+ }
+}
+
+async function launch(exe, profile, user, size) {
+ mkdirSync(profile, { recursive: true });
+ const args = [
+ "--headless=new",
+ "--remote-debugging-port=0",
+ "--remote-debugging-address=127.0.0.1",
+ `--user-data-dir=${profile}`,
+ "--no-first-run",
+ "--no-default-browser-check",
+ "--disable-extensions",
+ "--disable-sync",
+ "--disable-background-networking",
+ "--disable-component-update",
+ "--disable-default-apps",
+ "--disable-features=Translate,OptimizationHints,MediaRouter,msSmartScreenProtection",
+ "--hide-scrollbars",
+ "--mute-audio",
+ "--force-color-profile=srgb",
+ "--force-device-scale-factor=1",
+ `--window-size=${size.width},${size.height}`,
+ "about:blank",
+ ];
+ const child = spawn(exe, args, { env: cleanEnv(user), stdio: ["ignore", "ignore", "pipe"], windowsHide: true, detached: process.platform !== "win32" });
+ const stop = async () => {
+ killTree(child);
+ for (let i = 0; i < 50 && child.exitCode === null && child.signalCode === null; i++) await sleep(100);
+ };
+ cleanups.push(stop);
+ let stderr = "";
+ child.stderr.on("data", (d) => (stderr = (stderr + d).slice(-2000)));
+ const fail = async (msg, fatal = false) => {
+ await stop();
+ const tail = stderr.trim().split(/\r?\n/).slice(-3).join(" | ");
+ throw Object.assign(new Error(`${msg}${tail ? `; it said: ${tail}` : ""}`), { fatal });
+ };
+ let exited = null;
+ child.on("exit", (code) => (exited = code ?? -1));
+ child.on("error", (e) => (exited = e.message));
+
+ const portFile = join(profile, "DevToolsActivePort");
+ const deadline = Date.now() + 20_000;
+ let seen = "no DevToolsActivePort yet";
+ for (;;) {
+ if (exited !== null) await fail(`the browser exited before it was ready (${exited})`, typeof exited === "string");
+ if (existsSync(portFile)) {
+ const port = Number(readFileSync(portFile, "utf8").split(/\r?\n/)[0]);
+ if (port > 0) {
+ try {
+ const list = await (await fetch(`http://127.0.0.1:${port}/json/list`)).json();
+ const page = list.find((t) => t.type === "page" && t.webSocketDebuggerUrl);
+ if (page) return page.webSocketDebuggerUrl;
+ seen = `no page among ${list.length} targets on port ${port}`;
+ await fetch(`http://127.0.0.1:${port}/json/new?about:blank`, { method: "PUT" }).catch(() => {});
+ } catch (e) {
+ seen = `port ${port}: ${e.cause?.message ?? e.message}`;
+ }
+ }
+ }
+ if (Date.now() > deadline) await fail(`the browser's DevTools did not answer within 20 s (${seen})`);
+ await sleep(200);
+ }
+}
+
+/** A minimal DevTools client over Node's WebSocket. */
+async function devtools(url) {
+ const ws = new WebSocket(url);
+ await new Promise((ok, fail) => {
+ ws.onopen = ok;
+ ws.onerror = () => fail(new Error("cannot open the browser's DevTools socket"));
+ });
+ let id = 0;
+ const pending = new Map();
+ ws.onmessage = (m) => {
+ const msg = JSON.parse(String(m.data));
+ const p = msg.id !== undefined && pending.get(msg.id);
+ if (!p) return;
+ pending.delete(msg.id);
+ if (msg.error) p.fail(new Error(`${p.method}: ${msg.error.message}`));
+ else p.ok(msg.result);
+ };
+ ws.onclose = () => {
+ for (const p of pending.values()) p.fail(new Error("the browser closed its DevTools socket"));
+ pending.clear();
+ };
+ cleanups.push(() => ws.close());
+ const send = (method, params = {}) =>
+ new Promise((ok, fail) => {
+ const n = ++id;
+ pending.set(n, { ok, fail, method });
+ ws.send(JSON.stringify({ id: n, method, params }));
+ });
+ /** The value of an expression in the page; a page being replaced answers again later. */
+ const evaluate = async (expression) => {
+ const r = await send("Runtime.evaluate", { expression, awaitPromise: true, returnByValue: true });
+ if (r.exceptionDetails) throw new Error(r.exceptionDetails.exception?.description ?? r.exceptionDetails.text);
+ return r.result.value;
+ };
+ return { send, evaluate };
+}
+
+async function until(what, test) {
+ const deadline = Date.now() + WAIT_MS;
+ let last = null;
+ while (Date.now() < deadline) {
+ try {
+ if (await test()) return;
+ } catch (e) {
+ last = e;
+ }
+ await sleep(100);
+ }
+ throw new Error(`waited ${WAIT_MS / 1000} s for ${what}${last ? ` (${last.message})` : ""}`);
+}
+
+// ---------- the shots ----------
+
+async function main() {
+ clearOutput();
+ const tmp = mkdtempSync(join(tmpdir(), "ianitor-shots-"));
+ cleanups.push(async () => {
+ for (let i = 0; i < 20; i++) {
+ try {
+ rmSync(tmp, { recursive: true, force: true });
+ return;
+ } catch {
+ await sleep(250);
+ }
+ }
+ console.error(`shots: could not remove ${tmp}`);
+ });
+
+ // The demo's shots and answers, from the TypeScript the tests use.
+ const loader = await createViteServer({
+ root: web,
+ configFile: false,
+ logLevel: "error",
+ appType: "custom",
+ server: { middlewareMode: true, hmr: false, ws: false },
+ optimizeDeps: { noDiscovery: true, include: [] },
+ });
+ let demo;
+ try {
+ demo = await loader.ssrLoadModule("/tests/demo.ts");
+ } finally {
+ await loader.close();
+ }
+ const { SHOTS, SIZE, demoApi } = demo;
+
+ log("building the web UI");
+ const dist = join(tmp, "dist");
+ await build({ root: web, logLevel: "warn", build: { outDir: dist, emptyOutDir: true } });
+
+ const server = await serve(dist, demoApi());
+ cleanups.push(() => new Promise((r) => server.close(() => r())));
+ server.closeAllConnections && cleanups.push(() => server.closeAllConnections());
+ const base = `http://127.0.0.1:${server.address().port}`;
+ log(`demo control plane and UI on ${base}`);
+
+ const exe = findBrowser();
+ log(`browser: ${exe}`);
+ cleanups.push(() => sweep(exe, tmp));
+ const page = await devtools(await startBrowser(exe, tmp, SIZE));
+ await page.send("Page.enable");
+ await page.send("Emulation.setDeviceMetricsOverride", { width: SIZE.width, height: SIZE.height, deviceScaleFactor: 1, mobile: false });
+
+ const taken = [];
+ for (const shot of SHOTS) {
+ const url = base + shot.path;
+ try {
+ // A fresh load per shot: mark the old page, so a page that has not been replaced yet does not count.
+ await page.evaluate("window.__ianitorShotsOld = true").catch(() => {});
+ await page.send("Page.navigate", { url });
+ await until(`${url} to load`, () => page.evaluate("!window.__ianitorShotsOld && document.readyState === 'complete'"));
+ for (const sel of shot.click ?? []) {
+ const q = JSON.stringify(sel);
+ await until(`${sel} to click`, () => page.evaluate(`(() => { const e = document.querySelector(${q}); if (!e) return false; e.click(); return true; })()`));
+ }
+ const w = JSON.stringify(shot.wait);
+ await until(shot.wait, () => page.evaluate(`!!document.querySelector(${w})`));
+ await page.evaluate("document.fonts.ready.then(() => new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(() => r(true)))))");
+ await sleep(400);
+ } catch (e) {
+ try {
+ const failed = await page.send("Page.captureScreenshot", { format: "png" });
+ writeFileSync(join(out, `aula-${shot.name}-failed.png`), Buffer.from(failed.data, "base64"));
+ } catch {
+ /* nothing to save */
+ }
+ throw new Error(`shot ${shot.name}: ${e.message}; the page was ${url}; what it showed is aula-${shot.name}-failed.png`);
+ }
+ const png = Buffer.from((await page.send("Page.captureScreenshot", { format: "png" })).data, "base64");
+ const { width, height } = pngSize(png);
+ const file = `aula-${shot.name}.png`;
+ writeFileSync(join(out, file), png);
+ taken.push({ name: shot.name, title: shot.title, file, width, height, sha256: createHash("sha256").update(png).digest("hex") });
+ log(`${file} ${width}x${height}`);
+ }
+ writeFileSync(join(out, "aula.json"), `${JSON.stringify({ v: 1, shots: taken })}\n`);
+ log(`${taken.length} shots and aula.json in ${out}`);
+}
+
+let code = 0;
+try {
+ await main();
+} catch (e) {
+ console.error(`shots: ${e?.message ?? e}`);
+ code = 1;
+} finally {
+ await cleanup();
+}
+process.exit(code);