winzik/tools/chrome/run.cjs

118 lines
6.2 KiB
JavaScript

// A Chrome extension in a headless Chrome (bin/jumphp chrome:run <folder> [url]): loaded unpacked, its id printed,
// a page opened (https://example.com/ served from tests/fixtures/page.html when it exists: no network needed; or the
// URL given, from the network), then screenshots in var/screenshots/: page.png (the page, 1280x800 = a Chrome Web
// Store screenshot), options.png (1280x800) and popup.png (its own size). Console errors and failed loads of the
// service worker and of every page are printed; any of them = exit 1.
// node run.cjs <extension folder> [url]
'use strict';
const fs = require('fs');
const path = require('path');
const puppeteer = require('puppeteer');
const root = path.resolve(process.argv[2] || '.');
const url = process.argv[3] || 'https://example.com/';
const out = path.join(root, 'var', 'screenshots');
fs.mkdirSync(out, { recursive: true });
const manifest = JSON.parse(fs.readFileSync(path.join(root, 'manifest.json'), 'utf8'));
const fixture = path.join(root, 'tests', 'fixtures', 'page.html');
const errors = [];
const wait = (ms) => new Promise((r) => setTimeout(r, ms));
function watch(page, label) {
page.on('console', (m) => {
if (m.type() === 'error' || m.type() === 'warn') console.log(`[${label} console.${m.type()}] ${m.text()}`);
if (m.type() === 'error') errors.push(`${label}: ${m.text()}`);
});
page.on('pageerror', (e) => { console.log(`[${label} error] ${e.message}`); errors.push(`${label}: ${e.message}`); });
page.on('requestfailed', (r) => {
if (r.url().startsWith('chrome-extension://')) { console.log(`[${label} missing] ${r.url()}`); errors.push(`${label}: cannot load ${r.url()}`); }
});
}
(async () => {
const browser = await puppeteer.launch({
headless: 'new',
args: ['--no-sandbox', '--lang=en-US', `--disable-extensions-except=${root}`, `--load-extension=${root}`],
});
let worker = null, id = null;
if (manifest.background?.service_worker) {
const target = await browser.waitForTarget((t) => t.type() === 'service_worker' && t.url().startsWith('chrome-extension://'), { timeout: 15000 })
.catch(() => null);
if (!target) errors.push('the background service worker did not start (a syntax error, a missing import?)');
else {
id = new URL(target.url()).host;
worker = await target.worker();
worker.on('console', (m) => { console.log(`[worker console.${m.type()}] ${m.text()}`); if (m.type() === 'error') errors.push(`worker: ${m.text()}`); });
}
}
if (!id) {
// no service worker: find the id on chrome://extensions
const page = await browser.newPage();
await page.goto('chrome://extensions');
id = await page.evaluate(() => chrome.management?.getAll ? new Promise((r) => chrome.management.getAll((l) => r(l.find((e) => e.installType === 'development')?.id))) : null).catch(() => null);
await page.close();
}
const { resolveMessage } = require('./common.cjs');
let messages = {};
try { messages = JSON.parse(fs.readFileSync(path.join(root, '_locales', manifest.default_locale || 'en', 'messages.json'), 'utf8')); } catch { /* no locale */ }
console.log(`extension: ${resolveMessage(manifest.name, messages)} ${manifest.version}`);
console.log(`id: ${id || '(unknown)'}`);
// the page (the content scripts run there)
const page = await browser.newPage();
watch(page, 'page');
await page.setViewport({ width: 1280, height: 800 });
if (fs.existsSync(fixture) && /^https:\/\/(www\.)?example\.com\//.test(url)) {
await page.setRequestInterception(true);
page.on('request', (r) => (/^https:\/\/(www\.)?example\.com\//.test(r.url())
? r.respond({ status: 200, contentType: 'text/html; charset=utf-8', body: fs.readFileSync(fixture) })
: r.continue()));
}
await page.goto(url, { waitUntil: 'load', timeout: 30000 }).catch((e) => errors.push(`page: ${e.message}`));
await wait(1500);
await page.screenshot({ path: path.join(out, 'page.png') });
console.log(`page: ${url} -> var/screenshots/page.png`);
if (id) {
const optionsPath = manifest.options_page || manifest.options_ui?.page;
if (optionsPath) {
const options = await browser.newPage();
watch(options, 'options');
await options.setViewport({ width: 1280, height: 800 });
await options.goto(`chrome-extension://${id}/${optionsPath}`, { waitUntil: 'load' });
await wait(700);
await options.screenshot({ path: path.join(out, 'options.png') });
console.log(`options: chrome-extension://${id}/${optionsPath} -> var/screenshots/options.png`);
await options.close();
}
const popupPath = manifest.action?.default_popup;
if (popupPath) {
// the popup acts on the tab of the page above (?tab=<id>: see popup.js)
// (brought to the front it is the active tab: without the "tabs" permission tabs.query cannot filter by URL)
await page.bringToFront();
const tab = worker ? await worker.evaluate(async () => (await chrome.tabs.query({ active: true, lastFocusedWindow: true }))[0]?.id).catch(() => null) : null;
const popup = await browser.newPage();
watch(popup, 'popup');
await popup.setViewport({ width: 800, height: 600 });
await popup.goto(`chrome-extension://${id}/${popupPath}${tab ? `${popupPath.includes('?') ? '&' : '?'}tab=${tab}` : ''}`, { waitUntil: 'load' });
await wait(700);
// a popup is as big as its content (at most 800x600)
const size = await popup.evaluate(() => {
const r = document.body.getBoundingClientRect();
const style = getComputedStyle(document.body);
const h = r.height + parseFloat(style.marginTop) + parseFloat(style.marginBottom);
return { width: Math.min(800, Math.max(Math.ceil(r.width), 25)), height: Math.min(600, Math.max(Math.ceil(h), 25)) };
});
await popup.screenshot({ path: path.join(out, 'popup.png'), clip: { x: 0, y: 0, ...size } });
console.log(`popup: chrome-extension://${id}/${popupPath} (${size.width}x${size.height}) -> var/screenshots/popup.png`);
await popup.close();
}
}
await browser.close();
if (errors.length) {
console.log(`${errors.length} error(s):`);
for (const e of errors) console.log(` ${e}`);
process.exit(1);
}
console.log('no console error');
})().catch((e) => { console.error(e); process.exit(1); });