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

HtmlRender.test.ts

396 lines17.0 KB

1// @effect-diagnostics nodeBuiltinImport:off - plain local servers stand in for LAN services.
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import { describe, expect, it } from "@effect/vitest";
4import { ThreadId } from "@t3tools/contracts";
5import * as HostProcess from "@t3tools/shared/HostProcess";
6import {
7 HTML_RENDER_MEASURE_FONTS,
8 HTML_RENDER_MEASURE_WIDTHS,
9 htmlRenderTheme,
10} from "@t3tools/shared/htmlRender";
11import { T3_CODE_DARK_THEME_COLORS } from "@t3tools/shared/themePalettes";
12import * as Deferred from "effect/Deferred";
13import * as Effect from "effect/Effect";
14import * as Base64 from "effect/encoding/Base64";
15import * as Fiber from "effect/Fiber";
16import * as FileSystem from "effect/FileSystem";
17import * as Layer from "effect/Layer";
18import * as Option from "effect/Option";
19import * as Path from "effect/Path";
20import * as NodeDgram from "node:dgram";
21import * as NodeHttp from "node:http";
22import * as NodeURL from "node:url";
23​
24import { resolveAttachmentPathById } from "../attachmentStore.ts";
25import * as ServerConfig from "../config.ts";
26import * as HtmlRender from "./HtmlRender.ts";
27import * as PreviewBrowser from "../preview/PreviewBrowser.ts";
28​
29const TEST_BROWSER_ENV = "T3CODE_TEST_HEADLESS_SHELL";
30​
31const layerHtmlRender = (
32 executable?: string,
33 installed: Effect.Effect<Option.Option<string>> = Effect.succeed(
34 Option.fromUndefinedOr(executable),
35 ),
36) =>
37 HtmlRender.layer.pipe(
38 Layer.provide(
39 Layer.succeed(
40 PreviewBrowser.PreviewBrowser,
41 PreviewBrowser.PreviewBrowser.of({
42 executable:
43 executable === undefined
44 ? Effect.die("This test has no preview browser.")
45 : Effect.succeed(executable),
46 installed,
47 }),
48 ),
49 ),
50 Layer.provideMerge(ServerConfig.layerTest(process.cwd(), { prefix: "t3-html-render-" })),
51 Layer.provideMerge(NodeServices.layer),
52 );
53const layerTest = layerHtmlRender();
54​
55const PNG_BYTES = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
56​
57describe("HtmlRender", () => {
58 it.effect("inlines local images by absolute path and leaves URLs and relative paths alone", () =>
59 Effect.gen(function* () {
60 const fileSystem = yield* FileSystem.FileSystem;
61 const path = yield* Path.Path;
62 const htmlRender = yield* HtmlRender.HtmlRender;
63 const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-html-images-" });
64 const png = path.join(directory, "shot.png");
65 const svg = path.join(directory, "logo.svg");
66 yield* fileSystem.writeFile(png, PNG_BYTES);
67 yield* fileSystem.writeFileString(svg, "<svg/>");
68 const kept = [
69 "https://example.com/a.png",
70 "//cdn.example.com/b.png",
71 "./c.png",
72 "data:image/png;base64,AAAA",
73 ];
74​
75 const prepared = yield* htmlRender.prepare(
76 [
77 "<!doctype html><html><head><title>Shots</title></head><body>",
78 `<img src="${png}"><div style="background:url(${svg})"></div>`,
79 `<script>const shots = ['${png}', \`${svg}\`];</script>`,
80 ...kept.map((src) => `<img src="${src}">`),
81 "</body></html>",
82 ].join(""),
83 );
84​
85 const pngUri = `data:image/png;base64,${Base64.encode(PNG_BYTES)}`;
86 const svgUri = `data:image/svg+xml;base64,${Base64.encode("<svg/>")}`;
87 expect(prepared).toContain(`<img src="${pngUri}">`);
88 expect(prepared).toContain(`url(${svgUri})`);
89 expect(prepared).toContain(`['${pngUri}', \`${svgUri}\`]`);
90 expect(prepared).not.toContain(directory);
91 for (const src of kept) expect(prepared).toContain(`<img src="${src}">`);
92 expect(prepared.indexOf("<head>")).toBeLessThan(prepared.indexOf('<style id="t3-theme">'));
93 expect(prepared.indexOf('<style id="t3-theme">')).toBeLessThan(prepared.indexOf("<title>"));
94 }).pipe(Effect.provide(layerTest)),
95 );
96​
97 it.effect("inlines an SVG behind processing instructions and a doctype subset", () =>
98 Effect.gen(function* () {
99 const fileSystem = yield* FileSystem.FileSystem;
100 const path = yield* Path.Path;
101 const htmlRender = yield* HtmlRender.HtmlRender;
102 const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-html-images-" });
103 const svg = path.join(directory, "styled.svg");
104 const source = [
105 '<?xml version="1.0"?>',
106 '<?xml-stylesheet href="theme.css"?>',
107 '<!DOCTYPE svg [ <!ENTITY fill "red"> ]>',
108 '<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32"/>',
109 ].join("\n");
110 yield* fileSystem.writeFileString(svg, source);
111​
112 const prepared = yield* htmlRender.prepare(`<img src="${svg}">`);
113​
114 expect(prepared).toContain(`data:image/svg+xml;base64,${Base64.encode(source)}`);
115 }).pipe(Effect.provide(layerTest)),
116 );
117​
118 it.effect("lists every local image it cannot read", () =>
119 Effect.gen(function* () {
120 const fileSystem = yield* FileSystem.FileSystem;
121 const path = yield* Path.Path;
122 const htmlRender = yield* HtmlRender.HtmlRender;
123 const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-html-images-" });
124 const folder = path.join(directory, "folder.png");
125 yield* fileSystem.makeDirectory(folder);
126 const missing = path.join(directory, "missing.jpg");
127 const secret = path.join(directory, "secret.png");
128 yield* fileSystem.writeFileString(secret, "API_KEY=abc123");
129 const report = path.join(directory, "report.svg");
130 yield* fileSystem.writeFileString(report, "<!doctype html><body><svg></svg>API_KEY=abc123");
131 const config = path.join(directory, "config.svg");
132 yield* fileSystem.writeFileString(
133 config,
134 '<!DOCTYPE config [<!ENTITY a "a"><!ENTITY b "]><svg/>">]><config>API_KEY=abc123</config>',
135 );
136 const stalling = path.join(directory, "stalling.svg");
137 yield* fileSystem.writeFileString(stalling, `${"<?p?>".repeat(40)}<config><svg/></config>`);
138 const unclosed = path.join(directory, "unclosed.svg");
139 yield* fileSystem.writeFileString(unclosed, '<!DOCTYPE svg [<!ENTITY a "x><svg/>');
140 const upper = path.join(directory, "upper.svg");
141 yield* fileSystem.writeFileString(upper, "<SVG/>API_KEY=abc123");
142 const longer = path.join(directory, "longer.svg");
143 yield* fileSystem.writeFileString(longer, "<svg\u00e9/>API_KEY=abc123");
144​
145 const error = yield* htmlRender
146 .prepare(
147 `<img src="${missing}"><img src='${folder}'><img src="C:\\nope\\shot.webp"><img src="${secret}"><img src="${report}"><img src="${config}"><img src="${stalling}"><img src="${unclosed}"><img src="${upper}"><img src="${longer}">`,
148 )
149 .pipe(Effect.flip);
150​
151 expect(error).toBeInstanceOf(HtmlRender.HtmlRenderImagesNotFoundError);
152 expect(error._tag === "HtmlRenderImagesNotFoundError" && error.paths).toEqual([
153 missing,
154 folder,
155 "C:\\nope\\shot.webp",
156 secret,
157 report,
158 config,
159 stalling,
160 unclosed,
161 upper,
162 longer,
163 ]);
164 }).pipe(Effect.provide(layerTest)),
165 );
166​
167 it.effect("publishes the prepared page as an html thread attachment", () =>
168 Effect.gen(function* () {
169 const fileSystem = yield* FileSystem.FileSystem;
170 const config = yield* ServerConfig.ServerConfig;
171 const htmlRender = yield* HtmlRender.HtmlRender;
172​
173 const reference = yield* htmlRender.publish({
174 threadId: ThreadId.make("thread-html-render"),
175 html: "<p>Quarterly revenue</p>",
176 title: " Revenue ",
177 height: 9_000,
178 });
179​
180 expect(reference).toEqual({
181 attachmentId: expect.any(String),
182 title: "Revenue",
183 height: 2_000,
184 });
185 const stored = resolveAttachmentPathById({
186 attachmentsDir: config.attachmentsDir,
187 attachmentId: reference.attachmentId,
188 });
189 expect(stored?.endsWith(".html")).toBe(true);
190 const html = yield* fileSystem.readFileString(stored ?? "");
191 expect(html).toContain('<style id="t3-theme">');
192 expect(html).toContain("<p>Quarterly revenue</p>");
193 }).pipe(Effect.provide(layerTest)),
194 );
195​
196 it.effect("removes the page when publishing is interrupted", () =>
197 Effect.gen(function* () {
198 const measuring = yield* Deferred.make<void>();
199 yield* Effect.gen(function* () {
200 const fileSystem = yield* FileSystem.FileSystem;
201 const config = yield* ServerConfig.ServerConfig;
202 const htmlRender = yield* HtmlRender.HtmlRender;
203 const storedPages = fileSystem
204 .readDirectory(config.attachmentsDir, { recursive: true })
205 .pipe(Effect.map((names) => names.filter((name) => name.endsWith(".html"))));
206​
207 const publishing = yield* htmlRender
208 .publish({
209 threadId: ThreadId.make("thread-html-cancel"),
210 html: "<p>x</p>",
211 title: "X",
212 height: 200,
213 })
214 .pipe(Effect.forkChild);
215 yield* Deferred.await(measuring);
216 expect(yield* storedPages).toHaveLength(1);
217 yield* Fiber.interrupt(publishing);
218 expect(yield* storedPages).toEqual([]);
219 }).pipe(
220 Effect.provide(
221 layerHtmlRender(
222 undefined,
223 Deferred.succeed(measuring, undefined).pipe(Effect.andThen(Effect.never)),
224 ),
225 ),
226 );
227 }),
228 );
229​
230 it.live(
231 "screenshots the page in headless Chrome with the requested theme and every console level",
232 (ctx) =>
233 Effect.gen(function* () {
234 const executable = (yield* HostProcess.Environment)[TEST_BROWSER_ENV];
235 if (!executable) return ctx.skip(`Set ${TEST_BROWSER_ENV} to run this test.`);
236 yield* Effect.gen(function* () {
237 const htmlRender = yield* HtmlRender.HtmlRender;
238 const preview = yield* htmlRender.preview({
239 html: [
240 '<!doctype html><html><head></head><body><div id="page" tabindex="0" style="height:300px;background:var(--accent)"></div>',
241 '<img src="/nonexistent/t3-missing.png" hidden>',
242 "<script>",
243 "const root = getComputedStyle(document.documentElement);",
244 'const page = document.getElementById("page"); page.focus();',
245 'const focus = getComputedStyle(page); console.log("focus", focus.outlineWidth, focus.outlineOffset, page.getBoundingClientRect().width, document.documentElement.scrollWidth);',
246 'console.log("ready", 3); console.info(root.getPropertyValue("--font-sans"));',
247 'console.warn(root.getPropertyValue("--background")); console.error("boom");',
248 "</script>",
249 '<script>throw new Error("broken chart");</script>',
250 "</body></html>",
251 ].join(""),
252 width: 400,
253 appearance: "dark",
254 });
255​
256 const png = Buffer.from(preview.png, "base64");
257 expect(png.readUInt32BE(0)).toBe(0x89504e47);
258 expect([png.readUInt32BE(16), png.readUInt32BE(20)]).toEqual([400, 300]);
259 expect(preview).toMatchObject({
260 width: 400,
261 contentHeight: 300,
262 capturedHeight: 300,
263 missingImages: ["/nonexistent/t3-missing.png"],
264 });
265 // Headless Chrome prefers light, so a dark background proves the theme fragment applied.
266 expect(preview.consoleMessages).toEqual(
267 expect.arrayContaining([
268 { level: "log", text: "ready 3" },
269 { level: "log", text: "focus 2px -2px 400 400" },
270 { level: "info", text: HTML_RENDER_MEASURE_FONTS.sans },
271 {
272 level: "warning",
273 text: htmlRenderTheme(T3_CODE_DARK_THEME_COLORS, "dark").variables["--background"],
274 },
275 { level: "error", text: "boom" },
276 {
277 level: "error",
278 text: expect.stringMatching(/^Error: broken chart\n\s+at page\.html:1:\d+$/),
279 },
280 ]),
281 );
282 }).pipe(Effect.provide(layerHtmlRender(executable)));
283 }),
284 30_000,
285 );
286​
287 it.live(
288 "keeps every local file but the page itself out of the browser",
289 (ctx) =>
290 Effect.gen(function* () {
291 const executable = (yield* HostProcess.Environment)[TEST_BROWSER_ENV];
292 if (!executable) return ctx.skip(`Set ${TEST_BROWSER_ENV} to run this test.`);
293 yield* Effect.gen(function* () {
294 const fileSystem = yield* FileSystem.FileSystem;
295 const path = yield* Path.Path;
296 const htmlRender = yield* HtmlRender.HtmlRender;
297 const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-html-files-" });
298 const secret = path.join(directory, "secret.js");
299 yield* fileSystem.writeFileString(secret, 'window.secret = "abc123";');
300 const secretUrl = NodeURL.pathToFileURL(secret).href;
301​
302 const preview = yield* htmlRender.preview({
303 html: [
304 `<script src="${secretUrl}"></script>`,
305 `<iframe src="${secretUrl}" onload="console.log('frame loaded')"></iframe>`,
306 '<script>addEventListener("load", () => console.log("secret:", window.secret ?? "none"));</script>',
307 ].join(""),
308 });
309​
310 const texts = preview.consoleMessages.map((message) => message.text);
311 expect(texts).toContain("secret: none");
312 expect(texts.join(" ")).not.toContain("abc123");
313 }).pipe(Effect.scoped, Effect.provide(layerHtmlRender(executable)));
314 }),
315 30_000,
316 );
317​
318 it.live(
319 "keeps the page off this machine's local network",
320 (ctx) =>
321 Effect.gen(function* () {
322 const executable = (yield* HostProcess.Environment)[TEST_BROWSER_ENV];
323 if (!executable) return ctx.skip(`Set ${TEST_BROWSER_ENV} to run this test.`);
324 const requests: Array<string> = [];
325 const server = yield* Effect.acquireRelease(
326 Effect.callback<NodeHttp.Server>((resume) => {
327 const listening = NodeHttp.createServer((request, response) => {
328 requests.push(`${request.url} ${request.headers["sec-purpose"] ?? ""}`);
329 response.end("<p>LOCAL</p>");
330 });
331 listening.listen(0, "127.0.0.1", () => resume(Effect.succeed(listening)));
332 }),
333 (listening) =>
334 Effect.callback<void>((resume) => {
335 listening.close(() => resume(Effect.void));
336 }),
337 );
338 const datagrams: Array<string> = [];
339 const udp = yield* Effect.acquireRelease(
340 Effect.callback<NodeDgram.Socket>((resume) => {
341 const socket = NodeDgram.createSocket("udp4");
342 socket.on("message", (message) => datagrams.push(message.toString("hex")));
343 socket.bind(0, "127.0.0.1", () => resume(Effect.succeed(socket)));
344 }),
345 (socket) =>
346 Effect.callback<void>((resume) => {
347 socket.close(() => resume(Effect.void));
348 }),
349 );
350 const address = server.address();
351 const origin = `http://127.0.0.1:${typeof address === "object" && address ? address.port : 0}`;
352 const stun = `stun:127.0.0.1:${udp.address().port}`;
353 yield* Effect.gen(function* () {
354 const htmlRender = yield* HtmlRender.HtmlRender;
355 yield* htmlRender.preview({
356 html: [
357 `<img src="${origin}/x.png"><iframe src="${origin}/"></iframe>`,
358 `<script type="speculationrules">{"prefetch":[{"source":"list","urls":["${origin}/prefetch"]}]}</script>`,
359 `<script>fetch("${origin}/").catch(() => {}); new WebSocket("ws${origin.slice(4)}/socket");`,
360 `try { const peer = new RTCPeerConnection({ iceServers: [{ urls: "${stun}" }] });`,
361 `peer.createDataChannel("x"); peer.createOffer().then((offer) => peer.setLocalDescription(offer));`,
362 `} catch {}`,
363 `window.open("${origin}/popup"); location.href = "${origin}/navigate";</script>`,
364 ].join(""),
365 });
366 }).pipe(Effect.provide(layerHtmlRender(executable)));
367 expect(requests).toEqual([]);
368 expect(datagrams).toEqual([]);
369 }).pipe(Effect.scoped),
370 30_000,
371 );
372​
373 it.live(
374 "measures a published page at every client width with a fresh load each",
375 (ctx) =>
376 Effect.gen(function* () {
377 const executable = (yield* HostProcess.Environment)[TEST_BROWSER_ENV];
378 if (!executable) return ctx.skip(`Set ${TEST_BROWSER_ENV} to run this test.`);
379 yield* Effect.gen(function* () {
380 const htmlRender = yield* HtmlRender.HtmlRender;
381 const reference = yield* htmlRender.publish({
382 threadId: ThreadId.make("thread-html-measure"),
383 html: '<div id="chart" style="background:#888"></div><script>document.getElementById("chart").style.height = innerWidth / 2 + "px";</script>',
384 title: "Chart",
385 height: 600,
386 });
387​
388 expect(reference.heights).toEqual(
389 HTML_RENDER_MEASURE_WIDTHS.map((width) => [width, Math.ceil(width / 2)]),
390 );
391 expect(reference.outline).toBe("m0,0,182,91,1");
392 }).pipe(Effect.provide(layerHtmlRender(executable)));
393 }),
394 30_000,
395 );
396});