Open History to see the last commit
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
57/**
58 * A stand-in browser that reads T3's first command off its debugging pipe,
59 * then runs `exit`. Reading it first keeps the pipe from resetting.
60 */
61const exitingBrowser = (exit: string) =>
62 Effect.gen(function* () {
63 const fileSystem = yield* FileSystem.FileSystem;
64 const path = yield* Path.Path;
65 const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-exiting-browser-" });
66 const executable = path.join(directory, "chrome-headless-shell");
67 yield* fileSystem.writeFileString(
68 executable,
69 [
70 `#!${process.execPath}`,
71 `new (process.getBuiltinModule("node:net").Socket)({ fd: 3 }).on("data", (chunk) => { if (chunk.includes(0)) { ${exit} } });`,
72 ].join("\n"),
73 );
74 yield* fileSystem.chmod(executable, 0o755);
75 return executable;
76 });
77
78const previewError = (executable: string) =>
79 Effect.gen(function* () {
80 const htmlRender = yield* HtmlRender.HtmlRender;
81 return yield* htmlRender.preview({ html: "<p>x</p>" }).pipe(Effect.flip);
82 }).pipe(Effect.provide(layerHtmlRender(executable)));
83
84describe("HtmlRender", () => {
85 it.effect("inlines local images by absolute path and leaves URLs and relative paths alone", () =>
86 Effect.gen(function* () {
87 const fileSystem = yield* FileSystem.FileSystem;
88 const path = yield* Path.Path;
89 const htmlRender = yield* HtmlRender.HtmlRender;
90 const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-html-images-" });
91 const png = path.join(directory, "shot.png");
92 const svg = path.join(directory, "logo.svg");
93 yield* fileSystem.writeFile(png, PNG_BYTES);
94 yield* fileSystem.writeFileString(svg, "<svg/>");
95 const kept = [
96 "https://example.com/a.png",
97 "//cdn.example.com/b.png",
98 "./c.png",
99 "data:image/png;base64,AAAA",
100 ];
101
102 const prepared = yield* htmlRender.prepare(
103 [
104 "<!doctype html><html><head><title>Shots</title></head><body>",
105 `<img src="${png}"><div style="background:url(${svg})"></div>`,
106 `<script>const shots = ['${png}', \`${svg}\`];</script>`,
107 ...kept.map((src) => `<img src="${src}">`),
108 "</body></html>",
109 ].join(""),
110 );
111
112 const pngUri = `data:image/png;base64,${Base64.encode(PNG_BYTES)}`;
113 const svgUri = `data:image/svg+xml;base64,${Base64.encode("<svg/>")}`;
114 expect(prepared).toContain(`<img src="${pngUri}">`);
115 expect(prepared).toContain(`url(${svgUri})`);
116 expect(prepared).toContain(`['${pngUri}', \`${svgUri}\`]`);
117 expect(prepared).not.toContain(directory);
118 for (const src of kept) expect(prepared).toContain(`<img src="${src}">`);
119 expect(prepared.indexOf("<head>")).toBeLessThan(prepared.indexOf('<style id="t3-theme">'));
120 expect(prepared.indexOf('<style id="t3-theme">')).toBeLessThan(prepared.indexOf("<title>"));
121 }).pipe(Effect.provide(layerTest)),
122 );
123
124 it.effect("inlines an SVG behind processing instructions and a doctype subset", () =>
125 Effect.gen(function* () {
126 const fileSystem = yield* FileSystem.FileSystem;
127 const path = yield* Path.Path;
128 const htmlRender = yield* HtmlRender.HtmlRender;
129 const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-html-images-" });
130 const svg = path.join(directory, "styled.svg");
131 const source = [
132 '<?xml version="1.0"?>',
133 '<?xml-stylesheet href="theme.css"?>',
134 '<!DOCTYPE svg [ <!ENTITY fill "red"> ]>',
135 '<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32"/>',
136 ].join("\n");
137 yield* fileSystem.writeFileString(svg, source);
138
139 const prepared = yield* htmlRender.prepare(`<img src="${svg}">`);
140
141 expect(prepared).toContain(`data:image/svg+xml;base64,${Base64.encode(source)}`);
142 }).pipe(Effect.provide(layerTest)),
143 );
144
145 it.effect("lists every local image it cannot read", () =>
146 Effect.gen(function* () {
147 const fileSystem = yield* FileSystem.FileSystem;
148 const path = yield* Path.Path;
149 const htmlRender = yield* HtmlRender.HtmlRender;
150 const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-html-images-" });
151 const folder = path.join(directory, "folder.png");
152 yield* fileSystem.makeDirectory(folder);
153 const missing = path.join(directory, "missing.jpg");
154 const secret = path.join(directory, "secret.png");
155 yield* fileSystem.writeFileString(secret, "API_KEY=abc123");
156 const report = path.join(directory, "report.svg");
157 yield* fileSystem.writeFileString(report, "<!doctype html><body><svg></svg>API_KEY=abc123");
158 const config = path.join(directory, "config.svg");
159 yield* fileSystem.writeFileString(
160 config,
161 '<!DOCTYPE config [<!ENTITY a "a"><!ENTITY b "]><svg/>">]><config>API_KEY=abc123</config>',
162 );
163 const stalling = path.join(directory, "stalling.svg");
164 yield* fileSystem.writeFileString(stalling, `${"<?p?>".repeat(40)}<config><svg/></config>`);
165 const unclosed = path.join(directory, "unclosed.svg");
166 yield* fileSystem.writeFileString(unclosed, '<!DOCTYPE svg [<!ENTITY a "x><svg/>');
167 const upper = path.join(directory, "upper.svg");
168 yield* fileSystem.writeFileString(upper, "<SVG/>API_KEY=abc123");
169 const longer = path.join(directory, "longer.svg");
170 yield* fileSystem.writeFileString(longer, "<svg\u00e9/>API_KEY=abc123");
171
172 const error = yield* htmlRender
173 .prepare(
174 `<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}">`,
175 )
176 .pipe(Effect.flip);
177
178 expect(error).toBeInstanceOf(HtmlRender.HtmlRenderImagesNotFoundError);
179 expect(error._tag === "HtmlRenderImagesNotFoundError" && error.paths).toEqual([
180 missing,
181 folder,
182 "C:\\nope\\shot.webp",
183 secret,
184 report,
185 config,
186 stalling,
187 unclosed,
188 upper,
189 longer,
190 ]);
191 }).pipe(Effect.provide(layerTest)),
192 );
193
194 it.effect("publishes the prepared page as an html thread attachment", () =>
195 Effect.gen(function* () {
196 const fileSystem = yield* FileSystem.FileSystem;
197 const config = yield* ServerConfig.ServerConfig;
198 const htmlRender = yield* HtmlRender.HtmlRender;
199
200 const reference = yield* htmlRender.publish({
201 threadId: ThreadId.make("thread-html-render"),
202 html: "<p>Quarterly revenue</p>",
203 title: " Revenue ",
204 height: 9_000,
205 });
206
207 expect(reference).toEqual({
208 attachmentId: expect.any(String),
209 title: "Revenue",
210 height: 2_000,
211 });
212 const stored = resolveAttachmentPathById({
213 attachmentsDir: config.attachmentsDir,
214 attachmentId: reference.attachmentId,
215 });
216 expect(stored?.endsWith(".html")).toBe(true);
217 const html = yield* fileSystem.readFileString(stored ?? "");
218 expect(html).toContain('<style id="t3-theme">');
219 expect(html).toContain("<p>Quarterly revenue</p>");
220 }).pipe(Effect.provide(layerTest)),
221 );
222
223 it.effect("removes the page when publishing is interrupted", () =>
224 Effect.gen(function* () {
225 const measuring = yield* Deferred.make<void>();
226 yield* Effect.gen(function* () {
227 const fileSystem = yield* FileSystem.FileSystem;
228 const config = yield* ServerConfig.ServerConfig;
229 const htmlRender = yield* HtmlRender.HtmlRender;
230 const storedPages = fileSystem
231 .readDirectory(config.attachmentsDir, { recursive: true })
232 .pipe(Effect.map((names) => names.filter((name) => name.endsWith(".html"))));
233
234 const publishing = yield* htmlRender
235 .publish({
236 threadId: ThreadId.make("thread-html-cancel"),
237 html: "<p>x</p>",
238 title: "X",
239 height: 200,
240 })
241 .pipe(Effect.forkChild);
242 yield* Deferred.await(measuring);
243 expect(yield* storedPages).toHaveLength(1);
244 yield* Fiber.interrupt(publishing);
245 expect(yield* storedPages).toEqual([]);
246 }).pipe(
247 Effect.provide(
248 layerHtmlRender(
249 undefined,
250 Deferred.succeed(measuring, undefined).pipe(Effect.andThen(Effect.never)),
251 ),
252 ),
253 );
254 }),
255 );
256
257 describe.skipIf(HostProcess.Platform.defaultValue() === "win32")(
258 "when the browser exits before rendering",
259 () => {
260 it.live("reports its exit code and keeps what it printed out of the message", () =>
261 Effect.gen(function* () {
262 const executable = yield* exitingBrowser(
263 `process.stderr.write("[WARNING:bus.cc] Failed to connect to the bus\\n[FATAL:shared_memory.cc] Check failed: /dev/shm is not writable\\n"); process.exit(3);`,
264 );
265
266 const error = yield* previewError(executable);
267
268 expect(error.message).toBe(
269 "Headless Chrome could not render the page: the browser exited unexpectedly (exit code 3).",
270 );
271 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
272 );
273
274 it.live("reports the signal that ended it", () =>
275 Effect.gen(function* () {
276 const executable = yield* exitingBrowser(`process.kill(process.pid, "SIGKILL");`);
277
278 const error = yield* previewError(executable);
279
280 expect(error.message).toBe(
281 "Headless Chrome could not render the page: the browser exited unexpectedly (signal SIGKILL).",
282 );
283 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
284 );
285 },
286 );
287
288 it.live(
289 "screenshots the page in headless Chrome with the requested theme and every console level",
290 (ctx) =>
291 Effect.gen(function* () {
292 const executable = (yield* HostProcess.Environment)[TEST_BROWSER_ENV];
293 if (!executable) return ctx.skip(`Set ${TEST_BROWSER_ENV} to run this test.`);
294 yield* Effect.gen(function* () {
295 const htmlRender = yield* HtmlRender.HtmlRender;
296 const preview = yield* htmlRender.preview({
297 html: [
298 '<!doctype html><html><head></head><body><div id="page" tabindex="0" style="height:300px;background:var(--accent)"></div>',
299 '<img src="/nonexistent/t3-missing.png" hidden>',
300 "<script>",
301 "const root = getComputedStyle(document.documentElement);",
302 'const page = document.getElementById("page"); page.focus();',
303 'const focus = getComputedStyle(page); console.log("focus", focus.outlineWidth, focus.outlineOffset, page.getBoundingClientRect().width, document.documentElement.scrollWidth);',
304 'console.log("ready", 3); console.info(root.getPropertyValue("--font-sans"));',
305 'console.warn(root.getPropertyValue("--background")); console.error("boom");',
306 "</script>",
307 '<script>throw new Error("broken chart");</script>',
308 "</body></html>",
309 ].join(""),
310 width: 400,
311 appearance: "dark",
312 });
313
314 const png = Buffer.from(preview.png, "base64");
315 expect(png.readUInt32BE(0)).toBe(0x89504e47);
316 expect([png.readUInt32BE(16), png.readUInt32BE(20)]).toEqual([400, 300]);
317 expect(preview).toMatchObject({
318 width: 400,
319 contentHeight: 300,
320 capturedHeight: 300,
321 missingImages: ["/nonexistent/t3-missing.png"],
322 });
323 // Headless Chrome prefers light, so a dark background proves the theme fragment applied.
324 expect(preview.consoleMessages).toEqual(
325 expect.arrayContaining([
326 { level: "log", text: "ready 3" },
327 { level: "log", text: "focus 2px -2px 400 400" },
328 { level: "info", text: HTML_RENDER_MEASURE_FONTS.sans },
329 {
330 level: "warning",
331 text: htmlRenderTheme(T3_CODE_DARK_THEME_COLORS, "dark").variables["--background"],
332 },
333 { level: "error", text: "boom" },
334 {
335 level: "error",
336 text: expect.stringMatching(/^Error: broken chart\n\s+at page\.html:1:\d+$/),
337 },
338 ]),
339 );
340 }).pipe(Effect.provide(layerHtmlRender(executable)));
341 }),
342 30_000,
343 );
344
345 it.live(
346 "keeps every local file but the page itself out of the browser",
347 (ctx) =>
348 Effect.gen(function* () {
349 const executable = (yield* HostProcess.Environment)[TEST_BROWSER_ENV];
350 if (!executable) return ctx.skip(`Set ${TEST_BROWSER_ENV} to run this test.`);
351 yield* Effect.gen(function* () {
352 const fileSystem = yield* FileSystem.FileSystem;
353 const path = yield* Path.Path;
354 const htmlRender = yield* HtmlRender.HtmlRender;
355 const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-html-files-" });
356 const secret = path.join(directory, "secret.js");
357 yield* fileSystem.writeFileString(secret, 'window.secret = "abc123";');
358 const secretUrl = NodeURL.pathToFileURL(secret).href;
359
360 const preview = yield* htmlRender.preview({
361 html: [
362 `<script src="${secretUrl}"></script>`,
363 `<iframe src="${secretUrl}" onload="console.log('frame loaded')"></iframe>`,
364 '<script>addEventListener("load", () => console.log("secret:", window.secret ?? "none"));</script>',
365 ].join(""),
366 });
367
368 const texts = preview.consoleMessages.map((message) => message.text);
369 expect(texts).toContain("secret: none");
370 expect(texts.join(" ")).not.toContain("abc123");
371 }).pipe(Effect.scoped, Effect.provide(layerHtmlRender(executable)));
372 }),
373 30_000,
374 );
375
376 it.live(
377 "keeps the page off this machine's local network",
378 (ctx) =>
379 Effect.gen(function* () {
380 const executable = (yield* HostProcess.Environment)[TEST_BROWSER_ENV];
381 if (!executable) return ctx.skip(`Set ${TEST_BROWSER_ENV} to run this test.`);
382 const requests: Array<string> = [];
383 const server = yield* Effect.acquireRelease(
384 Effect.callback<NodeHttp.Server>((resume) => {
385 const listening = NodeHttp.createServer((request, response) => {
386 requests.push(`${request.url} ${request.headers["sec-purpose"] ?? ""}`);
387 response.end("<p>LOCAL</p>");
388 });
389 listening.listen(0, "127.0.0.1", () => resume(Effect.succeed(listening)));
390 }),
391 (listening) =>
392 Effect.callback<void>((resume) => {
393 listening.close(() => resume(Effect.void));
394 }),
395 );
396 const datagrams: Array<string> = [];
397 const udp = yield* Effect.acquireRelease(
398 Effect.callback<NodeDgram.Socket>((resume) => {
399 const socket = NodeDgram.createSocket("udp4");
400 socket.on("message", (message) => datagrams.push(message.toString("hex")));
401 socket.bind(0, "127.0.0.1", () => resume(Effect.succeed(socket)));
402 }),
403 (socket) =>
404 Effect.callback<void>((resume) => {
405 socket.close(() => resume(Effect.void));
406 }),
407 );
408 const address = server.address();
409 const origin = `http://127.0.0.1:${typeof address === "object" && address ? address.port : 0}`;
410 const stun = `stun:127.0.0.1:${udp.address().port}`;
411 yield* Effect.gen(function* () {
412 const htmlRender = yield* HtmlRender.HtmlRender;
413 yield* htmlRender.preview({
414 html: [
415 `<img src="${origin}/x.png"><iframe src="${origin}/"></iframe>`,
416 `<script type="speculationrules">{"prefetch":[{"source":"list","urls":["${origin}/prefetch"]}]}</script>`,
417 `<script>fetch("${origin}/").catch(() => {}); new WebSocket("ws${origin.slice(4)}/socket");`,
418 `try { const peer = new RTCPeerConnection({ iceServers: [{ urls: "${stun}" }] });`,
419 `peer.createDataChannel("x"); peer.createOffer().then((offer) => peer.setLocalDescription(offer));`,
420 `} catch {}`,
421 `window.open("${origin}/popup"); location.href = "${origin}/navigate";</script>`,
422 ].join(""),
423 });
424 }).pipe(Effect.provide(layerHtmlRender(executable)));
425 expect(requests).toEqual([]);
426 expect(datagrams).toEqual([]);
427 }).pipe(Effect.scoped),
428 30_000,
429 );
430
431 it.live(
432 "measures a published page at every client width with a fresh load each",
433 (ctx) =>
434 Effect.gen(function* () {
435 const executable = (yield* HostProcess.Environment)[TEST_BROWSER_ENV];
436 if (!executable) return ctx.skip(`Set ${TEST_BROWSER_ENV} to run this test.`);
437 yield* Effect.gen(function* () {
438 const htmlRender = yield* HtmlRender.HtmlRender;
439 const reference = yield* htmlRender.publish({
440 threadId: ThreadId.make("thread-html-measure"),
441 html: '<div id="chart" style="background:#888"></div><script>document.getElementById("chart").style.height = innerWidth / 2 + "px";</script>',
442 title: "Chart",
443 height: 600,
444 });
445
446 expect(reference.heights).toEqual(
447 HTML_RENDER_MEASURE_WIDTHS.map((width) => [width, Math.ceil(width / 2)]),
448 );
449 }).pipe(Effect.provide(layerHtmlRender(executable)));
450 }),
451 30_000,
452 );
453});