Files
simplex-chat/apps/simplex-badge-service/web/test/boot.ts
T
19e70faeec badges: webapp feature branch (#7548)
* badges: webapp (#7433)

* badges: service migrations, store and catalog

* badges: BTCPay provider and settlement poller

* badges: web listener and /api endpoints

* web: checkout single-page app

* badges: tests and BTCPay fixtures

* badges: README and ini reference

* badges: fix hex16 build on GHC 8.10.7

* badges: Stripe card lane

* badges: fix Stripe card checkout, add theming

* badges: add a discount row to the order summary

* badges: site navbar, embedding, theme, Forget move

* badges: use SB code prefix in web checkout

* badges: rename sxb app namespace to sb

* badges: embed checkout nav via site; keep original app navbar

* badges: post iframe height, apply site background when embedded

* badges: embed dark surfaces, steadier iframe height

* badges: hide app footer when embedded

* badges: size embedded body to content, not viewport

* badges: declare color-scheme to stop reload flash

* badges: fade shell in on load, no reload blank

* badges: prerender app shell into index.html

* badges: pre-paint theme, hide shell on deep reload

* badges: logo returns to landing client-side

* badges: embedded wizard back, buy-a-code, resume

* badges: signal app-managed screens, resume across reload

* badges: rebuild wizard history on deep load so Back walks it

* badges: carry welcome-page height as the iframe floor

* badges: keep selection on Buy a code; rename to Your codes

* badges: read web shell as UTF-8, not locale

* badges: resume the exact paid order after Stripe card redirect

* badges: move docker deploy under scripts

* badges: add serve_webapp toggle and webapp export

* badges: wire split webapp deploy in docker config

* badges: quiet agent logs by default

* badges: resume card redirect in the embedded frame

* badges: migrate Stripe adapter to PaymentIntents

* badges: correct Stripe restricted key scopes in ini example

* badges: card via Payment Element and PaymentIntents

* badges: fix stale Checkout Session wording in Stripe adapter

* badges: fix stale CheckoutActions reference in card comment

* badges: order shell stylesheet before bootstrap script

* badges: remove development card stand-in

* badges: theme the Stripe card form with the site palette

* badges: exclude web from the Haskell build stage

* badges: unify invoice cancel and mark canceled

* badges: default log level to info

* badges: unify closed-invoice buy-again button

* badges: mute agent connection logs at info level

* badges: show purchase time in local timezone in Your codes

* badges: log service events on own channel, quiet agent

* badges: fold service migrations into one baseline

* badges: run compose on postgres over host network

* badges: use high-res hero art

* badges: add web CI to catch stale builds

* badges: rebuild web shell from committed source

* badges: normalize invoice-code link and columns

* badges: drop unused columns, rename index

* badges: note deferred receipt_hash in migrations

* badges: apply code-review fixes

* badges: reduce comments across service and web

---------

Co-authored-by: Evgeny Poberezkin <evgeny@poberezkin.com>
Co-authored-by: Evgeny @ SimpleX Chat <259188159+evgeny-simplex@users.noreply.github.com>

* badges: improve web page (#7546)

* badges: improve web page

* improve layout

* improve layout

* fix

* small changes

---------

Co-authored-by: Evgeny @ SimpleX Chat <259188159+evgeny-simplex@users.noreply.github.com>

* badges: read one issuer key from the ini

* badges: move and group the service tests

* badges: service fixes (#7567)

* badges: match the redeem error wording in tests

* badges: drop unused imports in the bot tests

* badges: cancel Stripe orders when they expire

* badges: correct the Stripe config and docs

* badges: refuse to revoke a redeemed code

* badges: make the fake Stripe cancel like Stripe

* badges: limit replayed webhook deliveries

---------

Co-authored-by: sh <37271604+shumvgolove@users.noreply.github.com>
Co-authored-by: Evgeny @ SimpleX Chat <259188159+evgeny-simplex@users.noreply.github.com>
Co-authored-by: shum <github.shum@liber.li>
Co-authored-by: spaced4ndy <8711996+spaced4ndy@users.noreply.github.com>
2026-09-25 09:01:51 +00:00

196 lines
7.4 KiB
TypeScript

import { test } from "node:test";
// Installs the globals main.ts needs; it runs once per process on import, so a second boot scenario needs its own file.
import {
MemStorage, StubHistory, installDocument, locationOf,
type Clipboard, type Connectivity, type ServiceWorkers, type StubDocument, type StubElement,
} from "./stub-dom.js";
export interface Reply {
status: number;
body: unknown;
headers?: Record<string, string>;
}
export interface Page {
app: StubElement;
chrome: StubElement;
documentElement: StubElement;
document: StubDocument;
history: StubHistory;
location: { pathname: string; search: string; hash: string };
storage: MemStorage;
clipboard: Clipboard;
fetches: Array<{ url: string; init?: RequestInit }>;
confirms: string[];
workers: ServiceWorkers;
connectivity: Connectivity;
respondWith(reply: Reply): void;
// Answers a request already holding, which respondWith cannot; returns false when nothing matches.
answerHeld(reply: Reply, match?: string): boolean;
confirmAnswer(answer: boolean): void;
setOffline(on: boolean): void;
reducedMotion(on: boolean): void;
fire(type: string): void;
press(key: string, init?: { shiftKey?: boolean }): void;
}
export interface BootOptions {
storage?: MemStorage;
url?: string;
}
export function installPage(opts: BootOptions = {}): Page {
const { app, chrome, documentElement, clipboard, document, workers, connectivity } = installDocument();
const storage = opts.storage ?? new MemStorage();
const fetches: Array<{ url: string; init?: RequestInit }> = [];
const confirms: string[] = [];
const windowListeners = new Map<string, Array<() => void>>();
const location = { pathname: "/", search: "", hash: "" };
let offline = false;
let nextResponse: Reply | null = null;
const held: Array<{ url: string; resolve: (r: Response) => void }> = [];
let answer = true;
let reduced = false;
const syncLocation = (): void => { Object.assign(location, locationOf(history.url)); };
const fire = (type: string): void => {
syncLocation();
for (const fn of [...(windowListeners.get(type) ?? [])]) fn();
};
const press = (key: string, init: { shiftKey?: boolean } = {}): void => {
const event = { key, shiftKey: false, ...init, preventDefault: () => {} };
for (const fn of [...(windowListeners.get("keydown") ?? [])]) (fn as (e: unknown) => void)(event);
};
const history = new StubHistory(() => { fire("popstate"); }, () => { syncLocation(); });
if (opts.url !== undefined) {
history.replaceState(null, "", opts.url);
}
syncLocation();
Object.defineProperty(globalThis, "history", { configurable: true, value: history });
Object.defineProperty(globalThis, "location", { configurable: true, value: location });
Object.defineProperty(globalThis, "window", {
configurable: true,
value: {
localStorage: storage,
confirm: (message: string) => { confirms.push(message); return answer; },
matchMedia: (query: string) => ({
media: query,
matches: query === "(prefers-reduced-motion: reduce)" && reduced,
}),
addEventListener(type: string, fn: () => void) {
const list = windowListeners.get(type) ?? [];
list.push(fn);
windowListeners.set(type, list);
},
fetch: async (input: unknown, init?: RequestInit): Promise<Response> => {
fetches.push(init ? { url: String(input), init } : { url: String(input) });
// A browser with no network throws this TypeError.
if (offline) throw new TypeError("Failed to fetch");
const reply = nextResponse;
nextResponse = null;
if (reply === null) {
// A pending promise with no timer lets the process still exit while the request holds.
return new Promise<Response>((resolve, reject) => {
const signal = init?.signal;
// abort never fires for an already-aborted signal, so reject explicitly or the stub holds where fetch would reject.
if (signal?.aborted) { queueMicrotask(() => { reject(new Error("aborted")); }); return; }
const entry = { url: String(input), resolve };
held.push(entry);
signal?.addEventListener("abort", () => {
const at = held.indexOf(entry);
if (at >= 0) held.splice(at, 1);
// A real fetch rejects an aborted request on the microtask drain of the same turn.
queueMicrotask(() => { reject(new Error("aborted")); });
}, { once: true });
});
}
return responseOf(reply);
},
},
});
function responseOf(reply: Reply): Response {
return {
ok: reply.status < 400,
status: reply.status,
headers: {
get: (name: string) => {
const map = reply.headers ?? {};
const key = Object.keys(map).find((k) => k.toLowerCase() === name.toLowerCase());
return key === undefined ? null : map[key]!;
},
},
json: async () => reply.body,
text: async () => JSON.stringify(reply.body),
} as unknown as Response;
}
return {
app, chrome, documentElement, document, history, location, storage, clipboard, fetches, confirms, workers, connectivity,
respondWith: (reply) => { nextResponse = reply; },
answerHeld: (reply, match) => {
const at = match === undefined ? 0 : held.findIndex((h) => h.url.includes(match));
if (at < 0 || held.length === 0) return false;
const [entry] = held.splice(at, 1);
entry!.resolve(responseOf(reply));
return true;
},
confirmAnswer: (value) => { answer = value; },
setOffline: (on) => {
offline = on;
connectivity.online = !on;
fire(on ? "offline" : "online");
},
reducedMotion: (on) => { reduced = on; },
fire,
press,
};
}
export const flush = (): Promise<void> => new Promise((r) => setImmediate(r));
export async function settle(times = 6): Promise<void> {
for (let i = 0; i < times; i++) await flush();
}
// Waits for an outcome rather than a fixed number of turns, since crypto.subtle.digest resolves off the main thread and a tick count would race.
export async function until(condition: () => boolean, what: string, turns = 500): Promise<void> {
for (let i = 0; i < turns; i++) {
if (condition()) return;
await flush();
}
throw new Error(`timed out waiting for ${what}`);
}
export function timedTest(ms: number) {
return (name: string, fn: () => void | Promise<void>): void => {
test(name, { timeout: ms }, fn);
};
}
export function screenOf(app: StubElement): StubElement { return app.all("section.panel")[0]!; }
export function inViewOf(app: StubElement): StubElement {
const found = app.all("section.panel").find((p) => !p.hasAttribute("inert"));
if (found === undefined) throw new Error("exactly one panel must be in view");
return found;
}
export function headingOf(p: StubElement): string { return p.all("h1")[0]?.textContent ?? ""; }
export function primaryOf(p: StubElement): StubElement | undefined {
return p.all("button.primary").find((b) => !b.hasAttribute("disabled"));
}
const FORGET_LABEL = "Forget everything on this device";
export function forgetControl(page: Page): StubElement | undefined {
page.chrome.all("button.menu-button")[0]!.click();
page.chrome.all("button.menu-item").find((b) => b.textContent === "Your codes")!.click();
return page.app.all("button.danger").find((b) => b.textContent === FORGET_LABEL);
}