architecture-harness 0.22.0 → 0.23.0
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/package.json +9 -2
- package/src/cli/cli.test.mjs +6 -1
- package/src/cli/codex-implement.mjs +7 -2
- package/src/cli/codex-implement.test.mjs +29 -0
- package/src/cli/dispatch-reminder.mjs +4 -1
- package/src/cli/dispatch-reminder.test.mjs +5 -1
- package/src/cli/git-hooks.test.mjs +5 -0
- package/src/cli/qc.mjs +14 -1
- package/src/cli/screens-discovery.mjs +60 -0
- package/src/cli/screens.mjs +84 -0
- package/src/cli/stack.mjs +14 -0
- package/src/screens/auth-context.test.mjs +41 -0
- package/src/screens/auth-run.test.mjs +144 -0
- package/src/screens/auth.mjs +223 -0
- package/src/screens/auth.test.mjs +76 -0
- package/src/screens/capture-idle.test.mjs +26 -0
- package/src/screens/capture.browser-test.mjs +73 -0
- package/src/screens/capture.mjs +175 -0
- package/src/screens/capture.test.mjs +28 -0
- package/src/screens/catalog.browser-test.mjs +32 -0
- package/src/screens/catalog.mjs +72 -0
- package/src/screens/catalog.test.mjs +36 -0
- package/src/screens/compare.mjs +40 -0
- package/src/screens/compare.test.mjs +30 -0
- package/src/screens/discovery.browser-test.mjs +29 -0
- package/src/screens/discovery.mjs +158 -0
- package/src/screens/discovery.test.mjs +27 -0
- package/src/screens/inventory.mjs +69 -0
- package/src/screens/inventory.test.mjs +10 -0
- package/src/screens/map.mjs +63 -0
- package/src/screens/map.test.mjs +35 -0
- package/src/screens/open.browser-test.mjs +50 -0
- package/src/screens/regions.mjs +137 -0
- package/src/screens/regions.test.mjs +38 -0
- package/src/screens/session-files.mjs +39 -0
- package/src/screens/session-files.test.mjs +39 -0
- package/src/screens/setup.browser-test.mjs +49 -0
- package/src/screens/setup.mjs +78 -0
- package/src/screens/stack-auth.browser-test.mjs +30 -0
- package/src/screens/stack-auth.mjs +106 -0
- package/src/screens/stack-auth.test.mjs +65 -0
- package/src/screens/write-guard.mjs +26 -0
- package/src/stack/stack.mjs +131 -0
- package/src/stack/stack.test.mjs +40 -0
- package/src/stack/supervisor.mjs +30 -0
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
import { cpSync, existsSync, mkdirSync, readFileSync, realpathSync, rmSync } from "node:fs";
|
|
2
|
+
import os from "node:os";
|
|
3
|
+
import { atomicJson, withFileLock } from "./session-files.mjs";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { requireLocalhost } from "./map.mjs";
|
|
6
|
+
import { installWriteGuard } from "./write-guard.mjs";
|
|
7
|
+
|
|
8
|
+
/** Branch: a failed session advances to the next method. */
|
|
9
|
+
export async function firstSignedIn(methods) {
|
|
10
|
+
for (const method of methods) {
|
|
11
|
+
const session = await method();
|
|
12
|
+
if (session) return session;
|
|
13
|
+
}
|
|
14
|
+
throw new Error("No signed-in page reached; complete sign-in in the headed Chrome window and rerun");
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** Resource: authentication files stay outside every repository. */
|
|
18
|
+
export function privateRoot() {
|
|
19
|
+
const root = path.join(os.homedir(), ".qc", "screens");
|
|
20
|
+
mkdirSync(root, { recursive: true, mode: 0o700 });
|
|
21
|
+
for (let current = realpathSync(root); ; current = path.dirname(current)) {
|
|
22
|
+
if (existsSync(path.join(current, ".git"))) throw new Error("The screens state directory must stay outside every repository");
|
|
23
|
+
if (current === path.dirname(current)) break;
|
|
24
|
+
}
|
|
25
|
+
return root;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Resource: copy session files without opening the password store. */
|
|
29
|
+
export function copyChromeProfile(root, source) {
|
|
30
|
+
const chrome = source ?? (process.platform === "win32" ? path.join(process.env.LOCALAPPDATA, "Google", "Chrome", "User Data") : process.platform === "darwin" ? path.join(os.homedir(), "Library", "Application Support", "Google", "Chrome") : path.join(os.homedir(), ".config", "google-chrome"));
|
|
31
|
+
const localState = path.join(chrome, "Local State");
|
|
32
|
+
const profileName = JSON.parse(readFileSync(localState, "utf8")).profile?.last_used ?? "Default";
|
|
33
|
+
if (!/^(Default|Profile \d+)$/.test(profileName)) throw new Error("Chrome profile name is unsupported");
|
|
34
|
+
const destination = path.join(root, "profile");
|
|
35
|
+
mkdirSync(destination, { recursive: true, mode: 0o700 });
|
|
36
|
+
cpSync(localState, path.join(destination, "Local State"));
|
|
37
|
+
const output = path.join(destination, profileName);
|
|
38
|
+
mkdirSync(output, { recursive: true, mode: 0o700 });
|
|
39
|
+
for (const name of ["Cookies", "Cookies-journal", "Network/Cookies", "Network/Cookies-journal", "Local Storage", "IndexedDB", "Preferences", "Secure Preferences"]) {
|
|
40
|
+
const file = path.join(chrome, profileName, name);
|
|
41
|
+
if (existsSync(file)) cpSync(file, path.join(output, name), { recursive: true });
|
|
42
|
+
}
|
|
43
|
+
return { directory: destination, profileName };
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
async function reachesSignedIn(context, target, timeout) {
|
|
47
|
+
const page = await context.newPage();
|
|
48
|
+
await page.goto(new URL(target.auth.path ?? "/projects", target.baseUrl).href, { waitUntil: "domcontentloaded", timeout });
|
|
49
|
+
await page.locator(target.auth.signedIn).first().waitFor({ state: "visible", timeout });
|
|
50
|
+
if (new URL(page.url()).origin !== new URL(target.baseUrl).origin) throw new Error("Sign-in finished on another origin");
|
|
51
|
+
return { context, page };
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
async function saveState(context, file, target) {
|
|
55
|
+
// A parent-domain cookie, such as .auth0.com, reaches every tenant on that domain, so only exact hosts are kept.
|
|
56
|
+
const hosts = [new URL(target.baseUrl).hostname, target.auth.domain].filter(Boolean).map(host => host.toLowerCase());
|
|
57
|
+
const origins = [new URL(target.baseUrl).origin, ...(target.auth.domain ? [`https://${target.auth.domain.toLowerCase()}`] : [])];
|
|
58
|
+
const state = await context.storageState();
|
|
59
|
+
state.cookies = state.cookies.filter(cookie => hosts.includes(cookie.domain.replace(/^\./, "").toLowerCase()));
|
|
60
|
+
state.origins = state.origins.filter(origin => origins.includes(new URL(origin.origin).origin));
|
|
61
|
+
await atomicJson(file, state);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Record: interactive sign-in is a terminal result for unattended commands. */
|
|
65
|
+
export class PersonSignInRequired extends Error {
|
|
66
|
+
constructor(targetName) {
|
|
67
|
+
super(`${targetName}: needs a person to sign in (run qc screens auth ${targetName} --headed)`);
|
|
68
|
+
this.exitCode = 4;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Pipeline: reuse saved cookies and refresh through the real login page without typing. */
|
|
73
|
+
export async function browserSession(chromium, target, options = {}) {
|
|
74
|
+
const { targetName = target.name ?? target.baseUrl } = options;
|
|
75
|
+
try {
|
|
76
|
+
const file = path.join(privateRoot(), "state", `${target.auth.domain}.json`);
|
|
77
|
+
return await withFileLock(file, () => lockedBrowserSession(chromium, target, file, { ...options, targetName }));
|
|
78
|
+
} catch (error) {
|
|
79
|
+
if (error instanceof PersonSignInRequired || error.authFailure) throw error;
|
|
80
|
+
throw authFailure(targetName, "browser-session", "the session files");
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function authFailure(targetName, method, stage) {
|
|
85
|
+
const error = new Error(`${targetName}: ${method} sign-in failed at ${stage}`);
|
|
86
|
+
error.authFailure = true;
|
|
87
|
+
return error;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
async function lockedBrowserSession(chromium, target, file, { timeout = 15000, signInTimeout = 180000, say = console.error, chromeProfile, allowInteractive = false, headed = false, allowWrites = false, targetName }) {
|
|
91
|
+
const launch = async method => {
|
|
92
|
+
let context, browser, profileRoot;
|
|
93
|
+
let stage = "the copied Chrome profile";
|
|
94
|
+
const close = async () => {
|
|
95
|
+
try { if (context) await context.close(); }
|
|
96
|
+
finally {
|
|
97
|
+
try { if (browser) await browser.close(); }
|
|
98
|
+
finally { if (profileRoot) rmSync(profileRoot, { recursive: true, force: true }); }
|
|
99
|
+
}
|
|
100
|
+
};
|
|
101
|
+
try {
|
|
102
|
+
if (method === "profile") {
|
|
103
|
+
profileRoot = path.join(privateRoot(), `profile-${process.pid}-${Date.now()}`);
|
|
104
|
+
const profile = copyChromeProfile(profileRoot, chromeProfile);
|
|
105
|
+
stage = "the browser";
|
|
106
|
+
context = await chromium.launchPersistentContext(profile.directory, { channel: "chrome", headless: !headed, deviceScaleFactor: 1, reducedMotion: "reduce", serviceWorkers: "block", args: [`--profile-directory=${profile.profileName}`] });
|
|
107
|
+
} else {
|
|
108
|
+
if (method === "state" && !existsSync(file)) return null;
|
|
109
|
+
stage = "the browser";
|
|
110
|
+
browser = await chromium.launch({ channel: "chrome", headless: !headed && method !== "headed" });
|
|
111
|
+
stage = "the session file";
|
|
112
|
+
const storageState = method === "state" ? JSON.parse(readFileSync(file, "utf8")) : undefined;
|
|
113
|
+
stage = "the browser";
|
|
114
|
+
context = await browser.newContext({ deviceScaleFactor: 1, reducedMotion: "reduce", serviceWorkers: "block", ...(storageState ? { storageState } : {}) });
|
|
115
|
+
}
|
|
116
|
+
await installWriteGuard(context, target, { allowWrites });
|
|
117
|
+
if (method === "headed") say(`${targetName}: sign in once in the Chrome window.`);
|
|
118
|
+
stage = "the login page";
|
|
119
|
+
let session;
|
|
120
|
+
if (method === "state") {
|
|
121
|
+
try {
|
|
122
|
+
session = await reachesSignedIn(context, { ...target, auth: { ...target.auth, path: target.auth.checkPath ?? "/projects" } }, timeout);
|
|
123
|
+
} catch {
|
|
124
|
+
for (const page of context.pages()) await page.close();
|
|
125
|
+
const loginPath = target.auth.loginPath ?? (target.auth.path && target.auth.path !== "/projects" ? target.auth.path : "/bff/login?returnTo=%2Fprojects");
|
|
126
|
+
session = await reachesSignedIn(context, { ...target, auth: { ...target.auth, path: loginPath } }, timeout);
|
|
127
|
+
}
|
|
128
|
+
} else session = await reachesSignedIn(context, target, method === "headed" ? signInTimeout : timeout);
|
|
129
|
+
stage = "the session file";
|
|
130
|
+
await saveState(context, file, target);
|
|
131
|
+
return { ...session, close };
|
|
132
|
+
} catch {
|
|
133
|
+
await close().catch(() => {});
|
|
134
|
+
if (stage === "the browser" || stage === "the session file") throw authFailure(targetName, "browser-session", stage);
|
|
135
|
+
if (allowInteractive) say(`${targetName}: browser-session sign-in failed at the ${method === "state" ? "saved session and silent refresh" : method === "profile" ? "copied Chrome profile" : "headed login page"}.`);
|
|
136
|
+
return null;
|
|
137
|
+
}
|
|
138
|
+
};
|
|
139
|
+
const methods = allowInteractive ? ["state", "profile", "headed"] : ["state"];
|
|
140
|
+
for (const method of methods) {
|
|
141
|
+
const session = await launch(method);
|
|
142
|
+
if (session) return session;
|
|
143
|
+
}
|
|
144
|
+
throw new PersonSignInRequired(targetName);
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/** Resource: read only named fields, without evaluating seed code. */
|
|
148
|
+
export function seedFields(auth) {
|
|
149
|
+
try {
|
|
150
|
+
const source = readFileSync(auth.seedFile, "utf8");
|
|
151
|
+
let json;
|
|
152
|
+
try { json = JSON.parse(source); } catch { json = null; }
|
|
153
|
+
const field = name => {
|
|
154
|
+
if (json) return name.split(".").reduce((value, key) => value?.[key], json);
|
|
155
|
+
if (!/^[A-Za-z_$][\w$]*$/.test(name)) throw new Error("Invalid seed field");
|
|
156
|
+
const match = source.match(new RegExp(`(?:\\b${name}\\s*[:=]\\s*)(["'\x60])([^"'\x60\\r\\n]+)\\1`));
|
|
157
|
+
return match?.[2];
|
|
158
|
+
};
|
|
159
|
+
const user = field(auth.userField);
|
|
160
|
+
const password = field(auth.passwordField);
|
|
161
|
+
if (typeof user !== "string" || typeof password !== "string" || !user || !password) throw new Error("Missing seed fields");
|
|
162
|
+
return { user, password };
|
|
163
|
+
} catch {
|
|
164
|
+
throw new Error("Cannot read the named seed fields");
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** Pipeline: fill credentials only while every request stays on loopback. */
|
|
169
|
+
export async function seedSession(chromium, target, options = {}) {
|
|
170
|
+
const { targetName = target.name ?? target.baseUrl } = options;
|
|
171
|
+
const method = target.auth.mode === "form" ? "form" : "seed";
|
|
172
|
+
try {
|
|
173
|
+
requireLocalhost(target.baseUrl);
|
|
174
|
+
const file = path.join(privateRoot(), `local-${new URL(target.baseUrl).port || "80"}.json`);
|
|
175
|
+
return await withFileLock(file, () => lockedSeedSession(chromium, target, file, { ...options, targetName, method }));
|
|
176
|
+
} catch (error) {
|
|
177
|
+
if (error.authFailure) throw error;
|
|
178
|
+
throw authFailure(targetName, method, "the localhost guard or session files");
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
async function lockedSeedSession(chromium, target, file, { timeout = 15000, credentials, savedOnly = false, headed = false, targetName, method }) {
|
|
183
|
+
let browser;
|
|
184
|
+
let stage = "the saved session";
|
|
185
|
+
try {
|
|
186
|
+
if (savedOnly && !existsSync(file)) throw new Error("No saved local session");
|
|
187
|
+
stage = "the browser";
|
|
188
|
+
browser = await chromium.launch({ channel: "chrome", headless: !headed });
|
|
189
|
+
const context = await browser.newContext({ deviceScaleFactor: 1, reducedMotion: "reduce", serviceWorkers: "block", ...(existsSync(file) ? { storageState: JSON.parse(readFileSync(file, "utf8")) } : {}) });
|
|
190
|
+
await context.route("**/*", async route => {
|
|
191
|
+
try { requireLocalhost(route.request().url()); } catch { await route.abort(); return; }
|
|
192
|
+
await route.continue();
|
|
193
|
+
});
|
|
194
|
+
if (savedOnly) {
|
|
195
|
+
stage = "the saved session";
|
|
196
|
+
const session = await reachesSignedIn(context, { ...target, auth: { ...target.auth, path: target.auth.checkPath ?? "/projects" } }, timeout);
|
|
197
|
+
await saveState(context, file, target);
|
|
198
|
+
return { ...session, close: () => browser.close() };
|
|
199
|
+
}
|
|
200
|
+
stage = "the login page";
|
|
201
|
+
const page = await context.newPage();
|
|
202
|
+
await page.goto(new URL(target.auth.path ?? "/login", target.baseUrl).href, { waitUntil: "domcontentloaded", timeout });
|
|
203
|
+
requireLocalhost(page.url());
|
|
204
|
+
stage = "the credential fields";
|
|
205
|
+
const { user, password } = credentials ?? seedFields(target.auth);
|
|
206
|
+
stage = "the username field";
|
|
207
|
+
await page.locator(target.auth.userSelector).fill(user, { timeout });
|
|
208
|
+
requireLocalhost(page.url());
|
|
209
|
+
stage = "the password field";
|
|
210
|
+
await page.locator(target.auth.passwordSelector).fill(password, { timeout });
|
|
211
|
+
requireLocalhost(page.url());
|
|
212
|
+
stage = "the submit control";
|
|
213
|
+
await page.locator(target.auth.submitSelector).click({ timeout });
|
|
214
|
+
stage = "the signed-in page";
|
|
215
|
+
await page.locator(target.auth.signedIn).first().waitFor({ state: "visible", timeout });
|
|
216
|
+
stage = "the session file";
|
|
217
|
+
await saveState(context, file, target);
|
|
218
|
+
return { context, page, close: () => browser.close() };
|
|
219
|
+
} catch {
|
|
220
|
+
if (browser) await browser.close().catch(() => {});
|
|
221
|
+
throw authFailure(targetName, method, stage);
|
|
222
|
+
}
|
|
223
|
+
}
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import test from "node:test";
|
|
2
|
+
import assert from "node:assert/strict";
|
|
3
|
+
import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, existsSync, rmSync } from "node:fs";
|
|
4
|
+
import os from "node:os";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
import { firstSignedIn, seedFields, copyChromeProfile, browserSession } from "./auth.mjs";
|
|
7
|
+
|
|
8
|
+
test("profile sign-in saves only target and authentication hosts", async t => {
|
|
9
|
+
const root = mkdtempSync(path.join(os.tmpdir(), "qc-auth-filter-"));
|
|
10
|
+
t.after(() => rmSync(root, { recursive: true, force: true }));
|
|
11
|
+
t.mock.method(os, "homedir", () => root);
|
|
12
|
+
const source = path.join(root, "chrome");
|
|
13
|
+
mkdirSync(source);
|
|
14
|
+
writeFileSync(path.join(source, "Local State"), JSON.stringify({ profile: { last_used: "Default" } }));
|
|
15
|
+
const target = { baseUrl: "https://app.example.test", auth: { domain: "tenant.auth0.test", signedIn: "main" } };
|
|
16
|
+
const context = {
|
|
17
|
+
route: async () => {}, close: async () => {},
|
|
18
|
+
newPage: async () => ({ goto: async () => {}, url: () => target.baseUrl, locator: () => ({ first: () => ({ waitFor: async () => {} }) }) }),
|
|
19
|
+
storageState: async () => ({
|
|
20
|
+
cookies: ["app.example.test", ".example.test", ".tenant.auth0.test", ".auth0.test", "foreign.test", "evilapp.example.test", "example.test.evil"].map(domain => ({ name: "session", domain, path: "/" })),
|
|
21
|
+
origins: [target.baseUrl, "https://tenant.auth0.test", "https://app.example.test:8443", "http://app.example.test", "https://foreign.test", "https://evilapp.example.test"].map(origin => ({ origin, localStorage: [] })),
|
|
22
|
+
}),
|
|
23
|
+
};
|
|
24
|
+
const session = await browserSession({ launchPersistentContext: async () => context }, target, { chromeProfile: source, allowInteractive: true, say: () => {} });
|
|
25
|
+
t.after(() => session.close());
|
|
26
|
+
const saved = JSON.parse(readFileSync(path.join(root, ".qc", "screens", "state", "tenant.auth0.test.json"), "utf8"));
|
|
27
|
+
assert.deepEqual(saved.cookies.map(cookie => cookie.domain), ["app.example.test", ".tenant.auth0.test"]);
|
|
28
|
+
assert.deepEqual(saved.origins.map(origin => origin.origin), [target.baseUrl, "https://tenant.auth0.test"]);
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
test("auth falls back in order and stops at the first signed-in context", async () => {
|
|
32
|
+
const calls = [];
|
|
33
|
+
const session = { signedIn: true };
|
|
34
|
+
const result = await firstSignedIn([
|
|
35
|
+
async () => { calls.push("state"); return null; },
|
|
36
|
+
async () => { calls.push("profile"); return session; },
|
|
37
|
+
async () => { calls.push("headed"); throw new Error("must not run"); },
|
|
38
|
+
]);
|
|
39
|
+
assert.equal(result, session);
|
|
40
|
+
assert.deepEqual(calls, ["state", "profile"]);
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
test("auth reaches headed fallback after both reusable sessions fail", async () => {
|
|
44
|
+
const calls = [];
|
|
45
|
+
const session = {};
|
|
46
|
+
assert.equal(await firstSignedIn([async () => { calls.push(1); return null; }, async () => { calls.push(2); return null; }, async () => { calls.push(3); return session; }]), session);
|
|
47
|
+
assert.deepEqual(calls, [1, 2, 3]);
|
|
48
|
+
await assert.rejects(firstSignedIn([async () => null]), /signed-in/);
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
test("profile copy includes cookies and excludes Chrome's password store", () => {
|
|
52
|
+
const root = mkdtempSync(path.join(os.tmpdir(), "qc-screen-profile-"));
|
|
53
|
+
try {
|
|
54
|
+
const source = path.join(root, "source");
|
|
55
|
+
mkdirSync(path.join(source, "Default", "Network"), { recursive: true });
|
|
56
|
+
writeFileSync(path.join(source, "Local State"), JSON.stringify({ profile: { last_used: "Default" } }));
|
|
57
|
+
writeFileSync(path.join(source, "Default", "Network", "Cookies"), "encrypted cookie fixture");
|
|
58
|
+
writeFileSync(path.join(source, "Default", "Login Data"), "password store fixture");
|
|
59
|
+
const copy = copyChromeProfile(root, source);
|
|
60
|
+
assert.equal(existsSync(path.join(copy.directory, "Default", "Network", "Cookies")), true);
|
|
61
|
+
assert.equal(existsSync(path.join(copy.directory, "Default", "Login Data")), false);
|
|
62
|
+
} finally { rmSync(root, { recursive: true, force: true }); }
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
test("seed fields support JSON paths and literal source fields without evaluating code", () => {
|
|
66
|
+
const root = mkdtempSync(path.join(os.tmpdir(), "qc-screen-seed-"));
|
|
67
|
+
try {
|
|
68
|
+
const seedFile = path.join(root, "seed.json");
|
|
69
|
+
writeFileSync(seedFile, JSON.stringify({ account: { name: "a", pass: "b" } }));
|
|
70
|
+
assert.deepEqual(seedFields({ seedFile, userField: "account.name", passwordField: "account.pass" }), { user: "a", password: "b" });
|
|
71
|
+
writeFileSync(seedFile, 'const account = { username: "a", password: "b" }; throw new Error("must not evaluate");');
|
|
72
|
+
assert.deepEqual(seedFields({ seedFile, userField: "username", passwordField: "password" }), { user: "a", password: "b" });
|
|
73
|
+
writeFileSync(seedFile, 'const password = getSecret();');
|
|
74
|
+
assert.throws(() => seedFields({ seedFile, userField: "username", passwordField: "password" }), /^Error: Cannot read the named seed fields$/);
|
|
75
|
+
} finally { rmSync(root, { recursive: true, force: true }); }
|
|
76
|
+
});
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import test from "node:test";
|
|
2
|
+
import assert from "node:assert/strict";
|
|
3
|
+
import http from "node:http";
|
|
4
|
+
import { mkdtempSync, existsSync, rmSync } from "node:fs";
|
|
5
|
+
import os from "node:os";
|
|
6
|
+
import path from "node:path";
|
|
7
|
+
import { chromium } from "playwright";
|
|
8
|
+
import { capturePage } from "./capture.mjs";
|
|
9
|
+
|
|
10
|
+
test("an entry with idle false captures a page that polls forever", async t => {
|
|
11
|
+
const root = mkdtempSync(path.join(os.tmpdir(), "qc-capture-idle-"));
|
|
12
|
+
const server = http.createServer((req, res) => {
|
|
13
|
+
if (req.url === "/poll") return res.end("ok");
|
|
14
|
+
res.setHeader("content-type", "text/html");
|
|
15
|
+
res.end('<main id="ready">Pins</main><script>setInterval(() => fetch("/poll"), 100)</script>');
|
|
16
|
+
});
|
|
17
|
+
await new Promise(resolve => server.listen(0, "127.0.0.1", resolve));
|
|
18
|
+
t.after(async () => { server.closeAllConnections(); await new Promise(resolve => server.close(resolve)); rmSync(root, { recursive: true, force: true }); });
|
|
19
|
+
const browser = await chromium.launch({ channel: "chrome" });
|
|
20
|
+
t.after(() => browser.close());
|
|
21
|
+
const page = await browser.newPage();
|
|
22
|
+
const target = { baseUrl: `http://127.0.0.1:${server.address().port}`, auth: { signedIn: "#ready" } };
|
|
23
|
+
await assert.rejects(capturePage({ page }, target, { path: "/", ready: "#ready" }, 200, 200, path.join(root, "busy.png"), 1500), /networkidle|Timeout/);
|
|
24
|
+
await capturePage({ page }, target, { path: "/", ready: "#ready", idle: false }, 200, 200, path.join(root, "polling.png"), 1500);
|
|
25
|
+
assert.ok(existsSync(path.join(root, "polling.png")));
|
|
26
|
+
});
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import test from "node:test";
|
|
2
|
+
import assert from "node:assert/strict";
|
|
3
|
+
import { mkdtempSync, readFileSync, rmSync } from "node:fs";
|
|
4
|
+
import os from "node:os";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
import { setTimeout } from "node:timers/promises";
|
|
7
|
+
import { chromium } from "playwright";
|
|
8
|
+
import { PNG } from "pngjs";
|
|
9
|
+
import { capturePage } from "./capture.mjs";
|
|
10
|
+
import { findRegions } from "./regions.mjs";
|
|
11
|
+
import { collectInventory, diffInventory } from "./inventory.mjs";
|
|
12
|
+
|
|
13
|
+
test("accessibility inventory excludes table data and masked controls", async () => {
|
|
14
|
+
const browser = await chromium.launch({ channel: "chrome", headless: true });
|
|
15
|
+
try {
|
|
16
|
+
const page = await browser.newPage();
|
|
17
|
+
const content = value => `<label>Email<input placeholder="Your email"></label><button aria-label="Next">Go</button><table><tr><th>Title</th></tr><tr><td>${value}</td></tr></table><section id="masked"><button>Hidden</button></section>`;
|
|
18
|
+
await page.setContent(content("First row"));
|
|
19
|
+
const first = await collectInventory(page, ["#masked"]);
|
|
20
|
+
await page.setContent(content("Other data"));
|
|
21
|
+
const second = await collectInventory(page, ["#masked"]);
|
|
22
|
+
assert.deepEqual(first.map(item => item.role), ["textbox", "button", "columnheader"]);
|
|
23
|
+
assert.equal(first[0].name, "Email");
|
|
24
|
+
assert.equal(first[0].placeholder, "Your email");
|
|
25
|
+
assert.deepEqual(diffInventory(first, second), []);
|
|
26
|
+
} finally { await browser.close(); }
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
test("different text in the same box produces identical layout images", async () => {
|
|
30
|
+
const directory = mkdtempSync(path.join(os.tmpdir(), "qc-screens-layout-"));
|
|
31
|
+
const browser = await chromium.launch({ channel: "chrome", headless: true });
|
|
32
|
+
try {
|
|
33
|
+
const context = await browser.newContext({ deviceScaleFactor: 1, serviceWorkers: "block" });
|
|
34
|
+
let text = "First";
|
|
35
|
+
await context.route("https://screens.example/**", route => route.fulfill({ contentType: "text/html", body: `<main id="ready"><button style="width:100px;height:40px">${text}</button></main>` }));
|
|
36
|
+
const page = await context.newPage();
|
|
37
|
+
const target = { baseUrl: "https://screens.example", auth: { signedIn: "#ready" } };
|
|
38
|
+
await capturePage({ page }, target, { path: "/", ready: "#ready" }, 200, 100, path.join(directory, "a.png"), 5000);
|
|
39
|
+
text = "Other text";
|
|
40
|
+
await capturePage({ page }, target, { path: "/", ready: "#ready" }, 200, 100, path.join(directory, "b.png"), 5000);
|
|
41
|
+
const images = ["a", "b"].map(name => PNG.sync.read(readFileSync(path.join(directory, `${name}.layout.png`))));
|
|
42
|
+
assert.deepEqual(findRegions(...images), []);
|
|
43
|
+
} finally {
|
|
44
|
+
await browser.close();
|
|
45
|
+
rmSync(directory, { recursive: true, force: true });
|
|
46
|
+
}
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
test("capture includes a thumbnail whose response follows the ready selector", async () => {
|
|
50
|
+
const directory = mkdtempSync(path.join(os.tmpdir(), "qc-screens-image-"));
|
|
51
|
+
const browser = await chromium.launch({ channel: "chrome", headless: true });
|
|
52
|
+
try {
|
|
53
|
+
const context = await browser.newContext({ serviceWorkers: "block" });
|
|
54
|
+
const image = new PNG({ width: 20, height: 20 });
|
|
55
|
+
for (let offset = 0; offset < image.data.length; offset += 4) image.data.set([255, 0, 0, 255], offset);
|
|
56
|
+
await context.route("https://screens.example/**", async route => {
|
|
57
|
+
if (route.request().url().endsWith("/photo.png")) {
|
|
58
|
+
await setTimeout(800);
|
|
59
|
+
await route.fulfill({ contentType: "image/png", body: PNG.sync.write(image) });
|
|
60
|
+
} else {
|
|
61
|
+
await route.fulfill({ contentType: "text/html", body: '<body style="margin:0"><main id="ready"><img src="/photo.png" width="20" height="20"></main></body>' });
|
|
62
|
+
}
|
|
63
|
+
});
|
|
64
|
+
const page = await context.newPage();
|
|
65
|
+
const file = path.join(directory, "capture.png");
|
|
66
|
+
await capturePage({ page }, { baseUrl: "https://screens.example", auth: { signedIn: "#ready" } }, { path: "/", ready: "#ready" }, 100, 100, file, 5000);
|
|
67
|
+
const capture = PNG.sync.read(readFileSync(file));
|
|
68
|
+
assert.deepEqual([...capture.data.subarray(0, 4)], [255, 0, 0, 255]);
|
|
69
|
+
} finally {
|
|
70
|
+
await browser.close();
|
|
71
|
+
rmSync(directory, { recursive: true, force: true });
|
|
72
|
+
}
|
|
73
|
+
});
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { PNG } from "pngjs";
|
|
5
|
+
import { targetSession } from "./stack-auth.mjs";
|
|
6
|
+
import { compareImages, gallery, sortReport } from "./compare.mjs";
|
|
7
|
+
import { stableCapture, findRegions, regionCrop, boxPair } from "./regions.mjs";
|
|
8
|
+
import { collectInventory, diffInventory, inventoryBox } from "./inventory.mjs";
|
|
9
|
+
import { openScreen } from "./catalog.mjs";
|
|
10
|
+
import { safeControl, installWriteGuard } from "./write-guard.mjs";
|
|
11
|
+
|
|
12
|
+
/** Branch: a typo must never silently skip a requested screen. */
|
|
13
|
+
export function selectScreens(screens, only) {
|
|
14
|
+
if (!only) return screens;
|
|
15
|
+
const names = only.split(",").map(name => name.trim());
|
|
16
|
+
for (const name of names) if (!screens.some(screen => screen.name === name)) throw new Error(`Unknown screen ${name}`);
|
|
17
|
+
return screens.filter(screen => names.includes(screen.name));
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** Record: bind a cached image to its viewport, target, navigation, and masks. */
|
|
21
|
+
export function captureKey(target, route, width, height) {
|
|
22
|
+
return createHash("sha256").update(JSON.stringify({ baseUrl: target.baseUrl, route, width, height })).digest("hex");
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Ledger: a filtered rerun preserves rows for the same pair. */
|
|
26
|
+
export function mergeReport(previous, fresh) {
|
|
27
|
+
const keys = new Set(fresh.map(row => `${row.screen}@${row.width}`));
|
|
28
|
+
const targets = JSON.stringify(fresh[0]?.targets);
|
|
29
|
+
return sortReport([...previous.filter(row => JSON.stringify(row.targets) === targets && !keys.has(`${row.screen}@${row.width}`)), ...fresh]);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Branch: capture navigation excludes mutation controls. */
|
|
33
|
+
export function safeClick(control) {
|
|
34
|
+
return safeControl(control);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function readJson(file, fallback) {
|
|
38
|
+
return existsSync(file) ? JSON.parse(readFileSync(file, "utf8")) : fallback;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function writeJson(file, value) {
|
|
42
|
+
writeFileSync(`${file}.tmp`, `${JSON.stringify(value, null, 2)}\n`);
|
|
43
|
+
renameSync(`${file}.tmp`, file);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Pipeline: wait for page resources before recording the viewport. */
|
|
47
|
+
export async function capturePage(session, target, route, width, height, file, timeout, navigation = {}) {
|
|
48
|
+
const { page } = session;
|
|
49
|
+
await page.setViewportSize({ width, height });
|
|
50
|
+
if (route.open) await openScreen(page, target, route, { ...navigation, timeout });
|
|
51
|
+
const expected = new URL(route.path ?? page.url(), target.baseUrl);
|
|
52
|
+
const response = route.open ? null : await page.goto(expected.href, { waitUntil: "domcontentloaded", timeout });
|
|
53
|
+
if (response && response.status() >= 400) throw new Error(`Capture received HTTP ${response.status()}`);
|
|
54
|
+
await page.emulateMedia({ reducedMotion: "reduce" });
|
|
55
|
+
await page.addStyleTag({ content: "*,*::before,*::after{animation:none!important;transition:none!important;caret-color:transparent!important}" });
|
|
56
|
+
// A full-screen viewer has no header, so an entry's own ready selector replaces the signed-in check.
|
|
57
|
+
if (!route.ready) await page.locator(target.auth.signedIn).first().waitFor({ state: "visible", timeout });
|
|
58
|
+
for (const step of route.clicks ?? []) {
|
|
59
|
+
const selector = typeof step === "string" ? step : step.selector;
|
|
60
|
+
const control = page.locator(selector).first();
|
|
61
|
+
if (step.optional) {
|
|
62
|
+
try { await control.waitFor({ state: "visible", timeout: Math.min(timeout, 1500) }); }
|
|
63
|
+
catch (error) { if (error.name === "TimeoutError") continue; throw error; }
|
|
64
|
+
}
|
|
65
|
+
const description = await control.evaluate(element => ({ type: element.getAttribute("type") ?? (element.tagName === "BUTTON" && element.closest("form") ? "submit" : ""), text: `${element.textContent} ${element.getAttribute("aria-label") ?? ""}` }));
|
|
66
|
+
if (!safeClick(description)) throw new Error("Capture navigation refuses a mutation control");
|
|
67
|
+
await control.click({ timeout });
|
|
68
|
+
}
|
|
69
|
+
if (route.ready) await page.locator(route.ready).first().waitFor({ state: "visible", timeout });
|
|
70
|
+
const actual = new URL(page.url());
|
|
71
|
+
if (actual.origin !== expected.origin || actual.pathname !== expected.pathname || actual.search !== expected.search) throw new Error("Capture reached a URL other than the mapped screen");
|
|
72
|
+
if (await page.locator('input[type="password"]:visible, [role="alert"][data-error]:visible').count()) throw new Error("Capture reached a sign-in or error page");
|
|
73
|
+
await page.mouse.move(0, 0);
|
|
74
|
+
// A page that polls never goes idle, so its entry sets `idle: false` and relies on `ready`.
|
|
75
|
+
if (route.idle !== false) await page.waitForLoadState("networkidle", { timeout });
|
|
76
|
+
await page.evaluate(() => document.fonts.ready);
|
|
77
|
+
const inventory = await collectInventory(page, [...(route.masks ?? []), ...(route.exclude ?? [])]);
|
|
78
|
+
writeJson(file.replace(/\.png$/, ".inventory.json"), inventory);
|
|
79
|
+
const capture = () => page.screenshot({ animations: "disabled", caret: "hide", fullPage: false, mask: (route.masks ?? []).map(selector => page.locator(selector)), maskColor: "#808080", timeout }).then(buffer => PNG.sync.read(buffer));
|
|
80
|
+
const full = await stableCapture(capture);
|
|
81
|
+
writeFileSync(file, PNG.sync.write(full.image));
|
|
82
|
+
const style = await page.addStyleTag({ content: "*,*::before,*::after{color:transparent!important;text-shadow:none!important;-webkit-text-fill-color:transparent!important}img,canvas,video,svg{visibility:hidden!important}*:has(>img),*:has(>canvas),*:has(>video),*:has(>svg){background:#808080!important}input,textarea{color:transparent!important}" });
|
|
83
|
+
const layout = await stableCapture(capture);
|
|
84
|
+
await style.evaluate(element => element.remove());
|
|
85
|
+
writeFileSync(file.replace(/\.png$/, ".layout.png"), PNG.sync.write(layout.image));
|
|
86
|
+
const unstable = new PNG({ width, height });
|
|
87
|
+
for (const mask of [full.unstable, layout.unstable].filter(Boolean)) for (let i = 3; i < mask.data.length; i += 4) if (mask.data[i]) unstable.data.set([255, 0, 0, 255], i - 3);
|
|
88
|
+
writeFileSync(file.replace(/\.png$/, ".unstable.png"), PNG.sync.write(unstable));
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** Pipeline: authenticate, capture each viewport, compare, and publish the gallery. */
|
|
92
|
+
export async function captureScreens(map, options, { chromium, say = console.error, sessionFactory = targetSession } = {}) {
|
|
93
|
+
const { targets, out, only, changed, timeout = 15000, signInTimeout = 180000, height = 900, allowWrites = false } = options;
|
|
94
|
+
if (targets.length !== 2 || targets.some(name => !map.targets[name])) throw new Error("Choose two targets from the map");
|
|
95
|
+
if (changed && !targets.includes(changed)) throw new Error("--changed must name one of the two targets");
|
|
96
|
+
const screens = selectScreens(map.screens, only);
|
|
97
|
+
for (const screen of screens) for (const name of targets) if (!screen.targets[name]) throw new Error(`Screen ${screen.name} lacks target ${name}`);
|
|
98
|
+
mkdirSync(out, { recursive: true });
|
|
99
|
+
const cacheFile = path.join(out, "captures.json");
|
|
100
|
+
const cache = readJson(cacheFile, {});
|
|
101
|
+
const sessions = new Map();
|
|
102
|
+
const fresh = [];
|
|
103
|
+
const failures = new Map();
|
|
104
|
+
try {
|
|
105
|
+
for (const name of targets) {
|
|
106
|
+
const session = await sessionFactory(chromium, map.targets[name], { timeout, signInTimeout, say, targetName: name, allowInteractive: false, allowWrites });
|
|
107
|
+
sessions.set(name, session);
|
|
108
|
+
await installWriteGuard(session.context, map.targets[name], { allowWrites });
|
|
109
|
+
}
|
|
110
|
+
for (const name of targets) {
|
|
111
|
+
const target = map.targets[name];
|
|
112
|
+
if (changed && changed !== name) {
|
|
113
|
+
for (const screen of screens) for (const width of map.widths) {
|
|
114
|
+
const relative = `${screen.name}/${name}@${width}.png`;
|
|
115
|
+
if (![relative, relative.replace(/\.png$/, ".layout.png"), relative.replace(/\.png$/, ".unstable.png"), relative.replace(/\.png$/, ".inventory.json")].every(file => existsSync(path.join(out, file))) || cache[relative] !== captureKey(target, screen.targets[name], width, height)) throw new Error(`Cached capture missing or stale: ${relative}; run both targets first`);
|
|
116
|
+
}
|
|
117
|
+
continue;
|
|
118
|
+
}
|
|
119
|
+
const session = sessions.get(name);
|
|
120
|
+
for (const screen of screens) {
|
|
121
|
+
mkdirSync(path.join(out, screen.name), { recursive: true });
|
|
122
|
+
for (const width of map.widths) {
|
|
123
|
+
const relative = `${screen.name}/${name}@${width}.png`;
|
|
124
|
+
try {
|
|
125
|
+
await capturePage(session, target, screen.targets[name], width, height, path.join(out, relative), timeout, { targetName: name, screenName: screen.name, out });
|
|
126
|
+
} catch (error) {
|
|
127
|
+
failures.set(`${screen.name}@${width}`, { target: name, step: error.step ?? "Capture", screenshot: error.screenshot, message: error.message });
|
|
128
|
+
say(error.message);
|
|
129
|
+
continue;
|
|
130
|
+
}
|
|
131
|
+
cache[relative] = captureKey(target, screen.targets[name], width, height);
|
|
132
|
+
writeJson(cacheFile, cache);
|
|
133
|
+
say(`Captured ${relative}`);
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
await session.close();
|
|
137
|
+
sessions.delete(name);
|
|
138
|
+
}
|
|
139
|
+
for (const screen of screens) for (const width of map.widths) {
|
|
140
|
+
const error = failures.get(`${screen.name}@${width}`);
|
|
141
|
+
if (error) { fresh.push({ screen: screen.name, width, targets, error, regions: [], inventoryFindings: [] }); continue; }
|
|
142
|
+
const images = targets.map(name => PNG.sync.read(readFileSync(path.join(out, screen.name, `${name}@${width}.png`))));
|
|
143
|
+
const { pair, ...diff } = compareImages(...images);
|
|
144
|
+
const layouts = targets.map(name => PNG.sync.read(readFileSync(path.join(out, screen.name, `${name}@${width}.layout.png`))));
|
|
145
|
+
const unstable = new PNG({ width: layouts[0].width, height: layouts[0].height });
|
|
146
|
+
for (const name of targets) {
|
|
147
|
+
const mask = PNG.sync.read(readFileSync(path.join(out, screen.name, `${name}@${width}.unstable.png`)));
|
|
148
|
+
for (let i = 3; i < mask.data.length; i += 4) if (mask.data[i]) unstable.data.set([255, 0, 0, 255], i - 3);
|
|
149
|
+
}
|
|
150
|
+
const regions = findRegions(...layouts, { unstable: [unstable] });
|
|
151
|
+
for (const region of regions) {
|
|
152
|
+
region.crop = `${screen.name}/region-${region.id}@${width}.png`;
|
|
153
|
+
writeFileSync(path.join(out, region.crop), PNG.sync.write(regionCrop(...images, region.box)));
|
|
154
|
+
}
|
|
155
|
+
const inventories = targets.map(name => readJson(path.join(out, screen.name, `${name}@${width}.inventory.json`), []));
|
|
156
|
+
const inventoryFindings = diffInventory(...inventories);
|
|
157
|
+
for (const finding of inventoryFindings) {
|
|
158
|
+
finding.id += regions.length;
|
|
159
|
+
finding.box = inventoryBox(finding, images[0].width, images[0].height);
|
|
160
|
+
finding.crop = `${screen.name}/inventory-${finding.id}@${width}.png`;
|
|
161
|
+
writeFileSync(path.join(out, finding.crop), PNG.sync.write(regionCrop(...images, finding.box)));
|
|
162
|
+
}
|
|
163
|
+
const relative = `${screen.name}/pair@${width}.png`;
|
|
164
|
+
writeFileSync(path.join(out, relative), PNG.sync.write(boxPair(pair, [...regions, ...inventoryFindings])));
|
|
165
|
+
fresh.push({ screen: screen.name, width, targets, ...diff, regions, inventoryFindings, pair: relative });
|
|
166
|
+
}
|
|
167
|
+
const reportFile = path.join(out, "report.json");
|
|
168
|
+
const report = only ? mergeReport(readJson(reportFile, []), fresh) : sortReport(fresh);
|
|
169
|
+
writeJson(reportFile, report);
|
|
170
|
+
writeFileSync(path.join(out, "index.html"), gallery(report));
|
|
171
|
+
return report;
|
|
172
|
+
} finally {
|
|
173
|
+
for (const session of sessions.values()) await session.close();
|
|
174
|
+
}
|
|
175
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import test from "node:test";
|
|
2
|
+
import assert from "node:assert/strict";
|
|
3
|
+
import { selectScreens, captureKey, mergeReport, safeClick } from "./capture.mjs";
|
|
4
|
+
|
|
5
|
+
test("only selects named screens and refuses unknown names", () => {
|
|
6
|
+
const screens = [{ name: "projects" }, { name: "photos" }, { name: "drawings" }];
|
|
7
|
+
assert.deepEqual(selectScreens(screens, "photos,drawings").map(s => s.name), ["photos", "drawings"]);
|
|
8
|
+
assert.throws(() => selectScreens(screens, "typo"), /Unknown/);
|
|
9
|
+
});
|
|
10
|
+
|
|
11
|
+
test("cached captures change identity when routes or masks change", () => {
|
|
12
|
+
const target = { baseUrl: "https://app.example" };
|
|
13
|
+
const key = captureKey(target, { path: "/projects" }, 390, 900);
|
|
14
|
+
assert.notEqual(captureKey(target, { path: "/photos" }, 390, 900), key);
|
|
15
|
+
assert.notEqual(captureKey(target, { path: "/projects", masks: ["main"] }, 390, 900), key);
|
|
16
|
+
assert.notEqual(captureKey(target, { path: "/projects" }, 390, 800), key);
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
test("filtered report replaces matching rows and preserves other screens", () => {
|
|
20
|
+
const old = [{ screen: "photos", width: 390, targets: ["a", "b"], diffPercent: 50 }, { screen: "projects", width: 390, targets: ["a", "b"], diffPercent: 10 }];
|
|
21
|
+
const fresh = [{ screen: "photos", width: 390, targets: ["a", "b"], diffPercent: 0 }];
|
|
22
|
+
assert.deepEqual(mergeReport(old, fresh).map(r => [r.screen, r.diffPercent]), [["projects", 10], ["photos", 0]]);
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
test("hosted navigation rejects mutation controls", () => {
|
|
26
|
+
for (const control of [{ type: "submit", text: "Continue" }, { type: "button", text: "Delete project" }, { type: "button", text: "Save" }, { type: "button", text: "Complete" }]) assert.equal(safeClick(control), false);
|
|
27
|
+
assert.equal(safeClick({ type: "button", text: "Photos" }), true);
|
|
28
|
+
});
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import test from "node:test";
|
|
2
|
+
import assert from "node:assert/strict";
|
|
3
|
+
import { mkdtempSync, existsSync, rmSync } from "node:fs";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import os from "node:os";
|
|
6
|
+
import { chromium } from "playwright";
|
|
7
|
+
import { captureScreens } from "./capture.mjs";
|
|
8
|
+
|
|
9
|
+
test("a failing catalog step records its screenshot while the other screen completes", async () => {
|
|
10
|
+
const out = mkdtempSync(path.join(os.tmpdir(), "qc-catalog-browser-"));
|
|
11
|
+
const browser = await chromium.launch({ channel: "chrome", headless: true });
|
|
12
|
+
const target = { baseUrl: "https://screens.example", auth: { signedIn: "main" } };
|
|
13
|
+
const route = fail => ({ path: fail ? "/bad" : "/good", ready: "main", open: async (page, ctx) => {
|
|
14
|
+
await ctx.step("Navigate", () => page.goto(`${ctx.baseUrl}/${fail ? "bad" : "good"}`));
|
|
15
|
+
if (fail) await ctx.step("Open viewer", () => page.getByRole("button", { name: "Missing", exact: true }).click({ timeout: 100 }));
|
|
16
|
+
} });
|
|
17
|
+
try {
|
|
18
|
+
const report = await captureScreens({ widths: [200], targets: { a: target, b: target }, screens: ["bad", "good"].map(name => ({ name, targets: { a: route(name === "bad"), b: route(name === "bad") } })) }, { targets: ["a", "b"], out, timeout: 3000, height: 100 }, {
|
|
19
|
+
chromium, say: () => {}, sessionFactory: async () => {
|
|
20
|
+
const context = await browser.newContext({ serviceWorkers: "block" });
|
|
21
|
+
const page = await context.newPage();
|
|
22
|
+
await page.route("**/*", route => route.fulfill({ contentType: "text/html", body: '<main><h1>Fixture</h1><a href="/good">Good page</a></main>' }));
|
|
23
|
+
return { context, page, close: () => context.close() };
|
|
24
|
+
},
|
|
25
|
+
});
|
|
26
|
+
const bad = report.find(row => row.screen === "bad");
|
|
27
|
+
assert.equal(bad.error.step, "Open viewer");
|
|
28
|
+
assert.equal(existsSync(path.join(out, bad.error.screenshot)), true);
|
|
29
|
+
assert.equal(report.find(row => row.screen === "good").diffPercent, 0);
|
|
30
|
+
assert.equal(existsSync(path.join(out, "good/pair@200.png")), true);
|
|
31
|
+
} finally { await browser.close(); rmSync(out, { recursive: true, force: true }); }
|
|
32
|
+
});
|