253 lines
8.6 KiB
JavaScript
253 lines
8.6 KiB
JavaScript
import { createServer } from 'node:http';
|
|
import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
|
|
import { spawn } from 'node:child_process';
|
|
import { once } from 'node:events';
|
|
import { setTimeout as delay } from 'node:timers/promises';
|
|
import { join, extname, resolve, sep } from 'node:path';
|
|
import { tmpdir } from 'node:os';
|
|
|
|
// Serves the Flutter web build produced by:
|
|
// flutter build web -t tool/schedules_list_probe_app.dart
|
|
// The fixture is local-only: no Pipelines server, authentication or real
|
|
// schedule is touched.
|
|
const root = join(process.cwd(), 'build/web');
|
|
const outputIndex = process.argv.indexOf('--out');
|
|
const output = outputIndex >= 0
|
|
? resolve(process.argv[outputIndex + 1])
|
|
: resolve(process.env.OPENCODE_ARTIFACT_DIR ?? join(process.cwd(), 'build/schedules-captures'));
|
|
const chromePath = process.env.CHROME_PATH
|
|
?? '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome';
|
|
const mime = {
|
|
'.html': 'text/html; charset=utf-8',
|
|
'.js': 'text/javascript; charset=utf-8',
|
|
'.mjs': 'text/javascript; charset=utf-8',
|
|
'.json': 'application/json',
|
|
'.wasm': 'application/wasm',
|
|
'.png': 'image/png',
|
|
'.jpg': 'image/jpeg',
|
|
'.svg': 'image/svg+xml',
|
|
'.ico': 'image/x-icon',
|
|
'.css': 'text/css; charset=utf-8',
|
|
'.ttf': 'font/ttf',
|
|
'.otf': 'font/otf',
|
|
'.woff': 'font/woff',
|
|
'.woff2': 'font/woff2',
|
|
'.bin': 'application/octet-stream',
|
|
};
|
|
|
|
const server = createServer(async (req, res) => {
|
|
try {
|
|
const pathname = decodeURIComponent(new URL(req.url, 'http://localhost').pathname);
|
|
const path = resolve(root, '.' + pathname);
|
|
if (path !== root && !path.startsWith(root + sep)) {
|
|
return res.writeHead(403).end();
|
|
}
|
|
const filePath = pathname.endsWith('/') ? join(path, 'index.html') : path;
|
|
const file = await readFile(filePath);
|
|
res
|
|
.writeHead(200, {
|
|
'content-type': mime[extname(filePath)] ?? 'application/octet-stream',
|
|
'cache-control': 'no-store',
|
|
})
|
|
.end(file);
|
|
} catch {
|
|
res.writeHead(404).end('not found');
|
|
}
|
|
});
|
|
server.listen(0, '127.0.0.1');
|
|
await once(server, 'listening');
|
|
const port = server.address().port;
|
|
const profile = await mkdtemp(join(tmpdir(), 's1b-schedules-chrome-'));
|
|
const chrome = spawn(chromePath, [
|
|
'--headless=new',
|
|
'--no-first-run',
|
|
'--no-default-browser-check',
|
|
'--disable-gpu',
|
|
'--remote-debugging-port=0',
|
|
`--user-data-dir=${profile}`,
|
|
'about:blank',
|
|
], { stdio: ['ignore', 'ignore', 'pipe'] });
|
|
let stderr = '';
|
|
chrome.stderr.on('data', data => { stderr += data; });
|
|
const waitFor = async (fn, label, attempts = 160) => {
|
|
for (let i = 0; i < attempts; i++) {
|
|
const value = await fn();
|
|
if (value) return value;
|
|
await delay(100);
|
|
}
|
|
throw new Error(`Timed out waiting for ${label}`);
|
|
};
|
|
let ws;
|
|
try {
|
|
const endpoint = await waitFor(
|
|
() => stderr.match(/DevTools listening on (ws:\/\/[^\s]+)/)?.[1],
|
|
'Chrome DevTools',
|
|
);
|
|
ws = new WebSocket(endpoint);
|
|
await once(ws, 'open');
|
|
let id = 0;
|
|
const pending = new Map();
|
|
const pageErrors = [];
|
|
ws.addEventListener('message', event => {
|
|
const msg = JSON.parse(event.data);
|
|
if (msg.method === 'Runtime.exceptionThrown') {
|
|
pageErrors.push(msg.params?.exceptionDetails?.text ?? 'page exception');
|
|
}
|
|
if (msg.id && pending.has(msg.id)) {
|
|
pending.get(msg.id)(msg);
|
|
pending.delete(msg.id);
|
|
}
|
|
});
|
|
const send = (method, params = {}, sessionId) => new Promise(resolveCall => {
|
|
const callId = ++id;
|
|
pending.set(callId, resolveCall);
|
|
ws.send(JSON.stringify({
|
|
id: callId,
|
|
method,
|
|
params,
|
|
...(sessionId ? { sessionId } : {}),
|
|
}));
|
|
});
|
|
const created = await send('Target.createTarget', { url: 'about:blank' });
|
|
if (!created.result) throw new Error(`Target creation failed: ${JSON.stringify(created)}`);
|
|
const target = created.result.targetId;
|
|
const session = (
|
|
await send('Target.attachToTarget', { targetId: target, flatten: true })
|
|
).result.sessionId;
|
|
await send('Page.enable', {}, session);
|
|
await send('Runtime.enable', {}, session);
|
|
const evaluate = async expression => {
|
|
const response = await send(
|
|
'Runtime.evaluate',
|
|
{ expression, returnByValue: true, awaitPromise: true },
|
|
session,
|
|
);
|
|
if (response.error) throw new Error(`Runtime.evaluate failed: ${JSON.stringify(response)}`);
|
|
if (response.result?.exceptionDetails) {
|
|
throw new Error(`Runtime exception: ${JSON.stringify(response.result.exceptionDetails)}`);
|
|
}
|
|
return response.result?.result?.value;
|
|
};
|
|
await mkdir(output, { recursive: true });
|
|
const cases = [
|
|
{
|
|
name: 's1b-schedules-material-390',
|
|
theme: 'material',
|
|
scale: 1,
|
|
width: 390,
|
|
height: 844,
|
|
expect: ['4 schedules', 'Research batteries', 'Pipeline 4 · v2', 'Timer: Every 24h', 'Timezone: Europe/London', 'Next due:'],
|
|
},
|
|
{
|
|
name: 's1b-schedules-material-390-2x',
|
|
theme: 'material',
|
|
scale: 2,
|
|
width: 390,
|
|
height: 844,
|
|
expect: ['Research batteries', 'Pipeline 4 · v2', 'Workspace: /srv/research', 'Timer: Every 24h'],
|
|
},
|
|
{
|
|
name: 's1b-schedules-material-390-dark',
|
|
theme: 'material',
|
|
brightness: 'dark',
|
|
scale: 1,
|
|
width: 390,
|
|
height: 844,
|
|
expect: ['4 schedules', 'Research batteries', 'Pipeline 4 · v2', 'Timezone: Europe/London', 'Next due:'],
|
|
},
|
|
{
|
|
name: 's1b-schedules-cupertino-390',
|
|
theme: 'cupertino',
|
|
scale: 1,
|
|
width: 390,
|
|
height: 844,
|
|
expect: ['Research batteries', 'Pipeline 4 · v2', 'Timezone: Europe/London'],
|
|
},
|
|
{
|
|
name: 's1b-schedules-material-1100',
|
|
theme: 'material',
|
|
scale: 1,
|
|
width: 1100,
|
|
height: 800,
|
|
expect: ['Research batteries', 'Nightly report', 'Weekly digest', 'Sparse server record'],
|
|
},
|
|
];
|
|
const results = [];
|
|
for (const item of cases) {
|
|
const query = new URLSearchParams({ theme: item.theme, scale: String(item.scale) });
|
|
if (item.brightness) query.set('brightness', item.brightness);
|
|
const url = `http://127.0.0.1:${port}/?${query}`;
|
|
const navigation = await send('Page.navigate', { url }, session);
|
|
if (navigation.error || navigation.result?.errorText) {
|
|
throw new Error(`Navigation failed: ${JSON.stringify(navigation)}`);
|
|
}
|
|
await send(
|
|
'Emulation.setDeviceMetricsOverride',
|
|
{
|
|
width: item.width,
|
|
height: item.height,
|
|
deviceScaleFactor: 1,
|
|
mobile: item.width < 600,
|
|
},
|
|
session,
|
|
);
|
|
await delay(2500);
|
|
const placeholder = await waitFor(
|
|
() => evaluate("!!document.querySelector('flt-semantics-placeholder')"),
|
|
`${item.name} semantics placeholder`,
|
|
);
|
|
if (!placeholder) throw new Error(`${item.name}: no semantics placeholder`);
|
|
await evaluate("document.querySelector('flt-semantics-placeholder')?.click()");
|
|
const labels = await waitFor(async () => {
|
|
const current = await evaluate(
|
|
"[...document.querySelectorAll('flt-semantics')].map(x=>x.getAttribute('aria-label')||x.innerText).filter(Boolean)",
|
|
);
|
|
return current?.some(label => label.includes('Research batteries')) ? current : null;
|
|
}, `${item.name} schedule content`);
|
|
const text = labels.join('\n');
|
|
for (const expected of item.expect) {
|
|
if (!text.includes(expected)) {
|
|
throw new Error(`${item.name}: missing ${JSON.stringify(expected)} in ${JSON.stringify(labels)}`);
|
|
}
|
|
}
|
|
if (/does not support|No schedules yet|socket closed/.test(text)) {
|
|
throw new Error(`${item.name}: unexpected state text ${JSON.stringify(labels)}`);
|
|
}
|
|
await delay(400);
|
|
const screenshot = await send(
|
|
'Page.captureScreenshot',
|
|
{ format: 'png', captureBeyondViewport: false },
|
|
session,
|
|
);
|
|
const file = `${item.name}.png`;
|
|
await writeFile(join(output, file), Buffer.from(screenshot.result.data, 'base64'));
|
|
results.push({
|
|
name: item.name,
|
|
file,
|
|
width: item.width,
|
|
height: item.height,
|
|
theme: item.theme,
|
|
brightness: item.brightness ?? 'platform',
|
|
checked: item.expect,
|
|
labelCount: labels.length,
|
|
});
|
|
}
|
|
if (pageErrors.length) {
|
|
throw new Error(`Page exceptions: ${JSON.stringify(pageErrors)}`);
|
|
}
|
|
const manifest = {
|
|
url: `http://127.0.0.1:${port}/`,
|
|
fixture: 'tool/schedules_list_probe_app.dart',
|
|
output,
|
|
captures: results,
|
|
};
|
|
await writeFile(join(output, 'manifest.json'), JSON.stringify(manifest, null, 2));
|
|
console.log(JSON.stringify(manifest, null, 2));
|
|
} finally {
|
|
ws?.close();
|
|
chrome.kill('SIGTERM');
|
|
await Promise.race([once(chrome, 'exit'), delay(3000)]);
|
|
server.close();
|
|
await rm(profile, { recursive: true, force: true });
|
|
}
|