59 lines
2.7 KiB
JavaScript
59 lines
2.7 KiB
JavaScript
// Renders one of the plugin's pages or slots in jsdom with a fake bridge
|
|
// (`window.aiAgentPlugin`): every `query("read", {view})` answers from the
|
|
// fixtures file, every `action("act", …)` is recorded and answered `{ok: true}`.
|
|
// Prints {text, calls, errors, headers, empty} as JSON once the page settled.
|
|
// Test-only (tests/ is not installed).
|
|
//
|
|
// NODE_PATH=<a node_modules with jsdom> node render_harness.js <page.html> <fixtures.json> '<init json>' ['<click text>']
|
|
"use strict";
|
|
const fs = require("fs");
|
|
const { JSDOM } = require("jsdom");
|
|
|
|
const html = fs.readFileSync(process.argv[2], "utf8");
|
|
const fixtures = JSON.parse(fs.readFileSync(process.argv[3], "utf8"));
|
|
const init = JSON.parse(process.argv[4] || "{}");
|
|
const click = process.argv[5] || "";
|
|
const calls = [], errors = [], headers = [];
|
|
let empty = null;
|
|
|
|
const dom = new JSDOM(html, {
|
|
runScripts: "outside-only",
|
|
pretendToBeVisual: true,
|
|
url: "https://plugin.invalid/",
|
|
});
|
|
const w = dom.window;
|
|
w.scrollTo = () => {};
|
|
w.console.error = (...a) => errors.push(a.join(" "));
|
|
w.addEventListener("error", (e) => errors.push(String(e.message)));
|
|
w.aiAgentPlugin = {
|
|
init: Object.assign({ theme: { scheme: "light", tokens: {} } }, init),
|
|
query(name, payload, cb) {
|
|
calls.push(["query", name, payload]);
|
|
const d = fixtures[payload.view];
|
|
setTimeout(() => cb(d === undefined ? null : d, d === undefined ? { error: "no fixture for " + payload.view } : { fetching: false }), 0);
|
|
return { stop() {}, refresh() { calls.push(["refresh", name, payload]); } };
|
|
},
|
|
action(name, payload) { calls.push(["action", name, payload]); return Promise.resolve({ ok: true, killed: [1] }); },
|
|
setHeader(h) { headers.push(h); },
|
|
onHeaderAction() {}, onTheme() {}, onUpdate() {}, onRefresh() {},
|
|
resize() {}, setEmpty(e) { empty = e; },
|
|
navigate(p) { calls.push(["navigate", p]); return Promise.resolve(); },
|
|
toast(m) { calls.push(["toast", m]); return Promise.resolve(); },
|
|
scrollTo(t) { calls.push(["scrollTo", t]); return Promise.resolve(); },
|
|
};
|
|
for (const m of html.matchAll(/<script>([\s\S]*?)<\/script>/g)) {
|
|
try { w.eval(m[1]); } catch (e) { errors.push(String(e && e.stack || e)); }
|
|
}
|
|
setTimeout(() => {
|
|
if (click) {
|
|
const all = [...w.document.querySelectorAll("button, a, [role=button]")];
|
|
const b = all.find((x) => x.textContent.trim() === click) || all.find((x) => x.textContent.trim().startsWith(click));
|
|
if (b) { b.click(); b.click(); } else errors.push("no control named " + click);
|
|
}
|
|
setTimeout(() => {
|
|
w.document.querySelectorAll("script, style").forEach((n) => n.remove());
|
|
process.stdout.write(JSON.stringify({ text: w.document.body.textContent.replace(/\s+/g, " "), calls, errors, headers, empty }));
|
|
w.close();
|
|
}, 30);
|
|
}, 30);
|