import { test, expect } from "@playwright/test"; import * as http from "http"; import * as fs from "fs"; import * as path from "path"; import { readPkgFiles, readTree, buildVolume, bundleMemfsForBrowser, } from "./memfs-volume"; import { FileSystem } from "@servicenow/sdk-build-core"; const ROOT = path.resolve(__dirname, "../.."); const DIST_BROWSER = path.join(ROOT, "dist/browser"); const FIXTURES = path.join(__dirname, "fixtures"); const MIME: Record = { ".js": "application/javascript", ".mjs": "application/javascript", ".wasm": "application/wasm", ".html": "text/html", ".json": "application/json", ".css": "text/css", }; const HARNESS_HTML = ` Browser Build Test
`; // --------------------------------------------------------------------------- // Static file server — serves the isomorphic-rollup browser build + harness // --------------------------------------------------------------------------- function startServer( memfsBundle: string, ): Promise<{ server: http.Server; port: number }> { return new Promise((resolve) => { const server = http.createServer((req, res) => { const url = req.url || "/"; if (url === "/" || url === "/harness.html") { res.writeHead(200, { "Content-Type": "text/html" }); res.end(HARNESS_HTML); return; } if (url === "/memfs.js") { res.writeHead(200, { "Content-Type": "application/javascript" }); res.end(memfsBundle); return; } // Serve from dist/browser/ const safePath = path.normalize(url).replace(/^(\.\.(\/|\\|$))+/, ""); const filePath = path.join(DIST_BROWSER, safePath); try { const content = fs.readFileSync(filePath); const ext = path.extname(filePath); res.writeHead(200, { "Content-Type": MIME[ext] || "application/octet-stream", }); res.end(content); } catch { res.writeHead(404); res.end("Not found"); } }); server.listen(0, () => { const addr = server.address(); const port = typeof addr === "object" ? addr!.port : 0; resolve({ server, port }); }); }); } // --------------------------------------------------------------------------- // Test // --------------------------------------------------------------------------- let server: http.Server; let baseUrl: string; test.beforeAll(async () => { const memfsBundle = await bundleMemfsForBrowser(); const info = await startServer(memfsBundle); server = info.server; baseUrl = `http://localhost:${info.port}`; }); test.afterAll(async () => { await new Promise((resolve) => server.close(() => resolve())); }); test("builds and renders a React app from memfs in the browser", async ({ page, }) => { const volume = buildVolume({ // App source fixtures ...readTree(path.join(FIXTURES, "src"), "/src"), // React distributables ...readPkgFiles("react", ["*.js", "cjs/*.js", "package.json"]), // React DOM distributables ...readPkgFiles("react-dom", ["*.js", "cjs/*.js", "package.json"]), // Scheduler (react-dom dependency) ...readPkgFiles("scheduler", ["*.js", "cjs/*.js", "package.json"]), }); await page.goto(`${baseUrl}/harness.html`); // Run the entire build inside the browser using the isomorphic-rollup // browser bundle and a simple in-memory filesystem seeded from the volume. const buildError = await page.evaluate( async (vol: Record) => { try { // --------------------------------------------------------------- // Import memfs and isomorphic-rollup browser builds // --------------------------------------------------------------- // @ts-expect-error — served at runtime by the test harness const { Volume } = (await import("/memfs.js")) .default as typeof import("memfs"); // @ts-expect-error — served at runtime by the test harness const { rollup, swc, sass, nodeResolve, commonjs, replace } = (await import("/index.js")) as typeof import("@servicenow/isomorphic-rollup"); // --------------------------------------------------------------- // Create the memfs from the serialized volume // --------------------------------------------------------------- const memfs = Volume.fromJSON(vol); // --------------------------------------------------------------- // Build // --------------------------------------------------------------- const bundle = await rollup({ fs: memfs as FileSystem, input: "/src/index.jsx", plugins: [ replace({ "process.env.NODE_ENV": "'production'", preventAssignment: true, }), sass({ insert: true }), nodeResolve({ rootDir: "/", browser: true, extensions: [".mjs", ".js", ".jsx", ".json", ".node"], }), swc({ swc: { jsc: { parser: { jsx: true, syntax: "ecmascript" }, }, }, }), commonjs({ rootDir: "/" }), ], }); const { output } = await bundle.generate({ format: "iife", inlineDynamicImports: true, }); // --------------------------------------------------------------- // Inject the built bundle into the page // --------------------------------------------------------------- const script = document.createElement("script"); script.textContent = output[0].code; document.body.appendChild(script); return null; } catch (err: any) { return { message: err.message, stack: err.stack }; } }, volume, ); // Fail early with a clear message if the build errored if (buildError) { throw new Error( `Browser build failed: ${buildError.message}\n${buildError.stack}`, ); } // --------------------------------------------------------------- // Interact with the rendered React app // --------------------------------------------------------------- // Heading rendered await expect(page.locator("h1")).toHaveText("Browser Build Test"); // Counter starts at 0 const count = page.getByTestId("count"); await expect(count).toHaveText("0"); // Increment twice await page.getByTestId("increment").click(); await expect(count).toHaveText("1"); await page.getByTestId("increment").click(); await expect(count).toHaveText("2"); // Decrement once await page.getByTestId("decrement").click(); await expect(count).toHaveText("1"); // Text input echoes const input = page.getByTestId("text-input"); await input.fill("hello world"); await expect(page.getByTestId("echo")).toHaveText("Echo: hello world"); // CSS was applied — verify computed styles from styles.css const appStyles = await page.locator(".app").evaluate((el) => { const s = getComputedStyle(el); return { fontFamily: s.fontFamily, maxWidth: s.maxWidth }; }); expect(appStyles.fontFamily).toContain("sans-serif"); expect(appStyles.maxWidth).toBe("400px"); const counterStyles = await page.locator(".counter").evaluate((el) => { const s = getComputedStyle(el); return { display: s.display, gap: s.gap }; }); expect(counterStyles.display).toBe("flex"); expect(counterStyles.gap).toBe("16px"); // 1rem = 16px });