Skip to content

Playwright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API.

chore(watch): extend Vite HMR to html-reporter and trace viewer (#40402)

Pavel Feldman4adbb8ac1cf5
diff --git a/packages/playwright-core/src/server/trace/viewer/traceViewer.ts b/packages/playwright-core/src/server/trace/viewer/traceViewer.ts
index fa324e1b1e..95b0db0794 100644
--- a/packages/playwright-core/src/server/trace/viewer/traceViewer.ts
+++ b/packages/playwright-core/src/server/trace/viewer/traceViewer.ts
@@ -33,6 +33,10 @@ import type { BrowserType } from '../../browserType';
import type { Page } from '../../page';
import type http from 'http';
+// HMR: build-time flag — `true` in watch builds, `false` in release. Mirror of
+// the one in dashboardApp.ts; esbuild's `define` replaces both.
+declare const __PW_HMR__: boolean;
+
export type TraceViewerServerOptions = {
host?: string;
port?: number;
@@ -82,35 +86,62 @@ function validateTraceUrlOrPath(traceFileOrUrl: string | undefined): string | un
export async function startTraceViewerServer(options?: TraceViewerServerOptions): Promise<HttpServer> {
const server = new HttpServer();
- server.routePrefix('/trace', (request, response) => {
+
+ const serveTraceDataRoute = (request: http.IncomingMessage, response: http.ServerResponse, relativePath: string): boolean => {
+ if (!relativePath.startsWith('/file'))
+ return false;
const url = new URL('http://localhost' + request.url!);
- const relativePath = url.pathname.slice('/trace'.length);
- if (relativePath.startsWith('/file')) {
- try {
- const filePath = url.searchParams.get('path')!;
- if (fs.existsSync(filePath))
- return server.serveFile(request, response, url.searchParams.get('path')!);
-
- // If .json is requested, we'll synthesize it for zip-less operation.
- if (filePath.endsWith('.json')) {
- const fullPrefix = filePath.substring(0, filePath.length - '.json'.length);
- // Live traces are stored in the common artifacts directory. Trace files
- // corresponding to a particular test, all have the same unique prefix.
- return sendTraceDescriptor(response, path.dirname(fullPrefix), path.basename(fullPrefix));
- }
-
- // If 'trace.dir' is requested, return all trace files inside.
- if (filePath.endsWith(tracesDirMarker))
- return sendTraceDescriptor(response, path.dirname(filePath));
- } catch {
+ try {
+ const filePath = url.searchParams.get('path')!;
+ if (fs.existsSync(filePath))
+ return server.serveFile(request, response, filePath);
+
+ // If .json is requested, we'll synthesize it for zip-less operation.
+ if (filePath.endsWith('.json')) {
+ const fullPrefix = filePath.substring(0, filePath.length - '.json'.length);
+ // Live traces are stored in the common artifacts directory. Trace files
+ // corresponding to a particular test, all have the same unique prefix.
+ return sendTraceDescriptor(response, path.dirname(fullPrefix), path.basename(fullPrefix));
}
- response.statusCode = 404;
- response.end();
- return true;
+
+ // If 'trace.dir' is requested, return all trace files inside.
+ if (filePath.endsWith(tracesDirMarker))
+ return sendTraceDescriptor(response, path.dirname(filePath));
+ } catch {
}
- const absolutePath = path.join(libPath('vite', 'traceViewer'), ...relativePath.split('/'));
- return server.serveFile(request, response, absolutePath);
- });
+ response.statusCode = 404;
+ response.end();
+ return true;
+ };
+
+ // HMR: watch builds serve the trace viewer (incl. UI mode) through an
+ // embedded Vite dev server. Release builds always take the static branch
+ // (the dev-server arm is DCE'd). Set PW_HMR_STATIC=1 during watch to
+ // exercise the bundled output. The service worker at /trace/sw.bundle.js
+ // still ships from the separate vite.sw.config.ts build — serve it from lib.
+ if (__PW_HMR__ && process.env.PW_HMR_STATIC !== '1') {
+ const traceViewerRoot = path.resolve(__dirname, '..', '..', 'trace-viewer');
+ const devServer = await server.createViteDevServer({ root: traceViewerRoot, base: '/trace/' });
+ server.routePrefix('/trace', (request, response) => {
+ const url = new URL('http://localhost' + request.url!);
+ const relativePath = url.pathname.slice('/trace'.length);
+ if (relativePath.startsWith('/file'))
+ return serveTraceDataRoute(request, response, relativePath);
+ if (relativePath === '/sw.bundle.js')
+ return server.serveFile(request, response, path.join(libPath('vite', 'traceViewer'), 'sw.bundle.js'));
+ devServer.middlewares(request, response, HttpServer.notFoundFallback(response));
+ return true;
+ });
+ } else {
+ server.routePrefix('/trace', (request, response) => {
+ const url = new URL('http://localhost' + request.url!);
+ const relativePath = url.pathname.slice('/trace'.length);
+ if (relativePath.startsWith('/file'))
+ return serveTraceDataRoute(request, response, relativePath);
+ const absolutePath = path.join(libPath('vite', 'traceViewer'), ...relativePath.split('/'));
+ return server.serveFile(request, response, absolutePath);
+ });
+ }
const transport = options?.transport || (options?.isServer ? new StdinServer() : undefined);
if (transport)
diff --git a/packages/playwright-core/src/tools/dashboard/dashboardApp.ts b/packages/playwright-core/src/tools/dashboard/dashboardApp.ts
index b1374ce983..4d9d6fa57f 100644
--- a/packages/playwright-core/src/tools/dashboard/dashboardApp.ts
+++ b/packages/playwright-core/src/tools/dashboard/dashboardApp.ts
@@ -35,7 +35,7 @@ import type { AnnotationData } from '@dashboard/dashboardChannel';
// HMR: build-time flag — `true` in watch builds, `false` in release. esbuild
// replaces the identifier via `define`, so the static branch pays zero runtime
// cost and the dev-server code (incl. `import('vite')`) is DCE'd in release.
-declare const __PW_DASHBOARD_HMR__: boolean;
+declare const __PW_HMR__: boolean;
type DashboardServer = {
url: string;
@@ -82,8 +82,8 @@ async function startDashboardServer(options: DashboardOptions): Promise<Dashboar
// HMR: watch builds serve the dashboard through an embedded Vite dev server
// so edits to packages/dashboard/src/* reload live. Release builds always
// take the static branch (the dev-server arm is DCE'd). Set
- // PW_DASHBOARD_STATIC=1 during watch to exercise the bundled output.
- if (__PW_DASHBOARD_HMR__ && process.env.PW_DASHBOARD_STATIC !== '1')
+ // PW_HMR_STATIC=1 during watch to exercise the bundled output.
+ if (__PW_HMR__ && process.env.PW_HMR_STATIC !== '1')
await attachDashboardDevServer(httpServer);
else
attachDashboardStaticServer(httpServer, dashboardDir);
@@ -141,27 +141,9 @@ function attachDashboardStaticServer(httpServer: HttpServer, dashboardDir: strin
// HMR begin: dev-mode branch — wires a Vite dev server into HttpServer.
async function attachDashboardDevServer(httpServer: HttpServer) {
const dashboardRoot = path.resolve(__dirname, '..', '..', 'dashboard');
- const loadVite = new Function('return import("vite")') as () => Promise<typeof import('vite')>;
- const vite = await loadVite();
- const devServer = await vite.createServer({
- root: dashboardRoot,
- configFile: path.join(dashboardRoot, 'vite.config.ts'),
- server: {
- middlewareMode: true,
- // HMR: dedicated path so this websocket does not collide with the
- // dashboard IPC websocket HttpServer owns at /ws.
- hmr: { path: '/__vite_hmr', server: httpServer.server() },
- },
- appType: 'spa',
- clearScreen: false,
- });
+ const devServer = await httpServer.createViteDevServer({ root: dashboardRoot });
httpServer.routePrefix('/', (request: http.IncomingMessage, response: http.ServerResponse) => {
- devServer.middlewares(request, response, () => {
- if (!response.headersSent) {
- response.statusCode = 404;
- response.end();
- }
- });
+ devServer.middlewares(request, response, HttpServer.notFoundFallback(response));
return true;
});
}
diff --git a/packages/playwright/src/reporters/html.ts b/packages/playwright/src/reporters/html.ts
index 29df729b48..c319c3b787 100644
--- a/packages/playwright/src/reporters/html.ts
+++ b/packages/playwright/src/reporters/html.ts
@@ -27,9 +27,14 @@ import { MultiMap } from '@isomorphic/multimap';
import { calculateSha1 } from '@utils/crypto';
import { copyFileAndMakeWritable, removeFolders, sanitizeForFilePath, toPosixPath } from '@utils/fileUtils';
import { getPackageManagerExecCommand } from '@utils/env';
-import { serveFolder } from '@utils/httpServer';
+import { HttpServer, serveFolder } from '@utils/httpServer';
import { gracefullyProcessExitDoNotHang } from '@utils/processLauncher';
+// HMR: build-time flag — `true` in watch builds, `false` in release. esbuild's
+// `define` in the runner bundle replaces this so the dev-server code (incl.
+// `import('vite')`) is DCE'd in release builds.
+declare const __PW_HMR__: boolean;
+
import { CommonReporterOptions, formatError, formatResultFailure, internalScreen } from './base';
import * as babel from '../transform/babelBundle';
import { resolveReporterOutputPath, stripAnsiEscapes } from '../util';
@@ -222,7 +227,13 @@ export async function showHTMLReport(reportFolder: string | undefined, host: str
gracefullyProcessExitDoNotHang(1);
return;
}
- const server = serveFolder(folder);
+ // HMR: watch builds serve the html-reporter through an embedded Vite dev
+ // server so edits to packages/html-reporter/src/* reload live. Release
+ // builds always take the static branch (the dev-server arm is DCE'd).
+ // Set PW_HMR_STATIC=1 during watch to exercise the bundled output.
+ const server = (__PW_HMR__ && process.env.PW_HMR_STATIC !== '1')
+ ? await serveHtmlReportWithHMR(folder)
+ : serveFolder(folder);
await server.start({ port, host, preferredPort: port ? undefined : 9323 });
let url = server.urlPrefix('human-readable');
writeLine('');
@@ -234,6 +245,47 @@ export async function showHTMLReport(reportFolder: string | undefined, host: str
await new Promise(() => {});
}
+// HMR begin: dev-mode branch — mounts a Vite dev server for the html-reporter
+// source at `/` while still serving the generated attachments (and the bundled
+// trace-viewer copy under /trace/) from the output folder. The report's data
+// payload lives in a <template id="playwrightReportBase64"> tag at the tail of
+// the generated index.html; we extract it and splice it into Vite's
+// transformed HTML so the client still finds it at runtime.
+async function serveHtmlReportWithHMR(folder: string): Promise<HttpServer> {
+ const server = new HttpServer();
+ const reporterRoot = path.resolve(__dirname, '..', '..', '..', 'html-reporter');
+ const devServer = await server.createViteDevServer({ root: reporterRoot });
+ const generatedIndex = await fs.promises.readFile(path.join(folder, 'index.html'), 'utf-8');
+ const templateMatch = /<template id="playwrightReportBase64">[\s\S]*?<\/template>/.exec(generatedIndex);
+ const reportTemplate = templateMatch ? templateMatch[0] : '';
+ const sourceIndex = await fs.promises.readFile(path.join(reporterRoot, 'index.html'), 'utf-8');
+
+ server.routePrefix('/', (request, response) => {
+ const url = new URL('http://localhost' + request.url!);
+ if (url.pathname === '/' || url.pathname === '/index.html') {
+ devServer.transformIndexHtml(url.pathname, sourceIndex).then(html => {
+ const injected = html.replace(/<\/body>/i, `${reportTemplate}</body>`);
+ response.statusCode = 200;
+ response.setHeader('Content-Type', 'text/html; charset=utf-8');
+ response.end(injected);
+ }, () => {
+ response.statusCode = 500;
+ response.end();
+ });
+ return true;
+ }
+ // Serve attachments and the bundled trace-viewer copy from the generated
+ // output folder first, falling through to Vite for source modules.
+ const absolutePath = path.join(folder, ...url.pathname.split('/'));
+ if (absolutePath.startsWith(folder) && server.serveFile(request, response, absolutePath))
+ return true;
+ devServer.middlewares(request, response, HttpServer.notFoundFallback(response));
+ return true;
+ });
+ return server;
+}
+// HMR end
+
type DataMap = Map<string, { testFile: TestFile, testFileSummary: TestFileSummary }>;
class HtmlBuilder {
diff --git a/packages/utils/httpServer.ts b/packages/utils/httpServer.ts
index e3659002a3..ca7599adc5 100644
--- a/packages/utils/httpServer.ts
+++ b/packages/utils/httpServer.ts
@@ -25,6 +25,14 @@ import { createHttpServer, startHttpServer } from './network';
import type http from 'http';
+// Minimal shape of the Vite dev server we rely on. Kept inline so this file
+// doesn't need a type dep on `vite`, which is only available in watch builds.
+export type ViteDevServer = {
+ middlewares: (req: http.IncomingMessage, res: http.ServerResponse, next: (err?: unknown) => void) => void;
+ transformIndexHtml: (url: string, html: string, originalUrl?: string) => Promise<string>;
+ close: () => Promise<void>;
+};
+
export type ServerRouteHandler = (request: http.IncomingMessage, response: http.ServerResponse) => boolean;
export type Transport = {
@@ -103,6 +111,37 @@ export class HttpServer {
return this._wsGuid;
}
+ async createViteDevServer(options: { root: string, base?: string }): Promise<ViteDevServer> {
+ // HMR begin: hide the `vite` import from esbuild so release bundles can
+ // DCE this whole branch without keeping a resolvable module reference.
+ const loadVite = new Function('return import("vite")') as () => Promise<any>;
+ const vite = await loadVite();
+ return await vite.createServer({
+ root: options.root,
+ base: options.base,
+ server: {
+ middlewareMode: true,
+ // Dedicated path so Vite's HMR websocket does not collide with any
+ // websocket HttpServer owns via createWebSocket().
+ hmr: { path: '/__vite_hmr', server: this._server },
+ },
+ appType: 'spa',
+ clearScreen: false,
+ });
+ }
+ // HMR end
+
+ // Vite's middleware `next` callback for the "no middleware matched" case;
+ // emits a 404 only if nothing downstream already responded.
+ static notFoundFallback(response: http.ServerResponse): () => void {
+ return () => {
+ if (!response.headersSent) {
+ response.statusCode = 404;
+ response.end();
+ }
+ };
+ }
+
async start(options: { port?: number, preferredPort?: number, host?: string } = {}): Promise<void> {
assert(!this._started, 'server already started');
this._started = true;
diff --git a/utils/build/build.js b/utils/build/build.js
index de692fd301..de16c98250 100644
--- a/utils/build/build.js
+++ b/utils/build/build.js
@@ -635,11 +635,12 @@ steps.push(new EsbuildStep({
'chromium-bidi/*',
'mitt',
],
- // HMR: baked-in flag that enables the dashboard Vite dev server in watch
- // builds. In release builds it's `false` and esbuild dead-code-eliminates
- // the whole dev-server branch (including the `import('vite')` call).
+ // HMR: baked-in flag that enables the embedded Vite dev server for the
+ // dashboard and trace viewer (incl. UI mode) in watch builds. In release
+ // builds it's `false` and esbuild dead-code-eliminates the whole dev-server
+ // branch (including the `import('vite')` call).
define: {
- __PW_DASHBOARD_HMR__: String(!!watchMode),
+ __PW_HMR__: String(!!watchMode),
},
plugins: [{
name: 'externalize-utilsBundle',
@@ -768,6 +769,11 @@ steps.push(new EsbuildStep({
'../transform/babelBundle',
'../transform/esmLoader',
],
+ // HMR: same flag as coreBundle; enables the html-reporter Vite dev server
+ // in watch builds (reporters/html.ts lives in this bundle).
+ define: {
+ __PW_HMR__: String(!!watchMode),
+ },
plugins: [dynamicImportToRequirePlugin],
}, [filePath('packages/playwright/src')]));
@@ -883,12 +889,16 @@ steps.push(new ProgramStep({
}));
// Build/watch web packages.
-// HMR: in watch mode the dashboard is served by the embedded Vite dev server
-// in dashboardApp.ts, so skip its `vite build --watch` step. Set
-// PW_DASHBOARD_STATIC=1 to keep the watch-build for testing the bundled output.
-const hmrReplacesDashboardBuild = watchMode && process.env.PW_DASHBOARD_STATIC !== '1';
+// HMR: in watch mode the dashboard, html-reporter, and trace viewer (incl. UI
+// mode) are served by embedded Vite dev servers, so skip their
+// `vite build --watch` steps. Set PW_HMR_STATIC=1 to keep the watch builds for
+// testing the bundled output. Recorder is not yet HMR'd. The trace viewer
+// service worker still builds via vite.sw.config.ts above — that step is not
+// in this loop.
+const hmrReplacesWebBuilds = watchMode && process.env.PW_HMR_STATIC !== '1';
+const hmrHandledPackages = new Set(['dashboard', 'html-reporter', 'trace-viewer']);
const webPackages = ['html-reporter', 'recorder', 'trace-viewer', 'dashboard']
- .filter(pkg => !(pkg === 'dashboard' && hmrReplacesDashboardBuild));
+ .filter(pkg => !(hmrReplacesWebBuilds && hmrHandledPackages.has(pkg)));
for (const webPackage of webPackages) {
steps.push(new ProgramStep({
command: 'npx',