import { spawn } from "node:child_process"; import { readFile } from "node:fs/promises"; import { createServer, type Server } from "node:http"; import type { AddressInfo } from "node:net"; import path from "node:path"; import { afterEach, describe, expect, it } from "vitest"; import { assertPortUnused, assertServedRelease, labBrowserLaunchOptions, labFeatureRoute, previewArguments, summarizeSamples, } from "../../scripts/lib/lab-performance.ts"; import { NAVIGATION_ROUTES, ROUTE_FEATURE_OWNER, ROUTE_REGISTRY, } from "../../src/features/installed-feature-contracts.ts"; /** * 11-07. The lab performance gate measured once, and measured whatever server * held its port: `vite preview` without `--strictPort` moved elsewhere and the * script never checked which build answered. */ const servers: Server[] = []; afterEach(async () => { await Promise.all( servers.splice(0).map( (server) => new Promise((resolve) => server.close(() => resolve())), ), ); }); async function foreignServer(manifest: unknown): Promise { const server = createServer((_request, response) => { response .writeHead(200, { "content-type": "application/json" }) .end(JSON.stringify(manifest)); }); servers.push(server); await new Promise((resolve) => server.listen(0, "127.0.0.1", () => resolve())); return `http://127.0.0.1:${(server.address() as AddressInfo).port}`; } describe("lab performance gate (11-07)", () => { it("starts the preview server on exactly the requested port", () => { expect(previewArguments(4173)).toEqual([ "pnpm", "preview", "--host", "127.0.0.1", "--port", "4173", "--strictPort", ]); }); it("summarizes repeated runs by their median and keeps every sample", () => { expect(summarizeSamples([326, 1103, 410, 390, 505])).toEqual({ median: 410, min: 326, max: 1103, samples: [326, 1103, 410, 390, 505], }); expect(summarizeSamples([1, 4, 2, 3]).median).toBe(2.5); expect(() => summarizeSamples([])).toThrow(RangeError); }); it("refuses a port that another server already answers on", async () => { const baseUrl = await foreignServer({}); await expect(assertPortUnused(baseUrl)).rejects.toThrow(/another server/u); await expect(assertPortUnused("http://127.0.0.1:9")).resolves.toBeUndefined(); }); it("refuses a server that serves a different build", async () => { const baseUrl = await foreignServer({ buildId: "other", releaseId: "r1" }); await expect( assertServedRelease(baseUrl, { buildId: "measured", releaseId: "r1" }), ).rejects.toThrow(/serves build other\/r1, not the measured measured\/r1/u); await expect( assertServedRelease(baseUrl, { buildId: "other", releaseId: "r1" }), ).resolves.toBeUndefined(); }); it("fails the gate before measuring when its port is taken", async () => { const baseUrl = await foreignServer({ buildId: "other", releaseId: "r1" }); const child = spawn( process.execPath, [path.resolve("scripts/test-performance.ts")], { env: { ...process.env, LAB_PERFORMANCE_PORT: new URL(baseUrl).port }, stdio: ["ignore", "ignore", "pipe"], }, ); let stderr = ""; child.stderr.on("data", (chunk: Buffer) => { stderr += chunk.toString("utf8"); }); const code = await new Promise((resolve) => { const timer = setTimeout(() => child.kill("SIGKILL"), 20_000); child.on("exit", (exitCode) => { clearTimeout(timer); resolve(exitCode); }); }); expect(code).not.toBe(0); expect(stderr).toMatch(/another server holds the port/u); }, 30_000); }); /** * 1105/15-05. The home page's first render added a vertical scrollbar and * pushed the header's right side 15 px (CLS 0.0002 at 1280x720 and * 1366x657). Every gate's Chromium hid scrollbars, the lab included, so no * gate could see it. The page reserves the gutter, and the lab measures with * the scrollbar a Windows or Linux desktop draws. */ describe("lab performance with real scrollbars (1105/15-05)", () => { it("starts Chromium without Playwright's --hide-scrollbars", () => { expect(labBrowserLaunchOptions().ignoreDefaultArgs).toContain("--hide-scrollbars"); }); it("reserves the root scrollbar gutter before the first route renders", async () => { const base = await readFile("src/presentation/styles/theme/base.css", "utf8"); const root = base.match(/:root\s*\{([^}]*)\}/u)?.[1] ?? ""; expect(root).toMatch(/scrollbar-gutter:\s*stable\s*;/u); }); }); /** * 1105/15-04. The lab timed only the platform screen, which loads no feature * code; a feature route's first entry (two request rounds, 406 ms under the * lab conditions) had no gate. The lab now times the first public navigation * route an installed feature owns, with the same clock. */ describe("lab feature route (1105/15-04)", () => { const route = ( routeId: string, navigationOrder: number | null, access: "public" | "session-required" = "public", ) => ({ routeId, path: `/${routeId.toLowerCase()}`, access, title: routeId, navigationLabel: navigationOrder === null ? null : routeId, navigationOrder, }); it("takes the first public navigation route a feature owns", () => { const routes = [ route("APP_HOME", 10), route("EXAMPLES_PLATFORM", 15), route("ORDERS_LIST", 50, "session-required"), route("ORDERS_DETAIL", null), route("GALLERY", 30), route("CATALOG", 20), ]; const owners = { ORDERS_LIST: "orders-feature", ORDERS_DETAIL: "orders-feature", GALLERY: "gallery-feature", CATALOG: "catalog-feature", }; expect(labFeatureRoute(routes, owners)?.routeId).toBe("CATALOG"); expect(labFeatureRoute(routes, { ORDERS_LIST: "orders-feature" })).toBeNull(); expect(labFeatureRoute(routes, {})).toBeNull(); }); it("finds one in the installed registry while a feature has a public screen", () => { const selected = labFeatureRoute(Object.values(ROUTE_REGISTRY), ROUTE_FEATURE_OWNER); const publicFeatureRoutes = NAVIGATION_ROUTES.filter( (definition) => definition.access === "public" && ROUTE_FEATURE_OWNER[definition.routeId] !== undefined, ); expect(selected?.routeId ?? null).toBe(publicFeatureRoutes[0]?.routeId ?? null); if (selected) expect(ROUTE_FEATURE_OWNER[selected.routeId]).toEqual(expect.any(String)); }); });