Something went wrong. Try again.
Monorepo for the nibling.run platform
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133// Raw connections from an app page to its guest server, the transport under the// WebSocket shim: the page asks the SW for a connection with a MessagePort, the port// travels SW → host → kernel → runtime, and bytes then flow page ↔ runtime directly.// Guest documents get the shim tag first in <head>.import { test, expect, type Frame, type Page } from "@playwright/test";import "./guest";
const SERVER = `const http = require("node:http");const server = http.createServer((req, res) => { if (req.url === "/doc") { const body = "<!doctype html><html><head><title>doc</title></head><body><p id=last>end</p></body></html>"; res.writeHead(200, { "content-type": "text/html; charset=utf-8", "content-length": Buffer.byteLength(body) }); res.end(body); } else if (req.url === "/headless") { res.setHeader("content-type", "text/html"); res.end("<!doctype html><!-- <head> --><p id=p>no head</p><script>window.ran = document.scripts.length</script>"); } else { res.end("plain " + req.method + " " + req.url + " upgrade=" + req.upgrade); }});if (process.argv[2] === "upgrade") server.on("upgrade", (req, socket, head) => { socket.write("HTTP/1.1 101 Switching Protocols\\r\\nUpgrade: test\\r\\nConnection: Upgrade\\r\\n\\r\\n"); socket.write("head:" + head + "|" + req.url + "|" + req.headers["x-probe"] + "|" + (req.socket === socket) + "|"); socket.on("data", (d) => { if (String(d) === "exit") process.exit(0); socket.write("echo:" + d + "|"); }); socket.on("end", () => socket.end("bye"));});server.listen(4600);`;
async function boot(page: Page, argv: string[], path = "doc"): Promise<{ frame: Frame; base: string }> { await page.goto("/demo/fixture.html"); await page.waitForFunction(() => window.__runtime !== undefined, undefined, { timeout: 20_000 }); const base = await page.evaluate(async ({ src, argv }) => { const runtime = window.__runtime!; runtime.writeTree({ "/app/server.cjs": src }); runtime.exec("/app/server.cjs", { argv }); return await runtime.waitForPort(4600); }, { src: SERVER, argv }); await page.evaluate((url) => { const frame = document.createElement("iframe"); frame.id = "app"; frame.src = url; document.body.append(frame); }, base + path); const frame = await (await page.waitForSelector("#app")).contentFrame(); await frame!.waitForLoadState(); return { frame: frame!, base };}
/** Open a connection from the app document, send `chunks`, and record what comes back * until the runtime ends it: text, "<watch>" for the kernel's watch port, "<end>". */function exchange(frame: Frame, path: string, chunks: string[], close = false) { return frame.evaluate(async ({ path, chunks, close }) => { const ch = new MessageChannel(); navigator.serviceWorker.controller!.postMessage({ t: "connect", socket: ch.port2, path, page: location.href }, [ch.port2]); const got: string[] = []; const ended = new Promise<void>((resolve) => { ch.port1.onmessage = (ev) => { const d = ev.data; if (d === null) { got.push("<end>"); resolve(); } else if (d instanceof Uint8Array) { got.push(new TextDecoder().decode(d)); } else { got.push("<watch>"); d.port.onmessage = (w: MessageEvent) => { got.push(`<watch ${w.data.t}>`); resolve(); }; } }; }); for (const c of chunks) ch.port1.postMessage(new TextEncoder().encode(c)); if (close) ch.port1.postMessage(null); await Promise.race([ended, new Promise((r) => setTimeout(r, 5000))]); return got.join(""); }, { path, chunks, close });}
const UPGRADE = "GET /live?q=1 HTTP/1.1\r\nHost: x\r\nX-Probe: yes\r\nConnection: Upgrade\r\nUpgrade: test\r\n\r\nfirst";
test("app documents get the shim first in <head>, with content-length recomputed; fetches stay untouched", async ({ page }) => { const { frame, base } = await boot(page, []); expect(await frame.evaluate(() => [document.head.firstElementChild?.outerHTML, document.getElementById("last")?.textContent])) .toEqual(['<script src="/~/ws-shim.js"></script>', "end"]); expect(await frame.evaluate(async () => { const r = await fetch("/~/ws-shim.js"); return [r.status, r.headers.get("content-type"), r.headers.get("cross-origin-resource-policy")]; })).toEqual([200, "text/javascript; charset=utf-8", "same-origin"]); expect(await page.evaluate(async (url) => (await fetch(url)).text(), base + "doc")) .toBe("<!doctype html><html><head><title>doc</title></head><body><p id=last>end</p></body></html>");
await frame.goto(base + "headless"); expect(await frame.evaluate(() => [document.compatMode, document.head.firstElementChild?.getAttribute("src"), (window as unknown as { ran: number }).ran])) .toEqual(["CSS1Compat", "/~/ws-shim.js", 2]);});
test("a connection reaches the guest's 'upgrade' listener and bytes flow both ways until the end", async ({ page }) => { const { frame } = await boot(page, ["upgrade"]); expect(await exchange(frame, "/live", [UPGRADE, "abc"], true)).toBe( "<watch>HTTP/1.1 101 Switching Protocols\r\nUpgrade: test\r\nConnection: Upgrade\r\n\r\n" + "head:first|/live?q=1|yes|true|echo:abc|bye<end>", );});
test("a process exit reaches every open connection through its watch port", async ({ page }) => { const { frame } = await boot(page, ["upgrade"]); expect(await exchange(frame, "/live", [UPGRADE, "exit"])).toMatch(/^<watch>HTTP\/1\.1 101 .*\|<watch exited>$/s);});
// Byte for byte what Node v24 answers a raw socket with (Date masked): the// connection is kept alive, and ends once the page ends its side.test("with no 'upgrade' listener the request is served as a plain request, as Node does", async ({ page }) => { const { frame } = await boot(page, []); expect((await exchange(frame, "/live", [UPGRADE], true)).replace(/Date: [^\r]+/, "Date: X")).toBe( "<watch>HTTP/1.1 200 OK\r\nDate: X\r\nConnection: keep-alive\r\nKeep-Alive: timeout=5\r\nContent-Length: 33\r\n\r\nplain GET /live?q=1 upgrade=false<end>", );});
test("a port nobody listens on answers 502 and ends", async ({ page }) => { const { frame, base } = await boot(page, []); const other = base.replace("/http/4600/", "/http/4999/") + "live"; const text = "ERR_NIB_NO_LISTENER: nothing is listening on port 4999\n"; expect(await exchange(frame, other, [UPGRADE])).toBe( `HTTP/1.1 502 Bad Gateway\r\ncontent-type: text/plain; charset=utf-8\r\ncontent-length: ${text.length}\r\nconnection: close\r\n\r\n${text}<end>`, );});