okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-027-web: the served web chat page for 0.2.75d9f47922

main
4.0 KiB77 linesraw
1// Shared bits for the browser tests and the screenshot script of the served web page (serve/web): a headless Chromium,
2// a page against the mock server, small helpers. puppeteer-core is not a dependency of the repo: install it anywhere and
3// point WEBTEST_MODULES at that folder (the one that holds node_modules); CHROME_BIN is the Chrome or Edge to drive.
4import { createRequire } from "node:module";
5import path from "node:path";
6import fs from "node:fs";
7
8const req = createRequire(path.join(process.env.WEBTEST_MODULES || process.cwd(), "noop.js"));
9export const puppeteer = req("puppeteer-core");
10
11const CANDIDATES = [process.env.CHROME_BIN, "C:/Program Files/Google/Chrome/Application/chrome.exe",
12  "C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe", "/usr/bin/google-chrome", "/usr/bin/chromium", "/usr/bin/chromium-browser",
13  "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"].filter(Boolean);
14export const chrome = () => {
15  const found = CANDIDATES.find((p) => fs.existsSync(p));
16  if (!found) throw new Error("no Chrome or Edge found; set CHROME_BIN");
17  return found;
18};
19export const launch = () => puppeteer.launch({ executablePath: chrome(), headless: true, args: ["--no-sandbox", "--disable-gpu"] });
20
21// a page with a seeded browser store (localStorage values are JSON, as the page's own store writes them), console errors collected
22export async function openPage(browser, mock, { width = 1280, height = 800, seed = {}, query = "", dark = false, hash = "", dialogs = "accept" } = {}) {
23  const context = await browser.createBrowserContext();
24  const page = await context.newPage();
25  page.errors = [];
26  page.on("pageerror", (e) => page.errors.push("pageerror: " + e.message));
27  page.on("console", (m) => { if (m.type() === "error") page.errors.push("console: " + m.text()); });
28  page.on("dialog", async (d) => { page.lastDialog = d.message(); if (dialogs === "accept") await d.accept(); else await d.dismiss(); });
29  await page.setViewport({ width, height });
30  await page.emulateMediaFeatures([{ name: "prefers-color-scheme", value: dark ? "dark" : "light" }]);
31  await page.evaluateOnNewDocument((s) => {
32    if (window !== window.top) return;                  // not in the preview frames: they have no storage
33    if (sessionStorage.getItem("seeded")) return;
34    sessionStorage.setItem("seeded", "1");
35    for (const [k, v] of Object.entries(s)) localStorage.setItem("strata." + k, JSON.stringify(v));
36  }, seed);
37  await page.goto(mock.url + "/" + query + hash, { waitUntil: "networkidle0" });
38  return page;
39}
40
41export const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
42// the page's own `busy` is a top-level let of app.js: reachable by name from page.evaluate
43export const idle = (page, timeout = 15000) => page.waitForFunction(() => busy === null, { timeout });
44export async function say(page, text) {
45  await page.click("#input");
46  await page.type("#input", text);
47  await page.keyboard.press("Enter");
48}
49export const assistantText = (page, i = -1) => page.evaluate((n) => { const a = messages.filter((m) => m.role === "assistant"); return a.at(n).text; }, i);
50export const shot = async (page, dir, name, opts = {}) => {
51  fs.mkdirSync(dir, { recursive: true });
52  const file = path.join(dir, name + ".png");
53  await page.screenshot({ path: file, ...opts });
54  return file;
55};
56
57// tiny test runner: node file.mjs [name-substring]
58export function runner(title) {
59  const tests = [];
60  const only = process.argv[2];
61  return {
62    test: (name, fn) => tests.push([name, fn]),
63    async run(setup) {
64      const ctx = await setup();
65      let failed = 0;
66      for (const [name, fn] of tests) {
67        if (only && !name.includes(only)) continue;
68        const t = Date.now();
69        try { await fn(ctx); console.log(`ok   ${name} (${Date.now() - t} ms)`); }
70        catch (e) { failed++; console.log(`FAIL ${name}\n     ${String(e.stack || e).split("\n").slice(0, 6).join("\n     ")}`); }
71      }
72      await ctx.close();
73      console.log(failed ? `${title}: ${failed} failed` : `${title}: all passed`);
74      process.exitCode = failed ? 1 : 0;
75    },
76  };
77}