Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

preview-preload-bundle.test.mjs

70 lines2.4 KB

1import * as NodeFSP from "node:fs/promises";
2import * as NodeOS from "node:os";
3import * as NodePath from "node:path";
4import * as NodeVM from "node:vm";
5import { JSDOM } from "jsdom";
6import { build } from "vite-plus/pack";
7import { assert, it } from "vite-plus/test";
8​
9import desktopConfig from "../vite.config.ts";
10​
11it("gives the page's world a function that runs without the preload's scope", async () => {
12 const directory = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-preview-preload-"));
13 try {
14 assert.ok(Array.isArray(desktopConfig.pack));
15 const packConfig = desktopConfig.pack.find(
16 (config) =>
17 Array.isArray(config.entry) && config.entry.includes("src/preview-pick-preload.ts"),
18 );
19 assert.ok(packConfig);
20 await build({
21 ...packConfig,
22 config: false,
23 cwd: NodePath.join(import.meta.dirname, ".."),
24 outDir: directory,
25 sourcemap: false,
26 logLevel: "silent",
27 });
28 const source = await NodeFSP.readFile(
29 NodePath.join(directory, "preview-pick-preload.cjs"),
30 "utf8",
31 );
32​
33 const executions = [];
34 const electron = {
35 contextBridge: {
36 executeInMainWorld: (execution) => {
37 executions.push(execution);
38 return { elementContext: async () => null };
39 },
40 },
41 ipcRenderer: { on: () => {}, off: () => {}, send: () => {}, sendToHost: () => {} },
42 };
43 const preload = new JSDOM("<!doctype html>", { runScripts: "outside-only" });
44 NodeVM.runInContext(
45 source,
46 Object.assign(preload.getInternalVMContext(), {
47 process: { argv: [] },
48 require: (specifier) => {
49 assert.equal(specifier, "electron");
50 return electron;
51 },
52 }),
53 );
54 assert.equal(executions.length, 1);
55​
56 // Electron compiles the function's source text in the page, where nothing of the preload exists.
57 const page = new JSDOM('<!doctype html><button id="target">Pay</button>', {
58 runScripts: "outside-only",
59 // React Grab binds requestAnimationFrame while it loads.
60 pretendToBeVisual: true,
61 });
62 const install = NodeVM.runInContext(`(${executions[0].func})`, page.getInternalVMContext());
63 const context = await install(...executions[0].args).elementContext(
64 page.window.document.getElementById("target"),
65 );
66 assert.equal(context.selector, "#target");
67 } finally {
68 await NodeFSP.rm(directory, { recursive: true, force: true });
69 }
70});