Playwright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API.
TypeScript automationchromechromiume2e-testingelectronend-to-end-testingfirefoxjavascriptplaywrighttesttest-automationtestingtesting-toolswebwebkit
chore: build coreBundle (#40074)
Pavel Feldman9a99e0c8c679
diff --git a/.gitignore b/.gitignoreindex 7e5bfb7be1..13ff5dec04 100644--- a/.gitignore+++ b/.gitignore@@ -39,3 +39,4 @@ test-results.eslintcacheplaywright.env/firefox/+.playwright/diff --git a/eslint.config.mjs b/eslint.config.mjsindex 1ef61d5453..98f81595a0 100644--- a/eslint.config.mjs+++ b/eslint.config.mjs@@ -60,6 +60,7 @@ const ignores = ["test-results/","tests/assets/","tests/components/",+ "tests/config/ghaMarkdownReporter.ts","tests/installation/fixture-scripts/","tests/third_party/","utils/",@@ -357,17 +358,65 @@ export default [},},{- files: ["packages/playwright-core/src/tools/**/*.ts"],+ files: ["packages/playwright-core/src/**/*.ts"],+ ignores: [+ "packages/playwright-core/src/entry/**",+ ],rules: {"no-restricted-imports": ["error",{patterns: [{- group: ["**/client", "**/client/**"],- message: "tools/ must not import from client/",+ group: ["**/coreBundle"],+ message: "coreBundle can only be imported from entry/ files. Use direct imports instead.",}],},],+ },+ },+ {+ files: ["packages/playwright-core/src/**/*.ts"],+ ignores: [+ "packages/playwright-core/src/package.ts",+ "packages/playwright-core/src/cli/programWithTestStub.ts",+ ],+ rules: {+ "no-restricted-properties": [+ "error",+ {+ object: "process",+ property: "exit",+ message:+ "Please use gracefullyProcessExitDoNotHang function to exit the process.",+ },+ { object: "process", property: "stdout" },+ { object: "process", property: "stderr" },+ {+ object: "require",+ property: "resolve",+ message: "Use libPath() from package.ts instead of require.resolve.",+ },+ ],+ },+ },+ {+ files: ["packages/playwright-core/src/tools/**/*.ts"],+ rules: {+ "no-restricted-imports": [+ "error",+ {+ patterns: [+ {+ group: ["**/client", "**/client/**"],+ message: "tools/ must not import from client/",+ },+ {+ group: ["**/coreBundle"],+ message: "coreBundle can only be imported from entry/ files. Use direct imports instead.",+ },+ ],+ },+ ],"no-restricted-syntax": ["error",{diff --git a/packages/playwright-browser-chromium/install.js b/packages/playwright-browser-chromium/install.jsindex 8e42a18b24..d14a7aeba0 100644--- a/packages/playwright-browser-chromium/install.js+++ b/packages/playwright-browser-chromium/install.js@@ -18,7 +18,7 @@ let install;try {if (!require('playwright-core/lib/coreBundle').serverUtils.isLikelyNpxGlobal())- install = require('playwright-core/lib/coreBundle').sever.installBrowsersForNpmInstall;+ install = require('playwright-core/lib/coreBundle').registry.installBrowsersForNpmInstall;} catch (e) {// Dev build, don't install browsers by default.}diff --git a/packages/playwright-browser-firefox/install.js b/packages/playwright-browser-firefox/install.jsindex 561032d644..d53beb1048 100644--- a/packages/playwright-browser-firefox/install.js+++ b/packages/playwright-browser-firefox/install.js@@ -18,7 +18,7 @@ let install;try {if (!require('playwright-core/lib/coreBundle').serverUtils.isLikelyNpxGlobal())- install = require('playwright-core/lib/coreBundle').sever.installBrowsersForNpmInstall;+ install = require('playwright-core/lib/coreBundle').registry.installBrowsersForNpmInstall;} catch (e) {// Dev build, don't install browsers by default.}diff --git a/packages/playwright-browser-webkit/install.js b/packages/playwright-browser-webkit/install.jsindex dbb98b90eb..f4cb8dfcad 100644--- a/packages/playwright-browser-webkit/install.js+++ b/packages/playwright-browser-webkit/install.js@@ -18,7 +18,7 @@ let install;try {if (!require('playwright-core/lib/coreBundle').serverUtils.isLikelyNpxGlobal())- install = require('playwright-core/lib/coreBundle').sever.installBrowsersForNpmInstall;+ install = require('playwright-core/lib/coreBundle').registry.installBrowsersForNpmInstall;} catch (e) {// Dev build, don't install browsers by default.}diff --git a/packages/playwright-chromium/install.js b/packages/playwright-chromium/install.jsindex 8e42a18b24..d14a7aeba0 100644--- a/packages/playwright-chromium/install.js+++ b/packages/playwright-chromium/install.js@@ -18,7 +18,7 @@ let install;try {if (!require('playwright-core/lib/coreBundle').serverUtils.isLikelyNpxGlobal())- install = require('playwright-core/lib/coreBundle').sever.installBrowsersForNpmInstall;+ install = require('playwright-core/lib/coreBundle').registry.installBrowsersForNpmInstall;} catch (e) {// Dev build, don't install browsers by default.}diff --git a/packages/playwright-core/package.json b/packages/playwright-core/package.jsonindex 8bdc261a4b..24ba58c8b0 100644--- a/packages/playwright-core/package.json+++ b/packages/playwright-core/package.json@@ -27,7 +27,8 @@"./lib/mcpBundle": "./lib/mcpBundle.js","./lib/utilsBundle": "./lib/utilsBundle.js","./lib/zipBundle": "./lib/zipBundle.js",- "./lib/zodBundle": "./lib/zodBundle.js"+ "./lib/zodBundle": "./lib/zodBundle.js",+ "./lib/tools/cli-client/program": "./lib/tools/cli-client/program.js"},"bin": {"playwright-core": "cli.js"diff --git a/packages/playwright-core/src/DEPS.list b/packages/playwright-core/src/DEPS.listindex d962b703a6..6b852f35eb 100644--- a/packages/playwright-core/src/DEPS.list+++ b/packages/playwright-core/src/DEPS.list@@ -22,6 +22,7 @@ utilsBundle.ts[outofprocess.ts]client/+package.tsprotocol/utils/utils/isomorphicdiff --git a/packages/playwright-core/src/cli/DEPS.list b/packages/playwright-core/src/cli/DEPS.listindex 5ed8f9dfb4..bbded59df9 100644--- a/packages/playwright-core/src/cli/DEPS.list+++ b/packages/playwright-core/src/cli/DEPS.list@@ -1,6 +1,8 @@[*]../inprocess.ts+../package.ts../server/+../server/registry/../server/utils/../remote/../utils/diff --git a/packages/playwright-core/src/cli/browserActions.ts b/packages/playwright-core/src/cli/browserActions.tsindex 31d53c8a3f..6548d3982f 100644--- a/packages/playwright-core/src/cli/browserActions.ts+++ b/packages/playwright-core/src/cli/browserActions.ts@@ -22,7 +22,7 @@ import path from 'path';import { playwright } from '../inprocess';import { gracefullyProcessExitDoNotHang, ManualPromise } from '../utils';-import { dotenv, program } from '../utilsBundle';+import { debug, dotenv, program } from '../utilsBundle';import type { Browser } from '../client/browser';import type { BrowserContext } from '../client/browserContext';@@ -267,7 +267,7 @@ async function maybeSetupTestHooks(browser: Browser, closeBrowser: () => Promise// Make sure we exit abnormally when browser crashes.const logs: string[] = [];- require('playwright-core/lib/utilsBundle').debug.log = (...args: any[]) => {+ debug.log = (...args: any[]) => {const line = require('util').format(...args) + '\n';logs.push(line);// eslint-disable-next-line no-restricted-propertiesdiff --git a/packages/playwright-core/src/cli/driver.ts b/packages/playwright-core/src/cli/driver.tsindex 356b677c13..fba2276a5a 100644--- a/packages/playwright-core/src/cli/driver.ts+++ b/packages/playwright-core/src/cli/driver.ts@@ -17,7 +17,9 @@/* eslint-disable no-console */import fs from 'fs';+import path from 'path';+import { packageRoot } from '../package';import { playwright } from '../inprocess';import { PipeTransport } from '../server/utils/pipeTransport';import { PlaywrightServer } from '../remote/playwrightServer';@@ -29,7 +31,7 @@ import type { LaunchServerOptions } from '../client/types';export function printApiJson() {// Note: this file is generated by build-playwright-driver.sh- console.log(JSON.stringify(require('../../api.json')));+ console.log(JSON.stringify(require(path.join(packageRoot, 'api.json'))));}export function runDriver() {diff --git a/packages/playwright-core/src/cli/installActions.ts b/packages/playwright-core/src/cli/installActions.tsindex ada718f941..47ce93fb23 100644--- a/packages/playwright-core/src/cli/installActions.ts+++ b/packages/playwright-core/src/cli/installActions.ts@@ -18,12 +18,12 @@import path from 'path';-import { registry, writeDockerVersion } from '../server';+import { registry, writeDockerVersion } from '../server/registry';import { isLikelyNpxGlobal } from '../utils';import { assert } from '../utils';import { wrapInASCIIBox } from '../server/utils/ascii';-import type { BrowserInfo } from '../server';+import type { BrowserInfo } from '../server/registry';function printInstalledBrowsers(browsers: BrowserInfo[]) {const browserPaths = new Set<string>();diff --git a/packages/playwright-core/src/cli/program.ts b/packages/playwright-core/src/cli/program.tsindex 988ee101ba..17edd75b13 100644--- a/packages/playwright-core/src/cli/program.ts+++ b/packages/playwright-core/src/cli/program.ts@@ -17,6 +17,7 @@/* eslint-disable no-console */import '../bootstrap';+import { packageJSON } from '../package';import { gracefullyProcessExitDoNotHang, getPackageManagerExecCommand } from '../utils';import { addTraceCommands } from '../tools/trace/traceCli';import { program } from '../utilsBundle';@@ -25,7 +26,6 @@ import type { TraceViewerServerOptions } from '../server/trace/viewer/traceVieweimport type { Command } from '../utilsBundle';export function decorateProgram(program: Command) {- const packageJSON = require('../../package.json');program.version('Version ' + (process.env.PW_CLI_DISPLAY_VERSION || packageJSON.version))diff --git a/packages/playwright-core/src/client/clientStackTrace.ts b/packages/playwright-core/src/client/clientStackTrace.tsindex 3dc16dbae6..88ded75f2e 100644--- a/packages/playwright-core/src/client/clientStackTrace.ts+++ b/packages/playwright-core/src/client/clientStackTrace.ts@@ -55,10 +55,11 @@ export function captureLibraryStackTrace(platform: Platform): { frames: StackFrafunction normalizeAPIName(name?: string): string {if (!name)return '';- const match = name.match(/(API|JS|CDP|[A-Z])(.*)/);+ // (\d) is to tolerate bundler renames Locator2 instead of Locator.+ const match = name.match(/(API|JS|CDP|[A-Z])([^\d]+)\d?\.(.*)/);if (!match)return name;- return match[1].toLowerCase() + match[2];+ return match[1].toLowerCase() + match[2] + '.' + match[3];}// This is for the inspector so that it did not include the test runner stack frames.diff --git a/packages/playwright-core/src/client/fetch.ts b/packages/playwright-core/src/client/fetch.tsindex efdece2211..4b424d32b5 100644--- a/packages/playwright-core/src/client/fetch.ts+++ b/packages/playwright-core/src/client/fetch.ts@@ -304,6 +304,7 @@ export class APIResponse implements api.APIResponse {private readonly _initializer: channels.APIResponse;private readonly _headers: RawHeaders;readonly _request: APIRequestContext;+ _apiName = 'APIResponse';constructor(context: APIRequestContext, initializer: channels.APIResponse) {this._request = context;diff --git a/packages/playwright-core/src/client/index.ts b/packages/playwright-core/src/client/index.tsnew file mode 100644index 0000000000..d0c347137f--- /dev/null+++ b/packages/playwright-core/src/client/index.ts@@ -0,0 +1,17 @@+/**+ * Copyright (c) Microsoft Corporation.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++export * from './eventEmitter';diff --git a/packages/playwright-core/src/client/locator.ts b/packages/playwright-core/src/client/locator.tsindex 5aca23e540..695bc885cc 100644--- a/packages/playwright-core/src/client/locator.ts+++ b/packages/playwright-core/src/client/locator.ts@@ -40,6 +40,7 @@ export type LocatorOptions = {export class Locator implements api.Locator {_frame: Frame;_selector: string;+ _apiName = 'Locator';constructor(frame: Frame, selector: string, options?: LocatorOptions) {this._frame = frame;diff --git a/packages/playwright-core/src/client/page.ts b/packages/playwright-core/src/client/page.tsindex 392d982f12..0f284148dd 100644--- a/packages/playwright-core/src/client/page.ts+++ b/packages/playwright-core/src/client/page.ts@@ -79,6 +79,7 @@ export type ExpectScreenshotOptions = Omit<channels.PageExpectScreenshotOptions,export class Page extends ChannelOwner<channels.PageChannel> implements api.Page {private _browserContext: BrowserContext;_ownedContext: BrowserContext | undefined;+ _apiName = 'Page';private _mainFrame: Frame;private _frames = new Set<Frame>();diff --git a/packages/playwright-core/src/coreBundle.ts b/packages/playwright-core/src/coreBundle.tsindex b11112515c..29ff98816e 100644--- a/packages/playwright-core/src/coreBundle.ts+++ b/packages/playwright-core/src/coreBundle.ts@@ -14,15 +14,14 @@* limitations under the License.*/+export * as client from './client';export * as iso from './utils/isomorphic';export * as serverUtils from './server/utils';-export * as tools from './tools';export * as libCli from './cli/program';export * as libCliTestStub from './cli/programWithTestStub';export * as inprocess from './inprocess';export * as oop from './outofprocess';export * as remote from './remote/playwrightServer';-export * as mcp from './tools/mcp/program';-export * as cli from './tools/cli-client/program';export * as registry from './server/registry/index';export * as sever from './server/index';+export * as tools from './tools';diff --git a/packages/playwright-core/src/entry/DEPS.list b/packages/playwright-core/src/entry/DEPS.listnew file mode 100644index 0000000000..d3fec82ea3--- /dev/null+++ b/packages/playwright-core/src/entry/DEPS.list@@ -0,0 +1,4 @@+[*]+../coreBundle.ts+../package.ts+../utilsBundle.tsdiff --git a/packages/playwright-core/src/entry/cliDaemon.ts b/packages/playwright-core/src/entry/cliDaemon.tsnew file mode 100644index 0000000000..c733af1b84--- /dev/null+++ b/packages/playwright-core/src/entry/cliDaemon.ts@@ -0,0 +1,21 @@+/**+ * Copyright (c) Microsoft Corporation.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { tools } from '../coreBundle';+import { program } from '../utilsBundle';++tools.decorateCliDaemonProgram(program);+void program.parseAsync();diff --git a/packages/playwright-core/src/entry/dashboardApp.ts b/packages/playwright-core/src/entry/dashboardApp.tsnew file mode 100644index 0000000000..086b407387--- /dev/null+++ b/packages/playwright-core/src/entry/dashboardApp.ts@@ -0,0 +1,19 @@+/**+ * Copyright (c) Microsoft Corporation.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { tools } from '../coreBundle';++tools.openDashboardApp();diff --git a/packages/playwright-core/src/tools/mcp/cli-stub.ts b/packages/playwright-core/src/entry/mcp.tssimilarity index 67%rename from packages/playwright-core/src/tools/mcp/cli-stub.tsrename to packages/playwright-core/src/entry/mcp.tsindex 269212dec7..a53846905e 100644--- a/packages/playwright-core/src/tools/mcp/cli-stub.ts+++ b/packages/playwright-core/src/entry/mcp.ts@@ -14,10 +14,14 @@* limitations under the License.*/-import { program } from '../../utilsBundle';-import { decorateMCPCommand } from './program';+import { program } from '../utilsBundle';+import { tools, serverUtils } from '../coreBundle';+import { packageJSON } from '../package';-const packageJSON = require('../../../package.json');const p = program.version('Version ' + packageJSON.version).name('Playwright MCP');-decorateMCPCommand(p);-void program.parseAsync(process.argv);+tools.decorateMCPCommand(p);+program.parseAsync(process.argv).catch(e => {+ // eslint-disable-next-line no-console+ console.error(e.message);+ serverUtils.gracefullyProcessExitDoNotHang(1);+});diff --git a/packages/playwright-core/src/entry/oopBrowserDownload.ts b/packages/playwright-core/src/entry/oopBrowserDownload.tsnew file mode 100644index 0000000000..b81b9b0b77--- /dev/null+++ b/packages/playwright-core/src/entry/oopBrowserDownload.ts@@ -0,0 +1,19 @@+/**+ * Copyright (c) Microsoft Corporation.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { registry } from '../coreBundle';++registry.runOopDownloadBrowserMain();diff --git a/packages/playwright-core/src/outofprocess.ts b/packages/playwright-core/src/outofprocess.tsindex 3496c9895d..f38e99ca18 100644--- a/packages/playwright-core/src/outofprocess.ts+++ b/packages/playwright-core/src/outofprocess.ts@@ -18,6 +18,7 @@ import * as childProcess from 'child_process';import path from 'path';import { Connection } from './client/connection';+import { packageRoot } from './package';import { PipeTransport } from './server/utils/pipeTransport';import { ManualPromise } from './utils/isomorphic/manualPromise';import { nodePlatform } from './server/utils/nodePlatform';@@ -38,7 +39,7 @@ class PlaywrightClient {private _closePromise = new ManualPromise<void>();constructor(env: any) {- this._driverProcess = childProcess.fork(path.join(__dirname, '..', 'cli.js'), ['run-driver'], {+ this._driverProcess = childProcess.fork(path.join(packageRoot, 'cli.js'), ['run-driver'], {stdio: 'pipe',detached: true,env: {diff --git a/packages/playwright-core/src/package.ts b/packages/playwright-core/src/package.tsindex 47bff2d85d..d114e7e773 100644--- a/packages/playwright-core/src/package.ts+++ b/packages/playwright-core/src/package.ts@@ -19,3 +19,7 @@ import path from 'path';export const packageJSON = require('../package.json');export const packageRoot = path.dirname(require.resolve('../package.json'));export const binPath = path.join(packageRoot, 'bin');++export function libPath(...parts: string[]): string {+ return path.join(packageRoot, 'lib', ...parts);+}diff --git a/packages/playwright-core/src/server/bidi/bidiChromium.ts b/packages/playwright-core/src/server/bidi/bidiChromium.tsindex 1febca2ea2..4c16cc992e 100644--- a/packages/playwright-core/src/server/bidi/bidiChromium.ts+++ b/packages/playwright-core/src/server/bidi/bidiChromium.ts@@ -40,7 +40,8 @@ export class BidiChromium extends BrowserType {// Chrome doesn't support Bidi, we create Bidi over CDP which is used by Chrome driver.// bidiOverCdp depends on chromium-bidi which we only have in devDependencies, so// we load bidiOverCdp dynamically.- const bidiTransport = await require('./bidiOverCdp').connectBidiOverCdp(transport);+ const bidiOverCdp = await import('./bidiOverCdp');+ const bidiTransport = await bidiOverCdp.connectBidiOverCdp(transport);(transport as any)[kBidiOverCdpWrapper] = bidiTransport;try {return BidiBrowser.connect(this.attribution.playwright, bidiTransport, options);diff --git a/packages/playwright-core/src/server/electron/DEPS.list b/packages/playwright-core/src/server/electron/DEPS.listindex 193adeb6d6..fcb87d71e8 100644--- a/packages/playwright-core/src/server/electron/DEPS.list+++ b/packages/playwright-core/src/server/electron/DEPS.list@@ -1,5 +1,6 @@[*]../+../../package.ts../../utils/../../utils/isomorphic/../chromium/diff --git a/packages/playwright-core/src/server/electron/electron.ts b/packages/playwright-core/src/server/electron/electron.tsindex 879a729bee..912079ff5f 100644--- a/packages/playwright-core/src/server/electron/electron.ts+++ b/packages/playwright-core/src/server/electron/electron.ts@@ -19,6 +19,7 @@ import os from 'os';import path from 'path';import * as readline from 'readline';+import { libPath } from '../../package';import { ManualPromise } from '../../utils';import { wrapInASCIIBox } from '../utils/ascii';import { RecentLogsCollector } from '../utils/debugLogger';@@ -194,7 +195,7 @@ export class Electron extends SdkObject {}// Only use our own loader for non-packaged apps.// Packaged apps might have their own command line handling.- electronArguments.unshift('-r', require.resolve('./loader'));+ electronArguments.unshift('-r', libPath('server', 'electron', 'loader.js'));}let shell = false;if (process.platform === 'win32') {diff --git a/packages/playwright-core/src/server/electron/loader.ts b/packages/playwright-core/src/server/electron/loader.tsindex c3aee60db9..80c6f76fb3 100644--- a/packages/playwright-core/src/server/electron/loader.ts+++ b/packages/playwright-core/src/server/electron/loader.ts@@ -14,9 +14,8 @@* limitations under the License.*/-const { app } = require('electron');--const { chromiumSwitches } = require('../chromium/chromiumSwitches');+import { app } from 'electron';+import { chromiumSwitches } from '../chromium/chromiumSwitches';// Always pass user arguments first, see https://github.com/microsoft/playwright/issues/16614 and// https://github.com/microsoft/playwright/issues/29198.diff --git a/packages/playwright-core/src/server/har/harRecorder.ts b/packages/playwright-core/src/server/har/harRecorder.tsindex 29965fbd2d..7d99a37790 100644--- a/packages/playwright-core/src/server/har/harRecorder.ts+++ b/packages/playwright-core/src/server/har/harRecorder.ts@@ -21,6 +21,7 @@ import { Artifact } from '../artifact';import { HarTracer } from './harTracer';import { createGuid } from '../utils/crypto';import { ManualPromise } from '../../utils/isomorphic/manualPromise';+import { yazl } from '../../zipBundle';import type { BrowserContext } from '../browserContext';import type { HarTracerDelegate } from './harTracer';@@ -51,7 +52,6 @@ export class HarRecorder implements HarTracerDelegate {waitForContentOnStop: true,urlFilter: urlFilterRe ?? options.urlGlob,});- const { yazl } = require('../../zipBundle');this._zipFile = content === 'attach' || expectsZip ? new yazl.ZipFile() : null;this._tracer.start({ omitScripts: false });}diff --git a/packages/playwright-core/src/server/index.ts b/packages/playwright-core/src/server/index.tsindex 1513c16b81..50b78bf74b 100644--- a/packages/playwright-core/src/server/index.ts+++ b/packages/playwright-core/src/server/index.ts@@ -14,19 +14,21 @@* limitations under the License.*/-export type { BrowserInfo, Executable } from './registry';-export {- Registry,- installBrowsersForNpmInstall,- registry,- registryDirectory,- writeDockerVersion } from './registry';--export { DispatcherConnection, RootDispatcher } from './dispatchers/dispatcher';+export { Browser } from './browser';+export { BrowserContext } from './browserContext';+export { findRepeatedSubsequencesForTest } from './callLog';+export { deviceDescriptors } from './deviceDescriptors';+export { DispatcherConnection, RootDispatcher, setMaxDispatchersForTest } from './dispatchers/dispatcher';+export { RequestDispatcher, ResponseDispatcher } from './dispatchers/networkDispatchers';export { PlaywrightDispatcher } from './dispatchers/playwrightDispatcher';+export { Request, Response } from './network';+export { Page } from './page';export { createPlaywright } from './playwright';+export { nullProgress } from './progress';+export { WebSocketTransport } from './transport';export type { DispatcherScope } from './dispatchers/dispatcher';+export type { Frame } from './frames';export type { Playwright } from './playwright';export type { TraceViewerRedirectOptions, TraceViewerServerOptions } from './trace/viewer/traceViewer';export { installRootRedirect, openTraceInBrowser, openTraceViewerApp, startTraceViewerServer, runTraceViewerApp } from './trace/viewer/traceViewer';diff --git a/packages/playwright-core/src/server/launchApp.ts b/packages/playwright-core/src/server/launchApp.tsindex 58227d32ab..650505054d 100644--- a/packages/playwright-core/src/server/launchApp.ts+++ b/packages/playwright-core/src/server/launchApp.ts@@ -17,6 +17,7 @@import fs from 'fs';import path from 'path';+import { libPath } from '../package';import { isUnderTest, rewriteErrorMessage, wrapInASCIIBox } from '../utils';import { buildPlaywrightCLICommand, findChromiumChannelBestEffort } from './registry';import { registryDirectory } from './registry';@@ -88,7 +89,7 @@ export async function launchApp(browserType: BrowserType, options: {}async function installAppIcon(page: Page) {- const icon = await fs.promises.readFile(require.resolve('./chromium/appIcon.png'));+ const icon = await fs.promises.readFile(libPath('server', 'chromium', 'appIcon.png'));const crPage = page.delegate as CRPage;await crPage._mainFrameSession._client.send('Browser.setDockTile', {image: icon.toString('base64')diff --git a/packages/playwright-core/src/server/recorder/DEPS.list b/packages/playwright-core/src/server/recorder/DEPS.listindex 6151537ccb..61d3676264 100644--- a/packages/playwright-core/src/server/recorder/DEPS.list+++ b/packages/playwright-core/src/server/recorder/DEPS.list@@ -6,6 +6,7 @@../registry/**../utils/**../../generated/pollingRecorderSource.ts+../../package.ts../../protocol/../../utils/**../../utilsBundle.tsdiff --git a/packages/playwright-core/src/server/recorder/recorderApp.ts b/packages/playwright-core/src/server/recorder/recorderApp.tsindex a121178c04..eb3fc9bafd 100644--- a/packages/playwright-core/src/server/recorder/recorderApp.ts+++ b/packages/playwright-core/src/server/recorder/recorderApp.ts@@ -17,6 +17,7 @@import fs from 'fs';import path from 'path';+import { libPath } from '../../package';import { isUnderTest } from '../utils/debug';import { mime } from '../../utilsBundle';import { syncLocalStorageWithSettings } from '../launchApp';@@ -94,7 +95,7 @@ export class RecorderApp {}const uri = route.request().url().substring('https://playwright/'.length);- const file = require.resolve('../../vite/recorder/' + uri);+ const file = path.join(libPath('vite', 'recorder'), uri);fs.promises.readFile(file).then(buffer => {route.fulfill({status: 200,@@ -204,7 +205,8 @@ export class RecorderApp {const sdkLanguage = inspectedContext._browser.sdkLanguage();const isChromium = inspectedContext._browser.options.browserType === 'chromium';const headed = !!inspectedContext._browser.options.headful;- const recorderPlaywright = (require('../playwright').createPlaywright as typeof import('../playwright').createPlaywright)({ sdkLanguage: 'javascript', isInternalPlaywright: true });+ const { createPlaywright } = await import('../playwright');+ const recorderPlaywright = createPlaywright({ sdkLanguage: 'javascript', isInternalPlaywright: true });const { context: appContext, page } = await launchApp(recorderPlaywright.chromium, {sdkLanguage,windowSize: { width: 600, height: 600 },diff --git a/packages/playwright-core/src/server/registry/DEPS.list b/packages/playwright-core/src/server/registry/DEPS.listnew file mode 100644index 0000000000..a96f617a75--- /dev/null+++ b/packages/playwright-core/src/server/registry/DEPS.list@@ -0,0 +1,8 @@+[*]+../../package.ts+../../utils/+../../utils/isomorphic/+../../utilsBundle.ts+../../zipBundle.ts+../utils/+./diff --git a/packages/playwright-core/src/server/registry/browserFetcher.ts b/packages/playwright-core/src/server/registry/browserFetcher.tsindex f4c4d7df83..d67ae4a44e 100644--- a/packages/playwright-core/src/server/registry/browserFetcher.ts+++ b/packages/playwright-core/src/server/registry/browserFetcher.ts@@ -20,6 +20,7 @@ import fs from 'fs';import os from 'os';import path from 'path';+import { libPath } from '../../package';import { debugLogger } from '../utils/debugLogger';import { ManualPromise } from '../../utils/isomorphic/manualPromise';import { getUserAgent } from '../utils/userAgent';@@ -81,7 +82,7 @@ export async function downloadBrowserWithProgressBar(title: string, browserDirec* https://github.com/microsoft/playwright/issues/17394*/function downloadBrowserWithProgressBarOutOfProcess(title: string, browserDirectory: string, url: string, zipPath: string, executablePath: string | undefined, socketTimeout: number): Promise<{ error: Error | null }> {- const cp = childProcess.fork(path.join(__dirname, 'oopDownloadBrowserMain.js'));+ const cp = childProcess.fork(libPath('entry', 'oopBrowserDownload.js'));const promise = new ManualPromise<{ error: Error | null }>();const progress = getDownloadProgress();cp.on('message', (message: any) => {diff --git a/packages/playwright-core/src/server/registry/index.ts b/packages/playwright-core/src/server/registry/index.tsindex ad5bde97e0..0565330be3 100644--- a/packages/playwright-core/src/server/registry/index.ts+++ b/packages/playwright-core/src/server/registry/index.ts@@ -1518,4 +1518,6 @@ function lowercaseAllKeys(json: any): any {return result;}-export const registry = new Registry(require('../../../browsers.json'));+export const registry = new Registry(require(path.join(packageRoot, 'browsers.json')));++export { runOopDownloadBrowserMain } from './oopDownloadBrowserMain';diff --git a/packages/playwright-core/src/server/registry/oopDownloadBrowserMain.ts b/packages/playwright-core/src/server/registry/oopDownloadBrowserMain.tsindex 5923201206..eb683b5f7c 100644--- a/packages/playwright-core/src/server/registry/oopDownloadBrowserMain.ts+++ b/packages/playwright-core/src/server/registry/oopDownloadBrowserMain.ts@@ -125,21 +125,23 @@ async function main(options: DownloadParams) {await fs.promises.writeFile(browserDirectoryToMarkerFilePath(options.browserDirectory), '');}-process.on('message', async message => {- const { method, params } = message as any;- if (method === 'download') {- try {- await main(params);- // eslint-disable-next-line no-restricted-properties- process.exit(0);- } catch (e) {- // eslint-disable-next-line no-console- console.error(e);- // eslint-disable-next-line no-restricted-properties- process.exit(1);+export function runOopDownloadBrowserMain() {+ process.on('message', async message => {+ const { method, params } = message as any;+ if (method === 'download') {+ try {+ await main(params);+ // eslint-disable-next-line no-restricted-properties+ process.exit(0);+ } catch (e) {+ // eslint-disable-next-line no-console+ console.error(e);+ // eslint-disable-next-line no-restricted-properties+ process.exit(1);+ }}- }-});+ });-// eslint-disable-next-line no-restricted-properties-process.on('disconnect', () => { process.exit(0); });+ // eslint-disable-next-line no-restricted-properties+ process.on('disconnect', () => { process.exit(0); });+}diff --git a/packages/playwright-core/src/server/trace/viewer/DEPS.list b/packages/playwright-core/src/server/trace/viewer/DEPS.listindex cd0ac02b8a..bafc0d1ab7 100644--- a/packages/playwright-core/src/server/trace/viewer/DEPS.list+++ b/packages/playwright-core/src/server/trace/viewer/DEPS.list@@ -3,5 +3,6 @@../../utils/../../registry/../../../generated/+../../../package.ts../../../utils/../../../utilsBundle.tsdiff --git a/packages/playwright-core/src/server/trace/viewer/traceViewer.ts b/packages/playwright-core/src/server/trace/viewer/traceViewer.tsindex c0c5f99769..262cc9779c 100644--- a/packages/playwright-core/src/server/trace/viewer/traceViewer.ts+++ b/packages/playwright-core/src/server/trace/viewer/traceViewer.ts@@ -17,6 +17,7 @@import fs from 'fs';import path from 'path';+import { libPath } from '../../../package';import { gracefullyProcessExitDoNotHang } from '../../../utils';import { isUnderTest } from '../../../utils';import { HttpServer } from '../../utils/httpServer';@@ -107,7 +108,7 @@ export async function startTraceViewerServer(options?: TraceViewerServerOptions)response.end();return true;}- const absolutePath = path.join(__dirname, '..', '..', '..', 'vite', 'traceViewer', ...relativePath.split('/'));+ const absolutePath = path.join(libPath('vite', 'traceViewer'), ...relativePath.split('/'));return server.serveFile(request, response, absolutePath);});diff --git a/packages/playwright-core/src/server/utils/index.ts b/packages/playwright-core/src/server/utils/index.tsindex 8d72df26ca..05549190e1 100644--- a/packages/playwright-core/src/server/utils/index.ts+++ b/packages/playwright-core/src/server/utils/index.ts@@ -36,3 +36,7 @@ export * from './userAgent';export * from './wsServer';export * from './zipFile';export * from './zones';+export * from './image_tools/colorUtils';+export * from './image_tools/compare';+export * from './image_tools/imageChannel';+export * from './image_tools/stats';diff --git a/packages/playwright-core/src/server/utils/userAgent.ts b/packages/playwright-core/src/server/utils/userAgent.tsindex d9c7619ac5..25e930453b 100644--- a/packages/playwright-core/src/server/utils/userAgent.ts+++ b/packages/playwright-core/src/server/utils/userAgent.ts@@ -17,6 +17,7 @@import { execSync } from 'child_process';import os from 'os';+import { packageJSON } from '../../package';import { getLinuxDistributionInfoSync } from '../utils/linuxUtils';let cachedUserAgent: string | undefined;@@ -77,6 +78,6 @@ export function getEmbedderName(): { embedderName: string, embedderVersion: stri}export function getPlaywrightVersion(majorMinorOnly = false): string {- const version = process.env.PW_VERSION_OVERRIDE || require('./../../../package.json').version;+ const version = process.env.PW_VERSION_OVERRIDE || packageJSON.version;return majorMinorOnly ? version.split('.').slice(0, 2).join('.') : version;}diff --git a/packages/playwright-core/src/server/videoRecorder.ts b/packages/playwright-core/src/server/videoRecorder.tsindex 1489cda331..f10e12d38a 100644--- a/packages/playwright-core/src/server/videoRecorder.ts+++ b/packages/playwright-core/src/server/videoRecorder.ts@@ -20,7 +20,7 @@ import { assert, createGuid, debugLogger, mkdirIfNeeded, monotonicTime } from '.import { launchProcess } from './utils/processLauncher';import { jpegjs } from '../utilsBundle';import { Artifact } from './artifact';-import { registry } from '.';+import { registry } from './registry';import type * as types from './types';import type { ChildProcess } from 'child_process';diff --git a/packages/playwright-core/src/tools/cli-client/DEPS.list b/packages/playwright-core/src/tools/cli-client/DEPS.listindex c0159feef2..73a5463045 100644--- a/packages/playwright-core/src/tools/cli-client/DEPS.list+++ b/packages/playwright-core/src/tools/cli-client/DEPS.list@@ -3,11 +3,13 @@./minimist.ts./session.ts./registry.ts+../../package.ts../../serverRegistry.ts[session.ts]"strict"./minimist.ts+../../package.ts../utils/socketConnection.ts./registry.tsdiff --git a/packages/playwright-core/src/tools/cli-client/program.ts b/packages/playwright-core/src/tools/cli-client/program.tsindex 2a55cb8fbb..44ffc849da 100644--- a/packages/playwright-core/src/tools/cli-client/program.ts+++ b/packages/playwright-core/src/tools/cli-client/program.ts@@ -24,6 +24,7 @@ import os from 'os';import path from 'path';import { clientKey, createClientInfo, explicitSessionName, Registry, resolveSessionName } from './registry';import { Session, renderResolvedConfig } from './session';+import { libPath } from '../../package';import { serverRegistry } from '../../serverRegistry';import { minimist } from './minimist';@@ -77,7 +78,7 @@ const booleanOptions: (keyof (GlobalOptions & OpenOptions & AttachOptions & { alexport async function program(options?: { embedderVersion?: string}) {const clientInfo = createClientInfo();- const help = require('./help.json');+ const help = require(libPath('tools', 'cli-client', 'help.json'));const argv = process.argv.slice(2);const boolean = [...help.booleanOptions, ...booleanOptions];@@ -178,7 +179,7 @@ export async function program(options?: { embedderVersion?: string}) {await installBrowser();return;case 'show': {- const daemonScript = require.resolve('../dashboard/dashboardApp.js');+ const daemonScript = libPath('entry', 'dashboardApp.js');const child = spawn(process.execPath, [daemonScript], {detached: true,stdio: 'ignore',@@ -219,7 +220,7 @@ async function runInSession(entry: SessionFile, clientInfo: ClientInfo, args: Mi}async function runInitWorkspace(args: MinimistArgs) {- const cliPath = require.resolve('../cli-daemon/program.js');+ const cliPath = libPath('entry', 'cliDaemon.js');const daemonArgs: string[] = [cliPath, '--init-workspace', ...(args.skills ? ['--init-skills', String(args.skills)] : [])];await new Promise<void>((resolve, reject) => {const child = spawn(process.execPath, daemonArgs, {@@ -237,8 +238,8 @@ async function runInitWorkspace(args: MinimistArgs) {async function installBrowser() {const argv = process.argv.map(arg => arg === 'install-browser' ? 'install' : arg);- const { libCli } = await import('../../coreBundle');- const { program } = await import('../../utilsBundle');+ const { libCli } = await import('../../coreBundle.js');+ const { program } = await import('../../utilsBundle.js');if (!program.version())libCli.decorateProgram(program);program.parse(argv);diff --git a/packages/playwright-core/src/tools/cli-client/session.ts b/packages/playwright-core/src/tools/cli-client/session.tsindex 6cbebad914..c82ca867a1 100644--- a/packages/playwright-core/src/tools/cli-client/session.ts+++ b/packages/playwright-core/src/tools/cli-client/session.ts@@ -22,6 +22,7 @@ import fs from 'fs';import net from 'net';import os from 'os';import path from 'path';+import { libPath } from '../../package';import { compareSemver, SocketConnection } from '../utils/socketConnection';import { resolveSessionName } from './registry';@@ -122,7 +123,7 @@ export class Session {static async startDaemon(clientInfo: ClientInfo, cliArgs: MinimistArgs) {await fs.promises.mkdir(clientInfo.daemonProfilesDir, { recursive: true });- const cliPath = require.resolve('../cli-daemon/program.js');+ const cliPath = libPath('entry', 'cliDaemon.js');const sessionName = resolveSessionName(cliArgs.session as string);const errLog = path.join(clientInfo.daemonProfilesDir, sessionName + '.err');const err = fs.openSync(errLog, 'w');diff --git a/packages/playwright-core/src/tools/cli-daemon/DEPS.list b/packages/playwright-core/src/tools/cli-daemon/DEPS.listindex 85f03e1dc2..4e974a22c5 100644--- a/packages/playwright-core/src/tools/cli-daemon/DEPS.list+++ b/packages/playwright-core/src/tools/cli-daemon/DEPS.list@@ -1,4 +1,5 @@[*]+../../package.ts../utils/socketConnection.ts../cli-client/registry.ts../backend/diff --git a/packages/playwright-core/src/tools/cli-daemon/program.ts b/packages/playwright-core/src/tools/cli-daemon/program.tsindex ce6aa76aaa..1cc96c627e 100644--- a/packages/playwright-core/src/tools/cli-daemon/program.ts+++ b/packages/playwright-core/src/tools/cli-daemon/program.ts@@ -20,60 +20,61 @@ import fs from 'fs';import os from 'os';import path from 'path';+import { libPath } from '../../package';import { startCliDaemonServer } from './daemon';import { setupExitWatchdog } from '../mcp/watchdog';import { createBrowserWithInfo } from '../mcp/browserFactory';import * as configUtils from '../mcp/config';import { createClientInfo } from '../cli-client/registry';-import { program } from '../../utilsBundle';import { registry as browserRegistry } from '../../server/registry/index';import { getAsBooleanFromENV } from '../../server/utils/env';--program.argument('[session-name]', 'name of the session to create or connect to', 'default')- .option('--headed', 'run in headed mode (non-headless)')- .option('--extension', 'run with the extension')- .option('--browser <name>', 'browser to use (chromium, chrome, firefox, webkit)')- .option('--persistent', 'use a persistent browser context')- .option('--profile <path>', 'path to the user data dir')- .option('--config <path>', 'path to the config file; by default uses .playwright/cli.config.json in the project directory and ~/.playwright/cli.config.json as global config')- .option('--cdp <url>', 'connect to an existing browser via CDP endpoint URL')- .option('--endpoint <endpoint>', 'attach to a running Playwright browser endpoint')- .option('--init-workspace', 'initialize workspace')- .option('--init-skills <value>', 'install skills for the given agent type ("claude" or "agents")')-- .action(async (sessionName: string, options: any) => {- if (options.initWorkspace) {- await initWorkspace(options.initSkills);- return;- }-- setupExitWatchdog();- const clientInfo = createClientInfo();- const mcpConfig = await configUtils.resolveCLIConfigForCLI(clientInfo.daemonProfilesDir, sessionName, options);- const mcpClientInfo = {- cwd: process.cwd(),- clientName: guessClientName(),- };-- try {- const { browser, browserInfo, canBind } = await createBrowserWithInfo(mcpConfig, mcpClientInfo);- if (canBind)- await browser.bind(sessionName, { workspaceDir: clientInfo.workspaceDir });- const browserContext = mcpConfig.browser.isolated ? await browser.newContext(mcpConfig.browser.contextOptions) : browser.contexts()[0];- if (!browserContext)- throw new Error('Error: unable to connect to a browser that does not have any contexts');- const persistent = options.persistent || options.profile || mcpConfig.browser.userDataDir ? true : undefined;- const socketPath = await startCliDaemonServer(sessionName, browserContext, browserInfo, mcpConfig, clientInfo, mcpClientInfo, { persistent, exitOnClose: true });- console.log(`### Success\nDaemon listening on ${socketPath}`);- console.log('<EOF>');- } catch (error) {- const message = process.env.PWDEBUGIMPL ? (error as Error).stack || (error as Error).message : (error as Error).message;- console.log(`### Error\n${message}`);- console.log('<EOF>');- }- });--void program.parseAsync();+import type { Command } from '../../utilsBundle';++export function decorateProgram(program: Command) {+ program.argument('[session-name]', 'name of the session to create or connect to', 'default')+ .option('--headed', 'run in headed mode (non-headless)')+ .option('--extension', 'run with the extension')+ .option('--browser <name>', 'browser to use (chromium, chrome, firefox, webkit)')+ .option('--persistent', 'use a persistent browser context')+ .option('--profile <path>', 'path to the user data dir')+ .option('--config <path>', 'path to the config file; by default uses .playwright/cli.config.json in the project directory and ~/.playwright/cli.config.json as global config')+ .option('--cdp <url>', 'connect to an existing browser via CDP endpoint URL')+ .option('--endpoint <endpoint>', 'attach to a running Playwright browser endpoint')+ .option('--init-workspace', 'initialize workspace')+ .option('--init-skills <value>', 'install skills for the given agent type ("claude" or "agents")')++ .action(async (sessionName: string, options: any) => {+ if (options.initWorkspace) {+ await initWorkspace(options.initSkills);+ return;+ }++ setupExitWatchdog();+ const clientInfo = createClientInfo();+ const mcpConfig = await configUtils.resolveCLIConfigForCLI(clientInfo.daemonProfilesDir, sessionName, options);+ const mcpClientInfo = {+ cwd: process.cwd(),+ clientName: guessClientName(),+ };++ try {+ const { browser, browserInfo, canBind } = await createBrowserWithInfo(mcpConfig, mcpClientInfo);+ if (canBind)+ await browser.bind(sessionName, { workspaceDir: clientInfo.workspaceDir });+ const browserContext = mcpConfig.browser.isolated ? await browser.newContext(mcpConfig.browser.contextOptions) : browser.contexts()[0];+ if (!browserContext)+ throw new Error('Error: unable to connect to a browser that does not have any contexts');+ const persistent = options.persistent || options.profile || mcpConfig.browser.userDataDir ? true : undefined;+ const socketPath = await startCliDaemonServer(sessionName, browserContext, browserInfo, mcpConfig, clientInfo, mcpClientInfo, { persistent, exitOnClose: true });+ console.log(`### Success\nDaemon listening on ${socketPath}`);+ console.log('<EOF>');+ } catch (error) {+ const message = process.env.PWDEBUGIMPL ? (error as Error).stack || (error as Error).message : (error as Error).message;+ console.log(`### Error\n${message}`);+ console.log('<EOF>');+ }+ });+}function guessClientName(): string {if (process.env.CLAUDECODE)@@ -98,7 +99,7 @@ async function initWorkspace(initSkills: string | undefined) {console.log(`✅ Workspace initialized at \`${cwd}\`.`);if (initSkills) {- const skillSourceDir = path.join(__dirname, '../cli-client/skill');+ const skillSourceDir = libPath('tools', 'cli-client', 'skill');const target = initSkills === 'agents' ? 'agents' : 'claude';const skillDestDir = path.join(cwd, `.${target}`, 'skills', 'playwright-cli');if (!fs.existsSync(skillSourceDir)) {diff --git a/packages/playwright-core/src/tools/dashboard/dashboardApp.ts b/packages/playwright-core/src/tools/dashboard/dashboardApp.tsindex 4ad159191c..89c190d6bf 100644--- a/packages/playwright-core/src/tools/dashboard/dashboardApp.ts+++ b/packages/playwright-core/src/tools/dashboard/dashboardApp.ts@@ -20,7 +20,7 @@ import net from 'net';import http from 'http';import { playwright } from '../../inprocess';-import { packageRoot } from '../../package';+import { libPath } from '../../package';import { HttpServer } from '../../server/utils/httpServer';import { makeSocketPath } from '../../server/utils/fileUtils';import { gracefullyProcessExitDoNotHang } from '../../server/utils/processLauncher';@@ -129,9 +129,9 @@ async function handleApiRequest(httpServer: HttpServer, request: http.IncomingMeresponse.end(JSON.stringify({ error: 'Not found' }));}-async function openDashboardApp(): Promise<api.Page> {+async function innerOpenDashboardApp(): Promise<api.Page> {const httpServer = new HttpServer();- const dashboardDir = path.join(packageRoot, 'lib/vite/dashboard');+ const dashboardDir = libPath('vite', 'dashboard');httpServer.routePrefix('/api/', (request: http.IncomingMessage, response: http.ServerResponse) => {handleApiRequest(httpServer, request, response).catch(e => {@@ -215,7 +215,7 @@ async function launchApp(appName: string) {gracefullyProcessExitDoNotHang(0);});- const image = await fs.promises.readFile(path.join(__dirname, 'appIcon.png'));+ const image = await fs.promises.readFile(libPath('tools', 'dashboard', 'appIcon.png'));// This is local Playwright, so I can access private methods.// eslint-disable-next-line no-restricted-syntax -- it is not essential, can regress.await (page as any)._setDockTile?.(image);@@ -278,9 +278,13 @@ async function acquireSingleton(): Promise<net.Server> {});}-async function main() {+export async function openDashboardApp() {let server: net.Server | undefined;process.on('exit', () => server?.close());+ process.on('unhandledRejection', error => {+ // eslint-disable-next-line no-console+ console.error('Unhandled promise rejection:', error);+ });const underTest = !!process.env.PLAYWRIGHT_DASHBOARD_DEBUG_PORT;if (!underTest) {try {@@ -289,7 +293,7 @@ async function main() {return;}}- const page = await openDashboardApp();+ const page = await innerOpenDashboardApp();server?.on('connection', socket => {socket.on('data', data => {if (data.toString() === 'bringToFront')@@ -297,10 +301,3 @@ async function main() {});});}--process.on('unhandledRejection', error => {- // eslint-disable-next-line no-console- console.error('Unhandled promise rejection:', error);-});--void main();diff --git a/packages/playwright-core/src/tools/index.ts b/packages/playwright-core/src/tools/index.tsindex 5b98d33f06..000ef8036d 100644--- a/packages/playwright-core/src/tools/index.ts+++ b/packages/playwright-core/src/tools/index.ts@@ -26,6 +26,11 @@ export { resolveCLIConfigForCLI, resolveCLIConfigForMCP } from './mcp/config';export { isProfileLocked } from './mcp/browserFactory';export { compareSemver } from './utils/socketConnection';export { extractTrace, DirTraceLoaderBackend } from './trace/traceParser';+export { decorateMCPCommand } from './mcp/program';+export { program as cliProgram } from './cli-client/program';+export { generateHelp, generateHelpJSON } from './cli-daemon/helpGenerator';+export { decorateProgram as decorateCliDaemonProgram } from './cli-daemon/program';+export { openDashboardApp } from './dashboard/dashboardApp';export type { ContextConfig } from './backend/context';export type { CallToolRequest, CallToolResult, Tool } from './backend/tool';diff --git a/packages/playwright-core/src/tools/mcp/index.ts b/packages/playwright-core/src/tools/mcp/index.tsindex 606861905a..7e16894b6a 100644--- a/packages/playwright-core/src/tools/mcp/index.ts+++ b/packages/playwright-core/src/tools/mcp/index.ts@@ -19,14 +19,13 @@ import { filteredTools } from '../backend/tools';import { createBrowser } from './browserFactory';import { BrowserBackend } from '../backend/browserBackend';import { createServer } from '../utils/mcp/server';+import { packageJSON } from '../../package';import type { BrowserContext } from 'playwright';import type { Server } from '@modelcontextprotocol/sdk/server/index.js';import type { ClientInfo, ServerBackendFactory } from '../utils/mcp/server';import type { Config } from './config.d';-const packageJSON = require('../../../package.json');-export async function createConnection(userConfig: Config = {}, contextGetter?: () => Promise<BrowserContext>): Promise<Server> {const config = await resolveConfig(userConfig);const tools = filteredTools(config);diff --git a/packages/playwright-core/src/tools/mcp/program.ts b/packages/playwright-core/src/tools/mcp/program.tsindex 69ad3bb641..02c5fb0274 100644--- a/packages/playwright-core/src/tools/mcp/program.ts+++ b/packages/playwright-core/src/tools/mcp/program.ts@@ -23,12 +23,13 @@ import { createBrowser, createBrowserWithInfo } from './browserFactory';import { BrowserBackend } from '../backend/browserBackend';import { filteredTools } from '../backend/tools';import { testDebug } from './log';+import { packageJSON } from '../../package';import type { Command } from '../../utilsBundle';import type { ClientInfo } from '../utils/mcp/server';import type * as playwright from '../../..';-const version = require('../../../package.json').version;+const version = packageJSON.version;export function decorateMCPCommand(command: Command) {commanddiff --git a/packages/playwright-core/src/tools/trace/DEPS.list b/packages/playwright-core/src/tools/trace/DEPS.listindex 9aa231b27c..006ec02875 100644--- a/packages/playwright-core/src/tools/trace/DEPS.list+++ b/packages/playwright-core/src/tools/trace/DEPS.list@@ -1,4 +1,5 @@[*]+../../package.ts../../utils/isomorphic/**../../server/utils/zipFile.ts./*.tsdiff --git a/packages/playwright-core/src/tools/trace/installSkill.ts b/packages/playwright-core/src/tools/trace/installSkill.tsindex e45eefcc1c..eb3f348f3c 100644--- a/packages/playwright-core/src/tools/trace/installSkill.ts+++ b/packages/playwright-core/src/tools/trace/installSkill.ts@@ -19,9 +19,11 @@import fs from 'fs';import path from 'path';+import { libPath } from '../../package';+export async function installSkill() {const cwd = process.cwd();- const skillSource = path.join(__dirname, 'SKILL.md');+ const skillSource = libPath('tools', 'trace', 'SKILL.md');const destDir = path.join(cwd, '.claude', 'skills', 'playwright-trace');await fs.promises.mkdir(destDir, { recursive: true });const destFile = path.join(destDir, 'SKILL.md');diff --git a/packages/playwright-core/src/tools/trace/traceSnapshot.ts b/packages/playwright-core/src/tools/trace/traceSnapshot.tsindex 2805c905d3..bc19b79d5a 100644--- a/packages/playwright-core/src/tools/trace/traceSnapshot.ts+++ b/packages/playwright-core/src/tools/trace/traceSnapshot.ts@@ -20,7 +20,7 @@ import { TraceLoader } from '../../utils/isomorphic/trace/traceLoader';import { BrowserBackend } from '../backend/browserBackend';import { browserTools } from '../backend/tools';import { playwright } from '../../inprocess';-import { gracefullyCloseAll } from '../../utils';+import { gracefullyCloseAll, HttpServer, SnapshotServer } from '../../utils';import { parseCommand } from '../cli-daemon/command';import { minimist } from '../cli-client/minimist';import { commands } from '../cli-daemon/commands';@@ -82,9 +82,6 @@ export async function traceSnapshot(actionId: string, options: { name?: string,}async function serveTraceSnapshot(storage: SnapshotStorage, loader: TraceLoader, pageId: string, snapshotKey: string): Promise<{ url: string, stop: () => Promise<void> }> {- const { SnapshotServer } = require('../../utils/isomorphic/trace/snapshotServer') as typeof import('../../utils/isomorphic/trace/snapshotServer');- const { HttpServer } = require('../../server/utils/httpServer') as typeof import('../../server/utils/httpServer');-const snapshotServer = new SnapshotServer(storage, sha1 => loader.resourceForSha1(sha1));const httpServer = new HttpServer();diff --git a/packages/playwright-core/src/utils/isomorphic/index.ts b/packages/playwright-core/src/utils/isomorphic/index.tsindex ada2af9bee..ae29744571 100644--- a/packages/playwright-core/src/utils/isomorphic/index.ts+++ b/packages/playwright-core/src/utils/isomorphic/index.ts@@ -33,5 +33,13 @@ export * from './stringUtils';export * from './formatUtils';export * from './time';export * from './timeoutRunner';+export * from './trace/snapshotServer';export * from './urlMatch';+export * from './cssParser';+export * from './locatorParser';+export * from './selectorParser';+export * from './trace/snapshotStorage';+export * from './trace/traceLoader';+export * from './trace/traceModel';+export * from './trace/traceUtils';export * from './yaml';diff --git a/packages/playwright-core/src/utils/isomorphic/urlMatch.ts b/packages/playwright-core/src/utils/isomorphic/urlMatch.tsindex 590d90d6e2..cdd7f0aab0 100644--- a/packages/playwright-core/src/utils/isomorphic/urlMatch.ts+++ b/packages/playwright-core/src/utils/isomorphic/urlMatch.ts@@ -96,7 +96,7 @@ export type URLPattern = {username: string;};-// @ts-expect-error URLPattern is not in @types/node yet+// @ts-ignore URLPattern is not in @types/node yet// eslint-disable-next-line no-restricted-globalsexport const isURLPattern = (v: unknown): v is URLPattern => typeof globalThis.URLPattern === 'function' && v instanceof globalThis.URLPattern;@@ -128,12 +128,12 @@ export function serializeURLMatch(match: URLMatch): SerializedURLMatch | undefinfunction deserializeURLPattern(v: ReturnType<typeof serializeURLPattern>): URLPattern | ((url: URL) => boolean) {// Client is on Node 24+ and can use URLPattern, Server is not. Let's match all URLs on the server, they'll be filtered again on the client.- // @ts-expect-error URLPattern is not in @types/node yet+ // @ts-ignore URLPattern is not in @types/node yet// eslint-disable-next-line no-restricted-globalsif (typeof globalThis.URLPattern !== 'function')return () => true;- // @ts-expect-error URLPattern is not in @types/node yet+ // @ts-ignore URLPattern is not in @types/node yet// eslint-disable-next-line no-restricted-globalsreturn new globalThis.URLPattern({hash: v.hash,diff --git a/packages/playwright-firefox/install.js b/packages/playwright-firefox/install.jsindex 561032d644..d53beb1048 100644--- a/packages/playwright-firefox/install.js+++ b/packages/playwright-firefox/install.js@@ -18,7 +18,7 @@ let install;try {if (!require('playwright-core/lib/coreBundle').serverUtils.isLikelyNpxGlobal())- install = require('playwright-core/lib/coreBundle').sever.installBrowsersForNpmInstall;+ install = require('playwright-core/lib/coreBundle').registry.installBrowsersForNpmInstall;} catch (e) {// Dev build, don't install browsers by default.}diff --git a/packages/playwright-webkit/install.js b/packages/playwright-webkit/install.jsindex dbb98b90eb..f4cb8dfcad 100644--- a/packages/playwright-webkit/install.js+++ b/packages/playwright-webkit/install.js@@ -18,7 +18,7 @@ let install;try {if (!require('playwright-core/lib/coreBundle').serverUtils.isLikelyNpxGlobal())- install = require('playwright-core/lib/coreBundle').sever.installBrowsersForNpmInstall;+ install = require('playwright-core/lib/coreBundle').registry.installBrowsersForNpmInstall;} catch (e) {// Dev build, don't install browsers by default.}diff --git a/packages/playwright/src/matchers/matchers.ts b/packages/playwright/src/matchers/matchers.tsindex 0c6825b2d4..49ee539865 100644--- a/packages/playwright/src/matchers/matchers.ts+++ b/packages/playwright/src/matchers/matchers.ts@@ -511,7 +511,7 @@ export function computeMatcherTitleSuffix(matcherName: string, receiver: any, arconst title = toHaveScreenshotStepTitle(...args);return { short: title ? `(${title})` : '' };}- if (receiver && typeof receiver === 'object' && receiver.constructor?.name === 'Locator') {+ if (receiver && typeof receiver === 'object' && (receiver as any)._apiName === 'Locator') {try {return { long: ' ' + iso.asLocatorDescription('javascript', (receiver as LocatorEx)._selector) };} catch {diff --git a/packages/playwright/src/matchers/toBeTruthy.ts b/packages/playwright/src/matchers/toBeTruthy.tsindex d92a3a92e7..e5bfb47e30 100644--- a/packages/playwright/src/matchers/toBeTruthy.ts+++ b/packages/playwright/src/matchers/toBeTruthy.ts@@ -26,7 +26,7 @@ export async function toBeTruthy(this: ExpectMatcherStateInternal,matcherName: string,locator: Locator,- receiverType: string,+ receiverType: 'Locator',expected: string,arg: string,query: (isNot: boolean, timeout: number) => Promise<{ matches: boolean, log?: string[], received?: any, timedOut?: boolean, errorMessage?: string }>,diff --git a/packages/playwright/src/matchers/toEqual.ts b/packages/playwright/src/matchers/toEqual.tsindex e60260dbc9..40aac4e6f9 100644--- a/packages/playwright/src/matchers/toEqual.ts+++ b/packages/playwright/src/matchers/toEqual.ts@@ -30,7 +30,7 @@ export async function toEqual<T>(this: ExpectMatcherStateInternal,matcherName: string,locator: Locator,- receiverType: string,+ receiverType: 'Locator',query: (isNot: boolean, timeout: number) => Promise<{ matches: boolean, received?: any, log?: string[], timedOut?: boolean, errorMessage?: string }>,expected: T,options: { timeout?: number, contains?: boolean } = {},diff --git a/packages/playwright/src/matchers/toMatchAriaSnapshot.ts b/packages/playwright/src/matchers/toMatchAriaSnapshot.tsindex a63a645684..9d4e13432d 100644--- a/packages/playwright/src/matchers/toMatchAriaSnapshot.ts+++ b/packages/playwright/src/matchers/toMatchAriaSnapshot.ts@@ -43,7 +43,7 @@ export async function toMatchAriaSnapshot(): Promise<MatcherResult<string | RegExp, string>> {const matcherName = 'toMatchAriaSnapshot';expectTypes(receiver, ['Page', 'Locator'], matcherName);- const locator = receiver.constructor.name === 'Page' ? undefined : receiver as LocatorEx;+ const locator = (receiver as any)._apiName === 'Page' ? undefined : receiver as LocatorEx;const testInfo = currentTestInfo();if (!testInfo)diff --git a/packages/playwright/src/matchers/toMatchSnapshot.ts b/packages/playwright/src/matchers/toMatchSnapshot.tsindex 169f26f1a2..5457e96840 100644--- a/packages/playwright/src/matchers/toMatchSnapshot.ts+++ b/packages/playwright/src/matchers/toMatchSnapshot.ts@@ -334,7 +334,7 @@ export async function toHaveScreenshot(return { pass: !this.isNot, message: () => '', name: 'toHaveScreenshot', expected: nameOrOptions };expectTypes(pageOrLocator, ['Page', 'Locator'], 'toHaveScreenshot');- const [page, locator] = pageOrLocator.constructor.name === 'Page' ? [(pageOrLocator as PageEx), undefined] : [(pageOrLocator as Locator).page() as PageEx, pageOrLocator as Locator];+ const [page, locator] = (pageOrLocator as any)._apiName === 'Page' ? [(pageOrLocator as PageEx), undefined] : [(pageOrLocator as Locator).page() as PageEx, pageOrLocator as Locator];const configOptions = testInfo._projectInternal.expect?.toHaveScreenshot || {};const helper = new SnapshotHelper(this, testInfo, 'toHaveScreenshot', locator, undefined, configOptions, nameOrOptions, optOptions);if (!helper.expectedPath.toLowerCase().endsWith('.png'))diff --git a/packages/playwright/src/mcp/test/testContext.ts b/packages/playwright/src/mcp/test/testContext.tsindex d33a3419c7..dcbeb2ffde 100644--- a/packages/playwright/src/mcp/test/testContext.ts+++ b/packages/playwright/src/mcp/test/testContext.ts@@ -18,7 +18,8 @@ import fs from 'fs';import os from 'os';import path from 'path';-import { iso, serverUtils, tools } from 'playwright-core/lib/coreBundle';+import { iso, serverUtils } from 'playwright-core/lib/coreBundle';+import { tools } from 'playwright-core/lib/coreBundle';import { debug } from 'playwright-core/lib/utilsBundle';import { terminalScreen } from '../../reporters/base';diff --git a/packages/playwright/src/runner/testRunner.ts b/packages/playwright/src/runner/testRunner.tsindex e260551653..a9c40751a2 100644--- a/packages/playwright/src/runner/testRunner.ts+++ b/packages/playwright/src/runner/testRunner.ts@@ -18,7 +18,7 @@ import EventEmitter from 'events';import fs from 'fs';import path from 'path';-import { iso, serverUtils, sever } from 'playwright-core/lib/coreBundle';+import { iso, serverUtils, registry } from 'playwright-core/lib/coreBundle';import { loadConfig } from '../common/configLoader';import { Watcher } from '../fsWatcher';@@ -135,7 +135,7 @@ export class TestRunner extends EventEmitter<TestRunnerEventMap> {hasSomeBrowsers(): boolean {for (const browserName of ['chromium', 'webkit', 'firefox']) {try {- sever.registry.findExecutable(browserName)!.executablePathOrDie('javascript');+ registry.registry.findExecutable(browserName)!.executablePathOrDie('javascript');return true;} catch {}@@ -144,8 +144,8 @@ export class TestRunner extends EventEmitter<TestRunnerEventMap> {}async installBrowsers() {- const executables = sever.registry.defaultExecutables();- await sever.registry.install(executables);+ const executables = registry.registry.defaultExecutables();+ await registry.registry.install(executables);}async loadConfig() {diff --git a/packages/playwright/src/util.ts b/packages/playwright/src/util.tsindex e441cb7a3c..6871866d8a 100644--- a/packages/playwright/src/util.ts+++ b/packages/playwright/src/util.ts@@ -168,12 +168,13 @@ export function errorWithFile(file: string, message: string) {return new Error(`${relativeFilePath(file)}: ${message}`);}-export function expectTypes(receiver: any, types: string[], matcherName: string) {- if (typeof receiver !== 'object' || !types.includes(receiver.constructor.name)) {+export function expectTypes(receiver: any, types: ('APIResponse' | 'Page' | 'Locator')[], matcherName: string) {+ if (typeof receiver !== 'object' || !types.includes(receiver._apiName)) {+ const receiverString = typeof receiver === 'object' && receiver !== null ? `${receiver.constructor.name} ${util.inspect(receiver)}` : String(receiver);const commaSeparated = types.slice();const lastType = commaSeparated.pop();const typesString = commaSeparated.length ? commaSeparated.join(', ') + ' or ' + lastType : lastType;- throw new Error(`${matcherName} can be only used with ${typesString} object${types.length > 1 ? 's' : ''}`);+ throw new Error(`${matcherName} can be only used with ${typesString} object${types.length > 1 ? 's' : ''}, was called with ${receiverString}`);}}diff --git a/tests/android/launch-server.spec.ts b/tests/android/launch-server.spec.tsindex bcb51b9ac7..73e66cdee3 100644--- a/tests/android/launch-server.spec.ts+++ b/tests/android/launch-server.spec.ts@@ -14,7 +14,7 @@* limitations under the License.*/-import ws from 'ws';+import { WebSocket, WebSocketServer, type AddressInfo } from 'ws';import { androidTest as test, expect } from './androidTest';import { kTargetClosedErrorMessage } from '../config/errors';@@ -126,13 +126,13 @@ test('android.launchServer BrowserServer.kill() will disconnect the device', astest('android.launchServer should terminate WS connection when device gets disconnected', async ({ playwright }) => {const browserServer = await playwright._android.launchServer();- const forwardingServer = new ws.Server({ port: 0, path: '/connect' });- let receivedConnection: ws.WebSocket | undefined;+ const forwardingServer = new WebSocketServer({ port: 0, path: '/connect' });+ let receivedConnection: WebSocket | undefined;forwardingServer.on('connection', connection => {// Pause the connection until we establish the actual connection to the browser server.connection.pause();receivedConnection = connection;- const actualConnection = new ws.WebSocket(browserServer.wsEndpoint());+ const actualConnection = new WebSocket(browserServer.wsEndpoint());// We need to wait for the actual connection to be established before resumingactualConnection.on('open', () => connection.resume());actualConnection.on('message', message => connection.send(message));@@ -141,13 +141,13 @@ test('android.launchServer should terminate WS connection when device gets discoactualConnection.on('close', () => connection.close());});try {- const device = await playwright._android.connect(`ws://localhost:${(forwardingServer.address() as ws.AddressInfo).port}/connect`);+ const device = await playwright._android.connect(`ws://localhost:${(forwardingServer.address() as AddressInfo).port}/connect`);expect((await device.shell('echo 123')).toString()).toBe('123\n');- expect(receivedConnection!.readyState).toBe(ws.OPEN);+ expect(receivedConnection!.readyState).toBe(WebSocket.OPEN);const waitToClose = new Promise(f => receivedConnection!.on('close', f));await device.close();await waitToClose;- expect(receivedConnection!.readyState).toBe(ws.CLOSED);+ expect(receivedConnection!.readyState).toBe(WebSocket.CLOSED);} finally {await browserServer.close();await new Promise(f => forwardingServer.close(f));diff --git a/tests/config/browserTest.ts b/tests/config/browserTest.tsindex 670b583b32..ad463bed3b 100644--- a/tests/config/browserTest.ts+++ b/tests/config/browserTest.ts@@ -19,17 +19,17 @@ import * as os from 'os';import * as path from 'path';import { baseTest } from './baseTest';import { RunServer, RemoteServer } from './remoteServer';-import { removeFolders } from '../../packages/playwright-core/lib/server/utils/fileUtils';+import { serverUtils } from '../../packages/playwright-core/lib/coreBundle';import { isBidiChannel, parseHar } from '../config/utils';import { createSkipTestPredicate } from '../bidi/expectationUtil';-import { hostPlatform } from '../../packages/playwright-core/src/server/utils/hostPlatform';-import type { PageTestFixtures, PageWorkerFixtures } from '../page/pageTestApi';import type { RemoteServerOptions, PlaywrightServer } from './remoteServer';import type { BrowserContext, BrowserContextOptions, BrowserType, Page } from 'playwright-core';import type { Log } from '../../packages/trace/src/har';import type { TestInfo } from '@playwright/test';+const { removeFolders, hostPlatform } = serverUtils;+export type BrowserTestWorkerFixtures = PageWorkerFixtures & {browserVersion: string;defaultSameSiteCookieValue: string;diff --git a/tests/config/comparator.ts b/tests/config/comparator.tsindex 16ca27aaa9..60fc8e5dec 100644--- a/tests/config/comparator.ts+++ b/tests/config/comparator.ts@@ -14,7 +14,9 @@* limitations under the License.*/-import { getComparator } from '../../packages/playwright-core/lib/server/utils/comparators';+import { serverUtils } from '../../packages/playwright-core/lib/coreBundle';++const { getComparator } = serverUtils;const pngComparator = getComparator('image/png');type ComparatorResult = { diff?: Buffer; errorMessage: string; } | null;diff --git a/tests/config/ghaMarkdownReporter.ts b/tests/config/ghaMarkdownReporter.tsindex 91d974bddf..e90151c714 100644--- a/tests/config/ghaMarkdownReporter.ts+++ b/tests/config/ghaMarkdownReporter.ts@@ -16,7 +16,7 @@import MarkdownReporter from '../../packages/playwright/src/reporters/markdown';-import type { MetadataWithCommitInfo } from 'playwright/src/isomorphic/types';+import type { MetadataWithCommitInfo } from '@testIsomorphic/types';import type { IssueCommentEdge, Repository } from '@octokit/graphql-schema';class GHAMarkdownReporter extends MarkdownReporter {@@ -25,14 +25,12 @@ class GHAMarkdownReporter extends MarkdownReporter {private core: typeof import('@actions/core');override async publishReport(report: string) {- // @ts-expect-error dynamic importthis.core = await import('@actions/core');const token = process.env.GITHUB_TOKEN || this.core.getInput('github-token');if (!token) {this.core.setFailed('Missing "github-token" input');throw new Error('Missing "github-token" input');}- // @ts-expect-error dynamic importconst { context, getOctokit } = await import('@actions/github');this.context = context;this.octokit = getOctokit(token);diff --git a/tests/config/proxy.ts b/tests/config/proxy.tsindex 6fbad1ca7f..ae9f50adcd 100644--- a/tests/config/proxy.ts+++ b/tests/config/proxy.ts@@ -18,8 +18,12 @@ import type { IncomingMessage } from 'http';import type { ProxyServer } from '../third_party/proxy';import { createProxy } from '../third_party/proxy';import net from 'net';-import type { SocksSocketClosedPayload, SocksSocketDataPayload, SocksSocketRequestedPayload } from 'playwright-core/src/server/utils/socksProxy';-import { SocksProxy } from '../../packages/playwright-core/lib/server/utils/socksProxy';+import { serverUtils } from '../../packages/playwright-core/lib/coreBundle';++type SocksSocketClosedPayload = serverUtils.SocksSocketClosedPayload;+type SocksSocketDataPayload = serverUtils.SocksSocketDataPayload;+type SocksSocketRequestedPayload = serverUtils.SocksSocketRequestedPayload;+const { SocksProxy } = serverUtils;// Certain browsers perform telemetry requests which we want to ignore.const kConnectHostsToIgnore = new Set([diff --git a/tests/config/serverFixtures.ts b/tests/config/serverFixtures.tsindex 12dad5d99b..d36b1e9f93 100644--- a/tests/config/serverFixtures.ts+++ b/tests/config/serverFixtures.ts@@ -18,9 +18,11 @@ import type { Fixtures } from '@playwright/test';import path from 'path';import { TestServer } from './testserver';import { TestProxy } from './proxy';-import type { SocksSocketRequestedPayload } from 'playwright-core/src/server/utils/socksProxy';+import { serverUtils } from '../../packages/playwright-core/lib/coreBundle';-import { SocksProxy } from '../../packages/playwright-core/lib/server/utils/socksProxy';+type SocksSocketRequestedPayload = serverUtils.SocksSocketRequestedPayload;+const { SocksProxy } = serverUtils;+type SocksProxy = InstanceType<typeof SocksProxy>;export type ServerWorkerOptions = {loopback?: string;diff --git a/tests/config/testMode.ts b/tests/config/testMode.tsindex aa30c20910..0d86aa0762 100644--- a/tests/config/testMode.ts+++ b/tests/config/testMode.ts@@ -14,20 +14,19 @@* limitations under the License.*/-import { oop } from '../../packages/playwright-core/lib/coreBundle';-import type { Playwright } from '../../packages/playwright-core/lib/client/playwright';+import { oop, client } from '../../packages/playwright-core/lib/coreBundle';export type TestModeName = 'default' | 'driver' | 'service' | 'service2' | 'wsl';const { start } = oop;interface TestMode {- setup(): Promise<Playwright>;+ setup(): Promise<client.Playwright>;teardown(): Promise<void>;}export class DriverTestMode implements TestMode {- private _impl: { playwright: Playwright; stop: () => Promise<void>; };+ private _impl: { playwright: client.Playwright; stop: () => Promise<void>; };async setup() {this._impl = await start({diff --git a/tests/config/testserver/index.ts b/tests/config/testserver/index.tsindex 68ee850656..914551b5e8 100644--- a/tests/config/testserver/index.ts+++ b/tests/config/testserver/index.ts@@ -22,9 +22,11 @@ import type net from 'net';import path from 'path';import util from 'util';import type stream from 'stream';-import ws from 'ws';+import { WebSocket, WebSocketServer } from 'ws';import zlib, { gzip } from 'zlib';-import { createHttpServer, createHttpsServer } from '../../../packages/playwright-core/lib/server/utils/network';+import { serverUtils } from '../../../packages/playwright-core/lib/coreBundle';++const { createHttpServer, createHttpsServer } = serverUtils;const fulfillSymbol = Symbol('fulfil callback');const rejectSymbol = Symbol('reject callback');@@ -38,7 +40,7 @@ type UpgradeActions = {export class TestServer {private _server: http.Server;- private _wsServer: ws.WebSocketServer;+ private _wsServer: WebSocketServer;private _dirPath: string;readonly debugServer: any;private _startTime: Date;@@ -84,7 +86,7 @@ export class TestServer {elsethis._server = createHttpServer(this._onRequest.bind(this));this._server.on('connection', socket => this._onSocket(socket));- this._wsServer = new ws.WebSocketServer({ noServer: true });+ this._wsServer = new WebSocketServer({ noServer: true });this._server.on('upgrade', async (request, socket, head) => {const doUpgrade = () => {this._wsServer.handleUpgrade(request, socket, head, ws => {@@ -321,7 +323,7 @@ export class TestServer {}}- onceWebSocketConnection(handler: (socket: ws.WebSocket, request: http.IncomingMessage) => void) {+ onceWebSocketConnection(handler: (socket: WebSocket, request: http.IncomingMessage) => void) {this._wsServer.once('connection', handler);}@@ -336,7 +338,7 @@ export class TestServer {}waitForWebSocket() {- return new Promise<ws.WebSocket>(fulfill => this._wsServer.once('connection', (ws, req) => fulfill(ws)));+ return new Promise<WebSocket>(fulfill => this._wsServer.once('connection', (ws, req) => fulfill(ws)));}sendOnWebSocketConnection(data) {diff --git a/tests/config/utils.ts b/tests/config/utils.tsindex df61cffcb0..d5b9ae3137 100644--- a/tests/config/utils.ts+++ b/tests/config/utils.ts@@ -14,16 +14,17 @@* limitations under the License.*/+import { tools } from '../../packages/playwright-core/lib/coreBundle';+import { serverUtils, iso } from '../../packages/playwright-core/lib/coreBundle';++import type { iso as isoType } from '../../packages/playwright-core/lib/coreBundle';import type { Locator, Frame, Page } from 'playwright-core';-import { ZipFile } from '../../packages/playwright-core/lib/server/utils/zipFile';import type { StackFrame } from '../../packages/protocol/src/channels';-import { parseClientSideCallMetadata } from '../../packages/playwright-core/lib/utils/isomorphic/trace/traceUtils';-import { TraceLoader } from '../../packages/playwright-core/src/utils/isomorphic/trace/traceLoader';-import { TraceModel } from '../../packages/playwright-core/src/utils/isomorphic/trace/traceModel';import type { ActionTraceEvent, TraceEvent } from '@trace/trace';-import { renderTitleForCall } from '../../packages/playwright-core/lib/utils/isomorphic/protocolFormatter';-import { tools } from '../../packages/playwright-core/lib/coreBundle';-import type { SnapshotStorage } from '../../packages/playwright-core/src/utils/isomorphic/trace/snapshotStorage';++const { TraceLoader, TraceModel } = iso;+type TraceModel = InstanceType<typeof TraceModel>;+type SnapshotStorage = isoType.SnapshotStorage;export type BoundingBox = Awaited<ReturnType<Locator['boundingBox']>>;@@ -105,7 +106,7 @@ export function suppressCertificateWarning() {}export async function parseTraceRaw(file: string): Promise<{ events: any[], resources: Map<string, Buffer>, actions: string[], actionObjects: ActionTraceEvent[], stacks: Map<string, StackFrame[]> }> {- const zipFS = new ZipFile(file);+ const zipFS = new serverUtils.ZipFile(file);const resources = new Map<string, Buffer>();for (const entry of await zipFS.entries())resources.set(entry, await zipFS.read(entry));@@ -150,7 +151,7 @@ export async function parseTraceRaw(file: string): Promise<{ events: any[], resoconst stacks: Map<string, StackFrame[]> = new Map();for (const stacksFile of [...resources.keys()].filter(name => name.endsWith('.stacks'))) {- for (const [key, value] of parseClientSideCallMetadata(JSON.parse(resources.get(stacksFile)!.toString())))+ for (const [key, value] of iso.parseClientSideCallMetadata(JSON.parse(resources.get(stacksFile)!.toString())))stacks.set(key, value);}@@ -159,7 +160,7 @@ export async function parseTraceRaw(file: string): Promise<{ events: any[], resoreturn {events,resources,- actions: actionObjects.map(a => renderTitleForCall({ ...a, type: a.class })),+ actions: actionObjects.map(a => iso.renderTitleForCall({ ...a, type: a.class })),actionObjects,stacks,};@@ -175,7 +176,7 @@ export async function parseTrace(file: string): Promise<{ snapshots: SnapshotSto}export async function parseHar(file: string): Promise<Map<string, Buffer>> {- const zipFS = new ZipFile(file);+ const zipFS = new serverUtils.ZipFile(file);const resources = new Map<string, Buffer>();for (const entry of await zipFS.entries())resources.set(entry, await zipFS.read(entry));diff --git a/tests/electron/electronTest.ts b/tests/electron/electronTest.tsindex edb57bc34c..fa65fe0430 100644--- a/tests/electron/electronTest.ts+++ b/tests/electron/electronTest.ts@@ -22,10 +22,13 @@ import type { ElectronApplication, Page, Electron } from '@playwright/test';import type { PageTestFixtures, PageWorkerFixtures } from '../page/pageTestApi';import type { TraceViewerFixtures } from '../config/traceViewerFixtures';import { traceViewerFixtures } from '../config/traceViewerFixtures';-import { removeFolders } from '../../packages/playwright-core/lib/server/utils/fileUtils';+import { serverUtils } from '../../packages/playwright-core/lib/coreBundle';import { inheritAndCleanEnv } from '../config/utils';+export { expect } from '@playwright/test';+const { removeFolders } = serverUtils;+type ElectronTestFixtures = PageTestFixtures & {electronApp: ElectronApplication;launchElectronApp: (appFile: string, args?: string[], options?: Parameters<Electron['launch']>[0]) => Promise<ElectronApplication>;diff --git a/tests/electron/globalSetup.ts b/tests/electron/globalSetup.tsindex 9edeef68c5..98eaf01a8b 100644--- a/tests/electron/globalSetup.ts+++ b/tests/electron/globalSetup.ts@@ -15,7 +15,8 @@*/import assert from 'assert';-import { spawnAsync } from '../../packages/playwright-core/lib/server/utils/spawnAsync';+import { serverUtils } from '../../packages/playwright-core/lib/coreBundle';+const { spawnAsync } = serverUtils;export default async () => {const result = await spawnAsync(['npx', 'electron', `"${require.resolve('./electron-print-chromium-version.js')}"`, '--no-sandbox'].join(' '), [], {diff --git a/tests/image_tools/fixtures.spec.ts b/tests/image_tools/fixtures.spec.tsindex f091905096..6f95b6ba23 100644--- a/tests/image_tools/fixtures.spec.ts+++ b/tests/image_tools/fixtures.spec.ts@@ -16,10 +16,12 @@import { test, expect } from '../playwright-test/stable-test-runner';import { PNG } from 'playwright-core/lib/utilsBundle';-import { compare } from '../../packages/playwright-core/src/server/utils/image_tools/compare';+import { serverUtils } from '../../packages/playwright-core/lib/coreBundle';import fs from 'fs';import path from 'path';+const { compare } = serverUtils;+function listFixtures(root: string, fixtures: Set<string> = new Set()) {for (const item of fs.readdirSync(root, { withFileTypes: true })) {const p = path.join(root, item.name);diff --git a/tests/image_tools/unit.spec.ts b/tests/image_tools/unit.spec.tsindex c306ed2497..263bedde8f 100644--- a/tests/image_tools/unit.spec.ts+++ b/tests/image_tools/unit.spec.ts@@ -15,12 +15,14 @@*/import { test } from '../playwright-test/stable-test-runner';-import { ssim, FastStats } from '../../packages/playwright-core/src/server/utils/image_tools/stats';-import { ImageChannel } from '../../packages/playwright-core/src/server/utils/image_tools/imageChannel';-import { srgb2xyz, xyz2lab, colorDeltaE94 } from '../../packages/playwright-core/src/server/utils/image_tools/colorUtils';+import { serverUtils } from '../../packages/playwright-core/lib/coreBundle';+import referenceSSIM from 'ssim.js';import { randomPNG, assertEqual, grayChannel } from './utils';+const { ssim, FastStats, ImageChannel, srgb2xyz, xyz2lab, colorDeltaE94 } = serverUtils;+type ImageChannel = InstanceType<typeof ImageChannel>;+test('srgb to lab conversion should work', async () => {const srgb = [123, 81, 252];const [x, y, z] = srgb2xyz(srgb);diff --git a/tests/image_tools/utils.ts b/tests/image_tools/utils.tsindex 7b645531ff..77eae1da84 100644--- a/tests/image_tools/utils.ts+++ b/tests/image_tools/utils.ts@@ -15,7 +15,9 @@*/import { PNG } from 'playwright-core/lib/utilsBundle';-import { ImageChannel } from '../../packages/playwright-core/src/server/utils/image_tools/imageChannel';+import { serverUtils } from '../../packages/playwright-core/lib/coreBundle';++const { ImageChannel } = serverUtils;// mulberry32export function createRandom(seed) {diff --git a/tests/installation/globalSetup.ts b/tests/installation/globalSetup.tsindex d875f8b215..d982c3ca2c 100644--- a/tests/installation/globalSetup.ts+++ b/tests/installation/globalSetup.ts@@ -16,10 +16,11 @@import path from 'path';import fs from 'fs';-import { spawnAsync } from '../../packages/playwright-core/lib/server/utils/spawnAsync';-import { removeFolders } from '../../packages/playwright-core/lib/server/utils/fileUtils';+import { serverUtils } from '../../packages/playwright-core/lib/coreBundle';import { TMP_WORKSPACES } from './npmTest';+const { spawnAsync, removeFolders } = serverUtils;+const PACKAGE_BUILDER_SCRIPT = path.join(__dirname, '..', '..', 'utils', 'pack_package.js');async function globalSetup() {diff --git a/tests/installation/npmTest.ts b/tests/installation/npmTest.tsindex 73cca42fd7..68e6734ee4 100644--- a/tests/installation/npmTest.ts+++ b/tests/installation/npmTest.ts@@ -22,10 +22,11 @@ import debugLogger from 'debug';import { Registry } from './registry';import type { CommonFixtures, CommonWorkerFixtures } from '../config/commonFixtures';import { commonFixtures } from '../config/commonFixtures';-import { removeFolders } from '../../packages/playwright-core/lib/server/utils/fileUtils';-import { spawnAsync } from '../../packages/playwright-core/lib/server/utils/spawnAsync';+import { serverUtils } from '../../packages/playwright-core/lib/coreBundle';import type { SpawnOptions } from 'child_process';+const { removeFolders, spawnAsync } = serverUtils;+export const TMP_WORKSPACES = path.join(os.platform() === 'darwin' ? '/tmp' : os.tmpdir(), 'pwt', 'workspaces');const debug = debugLogger('itest');diff --git a/tests/installation/playwright-electron-should-work.spec.ts b/tests/installation/playwright-electron-should-work.spec.tsindex 5c6ced0948..09a6a5a5a3 100755--- a/tests/installation/playwright-electron-should-work.spec.ts+++ b/tests/installation/playwright-electron-should-work.spec.ts@@ -15,7 +15,7 @@*/import { test } from './npmTest';import fs from 'fs';-import { expect } from 'packages/playwright-test';+import { expect } from '../../packages/playwright-test';import path from 'path';test('electron should work', async ({ exec, tsc, writeFiles }) => {diff --git a/tests/installation/registry.ts b/tests/installation/registry.tsindex fd3194a039..83c635662f 100644--- a/tests/installation/registry.ts+++ b/tests/installation/registry.ts@@ -19,8 +19,9 @@ import type { Server } from 'http';import type http from 'http';import https from 'https';import path from 'path';-import { spawnAsync } from '../../packages/playwright-core/lib/server/utils/spawnAsync';-import { createHttpServer } from '../../packages/playwright-core/lib/server/utils/network';+import { serverUtils } from '../../packages/playwright-core/lib/coreBundle';++const { spawnAsync, createHttpServer } = serverUtils;const kPublicNpmRegistry = 'https://registry.npmjs.org';const kContentTypeAbbreviatedMetadata = 'application/vnd.npm.install-v1+json';diff --git a/tests/library/browsercontext-fetch.spec.ts b/tests/library/browsercontext-fetch.spec.tsindex d8f6f5a5f6..8d0457b8a0 100644--- a/tests/library/browsercontext-fetch.spec.ts+++ b/tests/library/browsercontext-fetch.spec.ts@@ -22,7 +22,7 @@ import { pipeline } from 'stream';import zlib from 'zlib';import { contextTest as it, expect } from '../config/browserTest';import { suppressCertificateWarning } from '../config/utils';-import { kTargetClosedErrorMessage } from 'tests/config/errors';+import { kTargetClosedErrorMessage } from '../config/errors';it.skip(({ mode }) => mode !== 'default');diff --git a/tests/library/browsercontext-storage-state.spec.ts b/tests/library/browsercontext-storage-state.spec.tsindex 5715ba3683..b8b03daece 100644--- a/tests/library/browsercontext-storage-state.spec.ts+++ b/tests/library/browsercontext-storage-state.spec.ts@@ -15,7 +15,7 @@* limitations under the License.*/-import { attachFrame } from 'tests/config/utils';+import { attachFrame } from '../config/utils';import { browserTest as it, expect } from '../config/browserTest';import fs from 'fs';diff --git a/tests/library/browsercontext-viewport.spec.ts b/tests/library/browsercontext-viewport.spec.tsindex 4d70520968..255bec61b2 100644--- a/tests/library/browsercontext-viewport.spec.ts+++ b/tests/library/browsercontext-viewport.spec.ts@@ -19,7 +19,8 @@ import { devices } from '@playwright/test';import { contextTest as it, expect } from '../config/browserTest';import { browserTest } from '../config/browserTest';import { verifyViewport } from '../config/utils';-import { deviceDescriptors } from 'packages/playwright-core/lib/server/deviceDescriptors';+import { sever } from '../../packages/playwright-core/lib/coreBundle';+const { deviceDescriptors } = sever;it('should get the proper default viewport size', async ({ page, server }) => {await verifyViewport(page, 1280, 720);diff --git a/tests/library/browsertype-connect.spec.ts b/tests/library/browsertype-connect.spec.tsindex c875b38067..e3aadd67e3 100644--- a/tests/library/browsertype-connect.spec.ts+++ b/tests/library/browsertype-connect.spec.ts@@ -19,13 +19,14 @@ import fs from 'fs';import type http from 'http';import type net from 'net';import * as path from 'path';-import { getUserAgent, getPlaywrightVersion } from '../../packages/playwright-core/lib/server/utils/userAgent';+import { serverUtils } from '../../packages/playwright-core/lib/coreBundle';import WebSocket from 'ws';import { expect, playwrightTest } from '../config/browserTest';import { parseTraceRaw, suppressCertificateWarning, rafraf } from '../config/utils';import formidable from 'formidable';import type { Browser, ConnectOptions } from 'playwright-core';-import { createHttpServer } from '../../packages/playwright-core/lib/server/utils/network';++const { getUserAgent, getPlaywrightVersion, createHttpServer } = serverUtils;import { kTargetClosedErrorMessage } from '../config/errors';import { RunServer } from '../config/remoteServer';diff --git a/tests/library/chromium/connect-over-cdp.spec.ts b/tests/library/chromium/connect-over-cdp.spec.tsindex 2e11f9e1ff..6bf93fcb96 100644--- a/tests/library/chromium/connect-over-cdp.spec.ts+++ b/tests/library/chromium/connect-over-cdp.spec.ts@@ -18,11 +18,12 @@import { playwrightTest as test, expect } from '../../config/browserTest';import http from 'http';import fs from 'fs';-import { getUserAgent } from '../../../packages/playwright-core/lib/server/utils/userAgent';-import { WebSocketTransport } from '../../../packages/playwright-core/lib/server/transport';+import { serverUtils, sever } from '../../../packages/playwright-core/lib/coreBundle';import { suppressCertificateWarning } from '../../config/utils';-import { nullProgress } from '../../../packages/playwright-core/lib/server/progress';-import type { Frame } from '../../../packages/playwright-core/lib/server/frames';++const { getUserAgent } = serverUtils;+const { WebSocketTransport, nullProgress } = sever;+type Frame = sever.Frame;test.skip(({ mode }) => mode === 'service2');diff --git a/tests/library/client-certificates.spec.ts b/tests/library/client-certificates.spec.tsindex b7546c47ee..c0557a193e 100644--- a/tests/library/client-certificates.spec.ts+++ b/tests/library/client-certificates.spec.ts@@ -22,9 +22,10 @@ import type http2 from 'http2';import type http from 'http';import { expect, playwrightTest as base } from '../config/browserTest';import type net from 'net';-import type { BrowserContextOptions } from 'packages/playwright-test';+import type { BrowserContextOptions } from '../../packages/playwright-test';import { setupSocksForwardingServer } from '../config/proxy';-const { createHttpsServer, createHttp2Server } = require('../../packages/playwright-core/lib/utils');+import { serverUtils } from '../../packages/playwright-core/lib/coreBundle';+const { createHttpsServer, createHttp2Server } = serverUtils;type TestOptions = {startCCServer(options?: {diff --git a/tests/library/component-parser.spec.ts b/tests/library/component-parser.spec.tsindex cad2aaca64..6411609c29 100644--- a/tests/library/component-parser.spec.ts+++ b/tests/library/component-parser.spec.ts@@ -15,8 +15,11 @@*/import { playwrightTest as it, expect } from '../config/browserTest';-import type { AttributeSelector } from '../../packages/playwright-core/src/utils/isomorphic/selectorParser';-import { parseAttributeSelector } from '../../packages/playwright-core/lib/utils/isomorphic/selectorParser';+import type { iso } from '../../packages/playwright-core/lib/coreBundle';+import { iso as _iso } from '../../packages/playwright-core/lib/coreBundle';++type AttributeSelector = iso.AttributeSelector;+const { parseAttributeSelector } = _iso;const parse = (selector: string) => parseAttributeSelector(selector, false);const serialize = (parsed: AttributeSelector) => {diff --git a/tests/library/css-parser.spec.ts b/tests/library/css-parser.spec.tsindex e6ff046579..45cc6df389 100644--- a/tests/library/css-parser.spec.ts+++ b/tests/library/css-parser.spec.ts@@ -15,7 +15,9 @@*/import { playwrightTest as it, expect } from '../config/browserTest';-import { parseCSS, serializeSelector as serialize } from '../../packages/playwright-core/lib/utils/isomorphic/cssParser';+import { iso } from '../../packages/playwright-core/lib/coreBundle';++const { parseCSS, serializeSelector: serialize } = iso;const parse = (selector: string) => {return parseCSS(selector, new Set(['text', 'not', 'has', 'react', 'scope', 'right-of', 'is'])).selector;diff --git a/tests/library/debug-controller.spec.ts b/tests/library/debug-controller.spec.tsindex 1ceb9e5048..46f2fe1b92 100644--- a/tests/library/debug-controller.spec.ts+++ b/tests/library/debug-controller.spec.ts@@ -15,13 +15,15 @@*/import { expect, playwrightTest as baseTest } from '../config/browserTest';-import { PlaywrightServer } from '../../packages/playwright-core/lib/remote/playwrightServer';-import { createGuid } from '../../packages/playwright-core/lib/server/utils/crypto';+import { remote, serverUtils } from '../../packages/playwright-core/lib/coreBundle';+const { PlaywrightServer } = remote;import { Backend } from '../config/debugControllerBackend';import type { Browser, BrowserContext } from '@playwright/test';import type * as channels from '@protocol/channels';import { roundBox } from '../config/utils';+const { createGuid } = serverUtils;+type BrowserWithReuse = Browser & { newContextForReuse: () => Promise<BrowserContext> };type Fixtures = {wsEndpoint: string;diff --git a/tests/library/events/remove-all-listeners-wait.spec.ts b/tests/library/events/remove-all-listeners-wait.spec.tsindex dbc141d6d8..d66d34e0cd 100644--- a/tests/library/events/remove-all-listeners-wait.spec.ts+++ b/tests/library/events/remove-all-listeners-wait.spec.ts@@ -15,10 +15,12 @@* limitations under the License.*/-import { ManualPromise } from '../../../packages/playwright-core/lib/utils/isomorphic/manualPromise';+import { iso } from '../../../packages/playwright-core/lib/coreBundle';import { EventEmitter } from './utils';import { test, expect } from '@playwright/test';+const { ManualPromise } = iso;+test('should not throw with ignoreErrors', async () => {const ee = new EventEmitter();const releaseHandler = new ManualPromise();diff --git a/tests/library/events/utils.ts b/tests/library/events/utils.tsindex 7ba4816376..242b89786c 100644--- a/tests/library/events/utils.ts+++ b/tests/library/events/utils.ts@@ -20,8 +20,9 @@// USE OR OTHER DEALINGS IN THE SOFTWARE.import { expect } from '@playwright/test';-import { EventEmitter as OriginalEventEmitter } from '../../../packages/playwright-core/lib/client/eventEmitter';-import { nodePlatform } from '../../../packages/playwright-core/lib/server/utils/nodePlatform';+import { client, serverUtils } from '../../../packages/playwright-core/lib/coreBundle';++const { nodePlatform } = serverUtils;export const mustNotCall = (msg?: string) => {return function mustNotCall() {@@ -47,7 +48,8 @@ export const mustCall = (fn?: Function, exact?: number) => {};};-export class EventEmitter extends OriginalEventEmitter {+/** as any breaks long TS resolution chain that makes tests unhappy */+export class EventEmitter extends (client as any).EventEmitter {constructor() {super(nodePlatform);}diff --git a/tests/library/global-fetch.spec.ts b/tests/library/global-fetch.spec.tsindex 3aed43f650..2a8da017a6 100644--- a/tests/library/global-fetch.spec.ts+++ b/tests/library/global-fetch.spec.ts@@ -16,9 +16,11 @@import os from 'os';import * as util from 'util';-import { getPlaywrightVersion } from '../../packages/playwright-core/lib/server/utils/userAgent';+import { serverUtils } from '../../packages/playwright-core/lib/coreBundle';import { expect, playwrightTest as base } from '../config/browserTest';-import { kTargetClosedErrorMessage } from 'tests/config/errors';+import { kTargetClosedErrorMessage } from '../config/errors';++const { getPlaywrightVersion } = serverUtils;const it = base.extend({context: async ({}, use) => {diff --git a/tests/library/har.spec.ts b/tests/library/har.spec.tsindex c67027fa7b..58fa3bfb21 100644--- a/tests/library/har.spec.ts+++ b/tests/library/har.spec.ts@@ -22,7 +22,8 @@ import type { AddressInfo } from 'net';import type { Log } from '../../packages/trace/src/har';import { parseHar } from '../config/utils';import { TestServer } from '../config/testserver';-const { createHttp2Server } = require('../../packages/playwright-core/lib/utils');+import { serverUtils } from '../../packages/playwright-core/lib/coreBundle';+const { createHttp2Server } = serverUtils;async function pageWithHar(contextFactory: (options?: BrowserContextOptions) => Promise<BrowserContext>, testInfo: any, options: { outputPath?: string } & Partial<Pick<BrowserContextOptions['recordHar'], 'content' | 'omitContent' | 'mode'>> = {}) {const harPath = testInfo.outputPath(options.outputPath || 'test.har');diff --git a/tests/library/headful.spec.ts b/tests/library/headful.spec.tsindex e6803f8619..921198730d 100644--- a/tests/library/headful.spec.ts+++ b/tests/library/headful.spec.ts@@ -14,10 +14,12 @@* limitations under the License.*/-import { compare } from '../../packages/playwright-core/src/server/utils/image_tools/compare';+import { serverUtils } from '../../packages/playwright-core/lib/coreBundle';import { PNG } from 'playwright-core/lib/utilsBundle';import { expect, playwrightTest as it } from '../config/browserTest';+const { compare } = serverUtils;+it.skip(({ headless }) => headless, 'avoid popping windows in headless mode');it.skip(({ channel }) => channel === 'chromium-headless-shell' || channel === 'chromium-tip-of-tree-headless-shell', 'shell is never headed');diff --git a/tests/library/inspector/cli-codegen-3.spec.ts b/tests/library/inspector/cli-codegen-3.spec.tsindex 488d8b82e2..ac48a6aeeb 100644--- a/tests/library/inspector/cli-codegen-3.spec.ts+++ b/tests/library/inspector/cli-codegen-3.spec.ts@@ -14,7 +14,7 @@* limitations under the License.*/-import type { TestServer } from 'tests/config/testserver';+import type { TestServer } from '../../config/testserver';import type { Recorder } from './inspectorTest';import { test, expect } from './inspectorTest';import type { Page } from '@playwright/test';diff --git a/tests/library/inspector/inspectorTest.ts b/tests/library/inspector/inspectorTest.tsindex 495bad1694..199207b14d 100644--- a/tests/library/inspector/inspectorTest.ts+++ b/tests/library/inspector/inspectorTest.ts@@ -46,7 +46,8 @@ const codegenLang2Id: Map<string, string> = new Map([]);const codegenLangId2lang = new Map([...codegenLang2Id.entries()].map(([lang, langId]) => [langId, lang]));-const playwrightToAutomateInspector = require('../../../packages/playwright-core/lib/inprocess').playwright;+import { inprocess } from '../../../packages/playwright-core/lib/coreBundle';+const playwrightToAutomateInspector = inprocess.playwright;export const test = contextTest.extend<CLITestArgs>({recorderPageGetter: async ({ context, toImpl, mode, headless }, run, testInfo) => {diff --git a/tests/library/locator-generator.spec.ts b/tests/library/locator-generator.spec.tsindex 9040438125..97a1f0a5a3 100644--- a/tests/library/locator-generator.spec.ts+++ b/tests/library/locator-generator.spec.ts@@ -15,10 +15,11 @@*/import { contextTest as it, expect } from '../config/browserTest';-import { asLocator, asLocators, asLocatorDescription } from '../../packages/playwright-core/lib/utils/isomorphic/locatorGenerators';-import { locatorOrSelectorAsSelector as parseLocator } from '../../packages/playwright-core/lib/utils/isomorphic/locatorParser';+import { iso } from '../../packages/playwright-core/lib/coreBundle';import type { Page, Frame, Locator, FrameLocator } from 'playwright-core';+const { asLocator, asLocators, asLocatorDescription, locatorOrSelectorAsSelector: parseLocator } = iso;+it.skip(({ mode }) => mode !== 'default');function generate(locator: Locator | FrameLocator) {diff --git a/tests/library/proxy-pattern.spec.ts b/tests/library/proxy-pattern.spec.tsindex 2969d49f27..6d75243c9f 100644--- a/tests/library/proxy-pattern.spec.ts+++ b/tests/library/proxy-pattern.spec.ts@@ -14,9 +14,11 @@* limitations under the License.*/-import { parsePattern } from '../../packages/playwright-core/lib/server/utils/socksProxy';+import { serverUtils } from '../../packages/playwright-core/lib/coreBundle';import { playwrightTest as test, expect } from '../config/browserTest';+const { parsePattern } = serverUtils;+test('socks proxy patter matcher', async ({}) => {const m1 = parsePattern('*');expect.soft(m1('example.com', 80)).toBe(true);diff --git a/tests/library/unit/json-schema.spec.ts b/tests/library/unit/json-schema.spec.tsindex e3b1d70a36..50a95bd688 100644--- a/tests/library/unit/json-schema.spec.ts+++ b/tests/library/unit/json-schema.spec.ts@@ -15,8 +15,11 @@*/import { test as it, expect } from '@playwright/test';-import { validate } from '../../../packages/playwright-core/lib/utils/isomorphic/jsonSchema';-import type { JsonSchema } from '../../../packages/playwright-core/src/utils/isomorphic/jsonSchema';+import type { iso } from '../../../packages/playwright-core/lib/coreBundle';+import { iso as _iso } from '../../../packages/playwright-core/lib/coreBundle';++const { validate } = _iso;+type JsonSchema = iso.JsonSchema;it('should validate string type', () => {expect(validate('hello', { type: 'string' }, '$')).toEqual([]);diff --git a/tests/library/unit/sequence.spec.ts b/tests/library/unit/sequence.spec.tsindex 7fdb20bd1a..8a469eaee7 100644--- a/tests/library/unit/sequence.spec.ts+++ b/tests/library/unit/sequence.spec.ts@@ -16,7 +16,8 @@import { test as it, expect } from '@playwright/test';-import { findRepeatedSubsequencesForTest as findRepeatedSubsequences } from '../../../packages/playwright-core/lib/server/callLog';+import { sever } from '../../../packages/playwright-core/lib/coreBundle';+const { findRepeatedSubsequencesForTest: findRepeatedSubsequences } = sever;it('should return an empty array when the input is empty', () => {const input = [];diff --git a/tests/library/unroute-behavior.spec.ts b/tests/library/unroute-behavior.spec.tsindex ef58fc6c65..b5c4f1010f 100644--- a/tests/library/unroute-behavior.spec.ts+++ b/tests/library/unroute-behavior.spec.ts@@ -16,7 +16,9 @@import { browserTest as it, expect } from '../config/browserTest';import type { Route } from '@playwright/test';-import { ManualPromise } from '../../packages/playwright-core/lib/utils/isomorphic/manualPromise';+import { iso } from '../../packages/playwright-core/lib/coreBundle';++const { ManualPromise } = iso;it('context.unroute should not wait for pending handlers to complete', async ({ page, context, server }) => {it.info().annotations.push({ type: 'issue', description: 'https://github.com/microsoft/playwright/issues/23781' });diff --git a/tests/library/videoPlayer.ts b/tests/library/videoPlayer.tsindex a75f7ff888..42721571bb 100644--- a/tests/library/videoPlayer.ts+++ b/tests/library/videoPlayer.ts@@ -17,7 +17,7 @@import { spawnSync } from 'child_process';import fs from 'fs';import { PNG } from 'playwright-core/lib/utilsBundle';-import { registry } from '../../packages/playwright-core/lib/server';+import { registry } from '../../packages/playwright-core/lib/coreBundle';export class VideoPlayer {fileName: string;@@ -30,7 +30,7 @@ export class VideoPlayer {constructor(fileName: string) {this.fileName = fileName;- const ffmpeg = registry.findExecutable('ffmpeg')!.executablePathOrDie('javascript');+ const ffmpeg = registry.registry.findExecutable('ffmpeg')!.executablePathOrDie('javascript');// Force output frame rate to 25 fps as otherwise it would produce one image per timebase unit// which is 1 / (25 * 1000).this.output = spawnSync(ffmpeg, ['-i', this.fileName, '-r', '25', `${this.fileName}-%04d.png`]).stderr.toString();diff --git a/tests/library/web-socket.spec.ts b/tests/library/web-socket.spec.tsindex 106682411e..4f49148794 100644--- a/tests/library/web-socket.spec.ts+++ b/tests/library/web-socket.spec.ts@@ -17,7 +17,7 @@import { kTargetClosedErrorMessage } from '../config/errors';import { contextTest as it, expect } from '../config/browserTest';-import { Server as WebSocketServer } from 'ws';+import { WebSocketServer, type WebSocket as WsSocket } from 'ws';it('should work @smoke', async ({ page, server }) => {server.sendOnWebSocketConnection('incoming');@@ -206,7 +206,7 @@ it('should turn off when offline', async ({ page }) => {const webSocketServer = new WebSocketServer();const address = webSocketServer.address();const [socket, wsHandle] = await Promise.all([- new Promise<import('ws')>(x => webSocketServer.once('connection', x)),+ new Promise<WsSocket>(x => webSocketServer.once('connection', x)),page.evaluateHandle(async address => {const ws = new WebSocket(`ws://${address}/`);await new Promise(x => ws.onopen = x);diff --git a/tests/mcp/fixtures.ts b/tests/mcp/fixtures.tsindex 812a134932..a47f9d7e14 100644--- a/tests/mcp/fixtures.ts+++ b/tests/mcp/fixtures.ts@@ -290,7 +290,7 @@ export const expect = baseExpect.extend({},});-export const mcpServerPath = [require.resolve('../../packages/playwright-core/lib/tools/mcp/cli-stub.js')];+export const mcpServerPath = [require.resolve('../../packages/playwright-core/lib/entry/mcp.js')];export const testMcpServerPath = [require.resolve('../../packages/playwright-test/cli.js'), 'run-test-mcp-server'];type Files = { [key: string]: string | Buffer };diff --git a/tests/mcp/init-agents.spec.ts b/tests/mcp/init-agents.spec.tsindex 7d58446ffd..597854b1d9 100644--- a/tests/mcp/init-agents.spec.ts+++ b/tests/mcp/init-agents.spec.ts@@ -15,11 +15,12 @@*/import { test, expect, writeFiles } from './fixtures';-import { spawnAsync } from '../../packages/playwright-core/lib/server/utils/spawnAsync';-+import { serverUtils } from '../../packages/playwright-core/lib/coreBundle';import path from 'path';import fs from 'fs';+const { spawnAsync } = serverUtils;+async function runInitAgents(options?: { args?: string[], cwd?: string }): Promise<{stdout: string, stderr: string, code: number | null, error?: Error}> {const result = await spawnAsync('npx', ['playwright', 'init-agents',diff --git a/tests/mcp/screenshot.spec.ts b/tests/mcp/screenshot.spec.tsindex 169569b6d5..f233eeb3f1 100644--- a/tests/mcp/screenshot.spec.ts+++ b/tests/mcp/screenshot.spec.ts@@ -17,7 +17,7 @@import fs from 'fs';import { test, expect } from './fixtures';-import { jpegjs, PNG } from 'packages/playwright-core/lib/utilsBundle';+import { jpegjs, PNG } from '../../packages/playwright-core/lib/utilsBundle';test('browser_take_screenshot (viewport)', async ({ startClient, server }, testInfo) => {const { client } = await startClient({diff --git a/tests/page/interception.spec.ts b/tests/page/interception.spec.tsindex a1df9ec645..e96e126f00 100644--- a/tests/page/interception.spec.ts+++ b/tests/page/interception.spec.ts@@ -16,9 +16,11 @@*/import { test as it, expect } from './pageTest';-import { globToRegexPattern, urlMatches } from '../../packages/playwright-core/lib/utils/isomorphic/urlMatch';+import { iso } from '../../packages/playwright-core/lib/coreBundle';import vm from 'vm';+const { globToRegexPattern, urlMatches } = iso;+it('should work with navigation @smoke', async ({ page, server }) => {const requests = new Map();await page.route('**/*', route => {diff --git a/tests/page/page-autowaiting-basic.spec.ts b/tests/page/page-autowaiting-basic.spec.tsindex dbfe482c33..5e680461d5 100644--- a/tests/page/page-autowaiting-basic.spec.ts+++ b/tests/page/page-autowaiting-basic.spec.ts@@ -15,7 +15,7 @@* limitations under the License.*/-import { stripAnsi } from 'tests/config/utils';+import { stripAnsi } from '../config/utils';import type { TestServer } from '../config/testserver';import { test as it, expect } from './pageTest';diff --git a/tests/page/page-emulate-media.spec.ts b/tests/page/page-emulate-media.spec.tsindex 2e6b2660b2..2cfd5cff52 100644--- a/tests/page/page-emulate-media.spec.ts+++ b/tests/page/page-emulate-media.spec.ts@@ -15,7 +15,7 @@* limitations under the License.*/-import type { Page } from 'packages/playwright-test';+import type { Page } from '../../packages/playwright-test';import { test as it, expect as baseExpect } from './pageTest';const expect = baseExpect.extend({diff --git a/tests/page/page-leaks.spec.ts b/tests/page/page-leaks.spec.tsindex 42ff3d1c41..1df64c52ee 100644--- a/tests/page/page-leaks.spec.ts+++ b/tests/page/page-leaks.spec.ts@@ -14,10 +14,12 @@* limitations under the License.*/-import { nullProgress } from '../../packages/playwright-core/lib/server/progress';-import { MultiMap } from '../../packages/playwright-core/lib/utils/isomorphic/multimap';+import { iso, sever } from '../../packages/playwright-core/lib/coreBundle';+const { nullProgress } = sever;import { test, expect } from './pageTest';+const { MultiMap } = iso;+function leakedJSHandles(): string {const map = new MultiMap();for (const [h, e] of (globalThis as any).leakedJSHandles) {diff --git a/tests/page/page-listeners.spec.ts b/tests/page/page-listeners.spec.tsindex 495ecf36c7..737a7b9432 100644--- a/tests/page/page-listeners.spec.ts+++ b/tests/page/page-listeners.spec.ts@@ -15,9 +15,11 @@* limitations under the License.*/-import { ManualPromise } from '../../packages/playwright-core/lib/utils/isomorphic/manualPromise';+import { iso } from '../../packages/playwright-core/lib/coreBundle';import { test as it, expect } from './pageTest';+const { ManualPromise } = iso;+// This test is mostly for type checking, the actual tests are in the library/events.it('should not throw with ignoreErrors', async ({ page }) => {diff --git a/tests/page/page-set-content.spec.ts b/tests/page/page-set-content.spec.tsindex 41d38787c7..399240e1ed 100644--- a/tests/page/page-set-content.spec.ts+++ b/tests/page/page-set-content.spec.ts@@ -16,7 +16,8 @@*/import { test as it, expect } from './pageTest';-import { nullProgress } from '../../packages/playwright-core/lib/server/progress';+import { sever } from '../../packages/playwright-core/lib/coreBundle';+const { nullProgress } = sever;const expectedOutput = '<html><head></head><body><div>hello</div></body></html>';diff --git a/tests/playwright-test/expect.spec.ts b/tests/playwright-test/expect.spec.tsindex a47dff42c6..e37b7da458 100644--- a/tests/playwright-test/expect.spec.ts+++ b/tests/playwright-test/expect.spec.ts@@ -16,7 +16,8 @@import path from 'path';import { test, expect, parseTestRunnerOutput, stripAnsi } from './playwright-test-fixtures';-const { spawnAsync } = require('../../packages/playwright-core/lib/utils');+import { serverUtils } from '../../packages/playwright-core/lib/coreBundle';+const { spawnAsync } = serverUtils;test('should not expand huge arrays', async ({ runInlineTest }) => {const result = await runInlineTest({diff --git a/tests/playwright-test/fit-to-width.spec.ts b/tests/playwright-test/fit-to-width.spec.tsindex c4f6dd3200..bf7a2aa4d0 100644--- a/tests/playwright-test/fit-to-width.spec.ts+++ b/tests/playwright-test/fit-to-width.spec.ts@@ -14,7 +14,7 @@* limitations under the License.*/-import { fitToWidth } from 'packages/playwright/lib/reporters/base';+import { fitToWidth } from '../../packages/playwright/lib/reporters/base';import { test, expect } from './playwright-test-fixtures';test('chinese characters', () => {diff --git a/tests/playwright-test/pause-at-end.spec.ts b/tests/playwright-test/pause-at-end.spec.tsindex 0aa640cbed..06f3a9ca34 100644--- a/tests/playwright-test/pause-at-end.spec.ts+++ b/tests/playwright-test/pause-at-end.spec.ts@@ -14,8 +14,8 @@* limitations under the License.*/-import { TestCase, TestResult, TestStep } from 'packages/playwright-test/reporter';-import { ReporterV2 } from 'packages/playwright/src/reporters/reporterV2';+import { TestCase, TestResult, TestStep } from '../../packages/playwright-test/reporter';+import { ReporterV2 } from '../../packages/playwright/src/reporters/reporterV2';import { test, expect } from './playwright-test-fixtures';test.describe.configure({ mode: 'parallel' });diff --git a/tests/playwright-test/playwright.spec.ts b/tests/playwright-test/playwright.spec.tsindex e390970afc..89339d93f4 100644--- a/tests/playwright-test/playwright.spec.ts+++ b/tests/playwright-test/playwright.spec.ts@@ -18,9 +18,9 @@ import { test, expect, parseTestRunnerOutput } from './playwright-test-fixtures'import fs from 'fs';import path from 'path';import { spawnSync } from 'child_process';-import { registry } from '../../packages/playwright-core/lib/server';+import { registry } from '../../packages/playwright-core/lib/coreBundle';-const ffmpeg = registry.findExecutable('ffmpeg')!.executablePath();+const ffmpeg = registry.registry.findExecutable('ffmpeg')!.executablePath();export class VideoPlayer {videoWidth: number;diff --git a/tests/playwright-test/reporter-blob.spec.ts b/tests/playwright-test/reporter-blob.spec.tsindex c278de2f6e..8c67d85ec3 100644--- a/tests/playwright-test/reporter-blob.spec.ts+++ b/tests/playwright-test/reporter-blob.spec.ts@@ -17,15 +17,17 @@import * as fs from 'fs';import type { PlaywrightTestConfig } from '@playwright/test';import path from 'path';-import type { HttpServer } from '../../packages/playwright-core/lib/server/utils/httpServer';import { startHtmlReportServer } from '../../packages/playwright/lib/reporters/html';import { expect as baseExpect, test as baseTest, stripAnsi } from './playwright-test-fixtures';import extractZip from '../../packages/playwright-core/bundles/zip/src/third_party/extract-zip';import * as yazl from '../../packages/playwright-core/bundles/zip/node_modules/yazl';-import { getUserAgent } from '../../packages/playwright-core/lib/server/utils/userAgent';+import { serverUtils } from '../../packages/playwright-core/lib/coreBundle';import { Readable } from 'stream';import type { FullResult, JSONReportTestResult } from '../../packages/playwright-test/reporter';+type HttpServer = serverUtils.HttpServer;+const { getUserAgent } = serverUtils;+const DOES_NOT_SUPPORT_UTF8_IN_TERMINAL = process.platform === 'win32' && process.env.TERM_PROGRAM !== 'vscode' && !process.env.WT_SESSION;const POSITIVE_STATUS_MARK = DOES_NOT_SUPPORT_UTF8_IN_TERMINAL ? 'ok' : '✓ ';const NEGATIVE_STATUS_MARK = DOES_NOT_SUPPORT_UTF8_IN_TERMINAL ? 'x ' : '✘ ';diff --git a/tests/playwright-test/reporter-html.spec.ts b/tests/playwright-test/reporter-html.spec.tsindex 2d839d110c..85e4a91516 100644--- a/tests/playwright-test/reporter-html.spec.ts+++ b/tests/playwright-test/reporter-html.spec.ts@@ -18,10 +18,13 @@ import fs from 'fs';import path from 'path';import url from 'url';import { test as baseTest, expect as baseExpect, createImage } from './playwright-test-fixtures';-import type { HttpServer } from '../../packages/playwright-core/lib/server/utils/httpServer';import { startHtmlReportServer } from '../../packages/playwright/lib/reporters/html';-import { msToString } from '../../packages/playwright-core/src/utils/isomorphic/formatUtils';-const { spawnAsync } = require('../../packages/playwright-core/lib/utils');+import { iso, serverUtils } from '../../packages/playwright-core/lib/coreBundle';++type HttpServer = serverUtils.HttpServer;++const { msToString } = iso;+const { spawnAsync } = serverUtils;const test = baseTest.extend<{ showReport: (reportFolder?: string) => Promise<void> }>({showReport: async ({ page }, use, testInfo) => {diff --git a/tests/playwright-test/test-server.spec.ts b/tests/playwright-test/test-server.spec.tsindex e0ecb51f0b..3dff3ac06a 100644--- a/tests/playwright-test/test-server.spec.ts+++ b/tests/playwright-test/test-server.spec.ts@@ -14,6 +14,8 @@* limitations under the License.*/+// @ts-nocheck+import { test as baseTest, expect } from './ui-mode-fixtures';import { TestServerConnection } from '../../packages/playwright/lib/isomorphic/testServerConnection';import { playwrightCtConfigText } from './playwright-test-fixtures';diff --git a/tests/playwright-test/ui-mode-fixtures.ts b/tests/playwright-test/ui-mode-fixtures.tsindex 25f307d093..7487b1d995 100644--- a/tests/playwright-test/ui-mode-fixtures.ts+++ b/tests/playwright-test/ui-mode-fixtures.ts@@ -22,9 +22,11 @@ import { cliEntrypoint, test as base, writeFiles, removeFolders } from './playwrimport type { Files, RunOptions } from './playwright-test-fixtures';import type { Browser, Page, TestInfo } from './stable-test-runner';import { chromium } from './stable-test-runner';-import { createGuid } from '../../packages/playwright-core/src/server/utils/crypto';+import { serverUtils } from '../../packages/playwright-core/lib/coreBundle';import { inheritAndCleanEnv } from '../config/utils';+const { createGuid } = serverUtils;+type Latch = {blockingCode: string;open: () => void;diff --git a/tests/playwright-test/ui-mode-test-progress.spec.ts b/tests/playwright-test/ui-mode-test-progress.spec.tsindex ada6a788b6..932f3c5cf1 100644--- a/tests/playwright-test/ui-mode-test-progress.spec.ts+++ b/tests/playwright-test/ui-mode-test-progress.spec.ts@@ -14,9 +14,11 @@* limitations under the License.*/-import { ManualPromise } from '../../packages/playwright-core/lib/utils/isomorphic/manualPromise';+import { iso } from '../../packages/playwright-core/lib/coreBundle';import { test, expect, retries, dumpTestTree } from './ui-mode-fixtures';+const { ManualPromise } = iso;+test.describe.configure({ mode: 'parallel', retries });test('should update trace live', async ({ runUITest, server }) => {diff --git a/tests/playwright-test/web-server.spec.ts b/tests/playwright-test/web-server.spec.tsindex bbdd4d9f56..a33f3168b6 100644--- a/tests/playwright-test/web-server.spec.ts+++ b/tests/playwright-test/web-server.spec.ts@@ -18,7 +18,9 @@ import type http from 'http';import path from 'path';import { test, expect, parseTestRunnerOutput } from './playwright-test-fixtures';import type { RunResult } from './playwright-test-fixtures';-import { createHttpServer } from '../../packages/playwright-core/lib/server/utils/network';+import { serverUtils } from '../../packages/playwright-core/lib/coreBundle';++const { createHttpServer } = serverUtils;const SIMPLE_SERVER_PATH = path.join(__dirname, 'assets', 'simple-server.js');diff --git a/tests/stress/frames.spec.ts b/tests/stress/frames.spec.tsindex a438ec689f..e2cb18b2fc 100644--- a/tests/stress/frames.spec.ts+++ b/tests/stress/frames.spec.ts@@ -15,11 +15,12 @@*/import { contextTest as test, expect } from '../config/browserTest';+import { sever } from '../../packages/playwright-core/lib/coreBundle';test.slow();test('cycle frames', async ({ page, server }) => {- require('../../packages/playwright-core/lib/server/dispatchers/dispatcher').setMaxDispatchersForTest(100);+ sever.setMaxDispatchersForTest(100);const kFrameCount = 310;@@ -46,7 +47,7 @@ test('cycle frames', async ({ page, server }) => {await promise;await page.waitForTimeout(500);- require('../../packages/playwright-core/lib/server/dispatchers/dispatcher').setMaxDispatchersForTest(null);+ sever.setMaxDispatchersForTest(null);});test('cycle handles', async ({ page, server }) => {diff --git a/tests/stress/heap.spec.ts b/tests/stress/heap.spec.tsindex d07edddab7..0fc5289677 100644--- a/tests/stress/heap.spec.ts+++ b/tests/stress/heap.spec.ts@@ -15,6 +15,7 @@*/import { contextTest as test, expect } from '../config/browserTest';+import { sever } from '../../packages/playwright-core/lib/coreBundle';import { queryObjectCount } from '../config/queryObjects';test.describe.configure({ mode: 'serial' });@@ -43,10 +44,10 @@ test('should not leak fixtures w/o page', async ({}) => {});test('should not leak server-side objects', async ({ page }) => {- expect(await queryObjectCount(require('../../packages/playwright-core/lib/server/page').Page)).toBe(1);+ expect(await queryObjectCount(sever.Page)).toBe(1);// 4 is because v8 heap creates objects for descendant classes, so WKContext, CRContext, FFContext, BidiBrowserContext and our context instance.- expect(await queryObjectCount(require('../../packages/playwright-core/lib/server/browserContext').BrowserContext)).toBe(5);- expect(await queryObjectCount(require('../../packages/playwright-core/lib/server/browser').Browser)).toBe(5);+ expect(await queryObjectCount(sever.BrowserContext)).toBe(5);+ expect(await queryObjectCount(sever.Browser)).toBe(5);});test('should not leak dispatchers after closing page', async ({ context, server }) => {@@ -63,27 +64,27 @@ test('should not leak dispatchers after closing page', async ({ context, serverpages.push(page);}- expect(await queryObjectCount(require('../../packages/playwright-core/lib/server/page').Page)).toBe(COUNT);- expect(await queryObjectCount(require('../../packages/playwright-core/lib/server/dispatchers/networkDispatchers').RequestDispatcher)).toBe(COUNT);- expect(await queryObjectCount(require('../../packages/playwright-core/lib/server/dispatchers/networkDispatchers').ResponseDispatcher)).toBe(COUNT);+ expect(await queryObjectCount(sever.Page)).toBe(COUNT);+ expect(await queryObjectCount(sever.RequestDispatcher)).toBe(COUNT);+ expect(await queryObjectCount(sever.ResponseDispatcher)).toBe(COUNT);for (const page of pages)await page.close();pages.length = 0;- expect(await queryObjectCount(require('../../packages/playwright-core/lib/server/page').Page)).toBe(0);- expect(await queryObjectCount(require('../../packages/playwright-core/lib/server/dispatchers/networkDispatchers').RequestDispatcher)).toBe(0);- expect(await queryObjectCount(require('../../packages/playwright-core/lib/server/dispatchers/networkDispatchers').ResponseDispatcher)).toBe(0);+ expect(await queryObjectCount(sever.Page)).toBe(0);+ expect(await queryObjectCount(sever.RequestDispatcher)).toBe(0);+ expect(await queryObjectCount(sever.ResponseDispatcher)).toBe(0);expect(await queryObjectCount(require('../../packages/playwright-core/lib/client/page').Page)).toBeLessThan(COUNT);- expect(await queryObjectCount(require('../../packages/playwright-core/lib/server/page').Page)).toBe(0);+ expect(await queryObjectCount(sever.Page)).toBe(0);expect(await queryObjectCount(require('../../packages/playwright-core/lib/client/network').Request)).toBe(0);expect(await queryObjectCount(require('../../packages/playwright-core/lib/client/network').Response)).toBe(0);});test.describe(() => {test.beforeEach(() => {- require('../../packages/playwright-core/lib/server/dispatchers/dispatcher').setMaxDispatchersForTest(100);+ sever.setMaxDispatchersForTest(100);});test('should collect stale handles', async ({ page, server }) => {@@ -101,10 +102,10 @@ test.describe(() => {const counts = [{ count: await queryObjectCount(require('../../packages/playwright-core/lib/client/network').Request), message: 'client.Request' },{ count: await queryObjectCount(require('../../packages/playwright-core/lib/client/network').Response), message: 'client.Response' },- { count: await queryObjectCount(require('../../packages/playwright-core/lib/server/network').Request), message: 'server.Request' },- { count: await queryObjectCount(require('../../packages/playwright-core/lib/server/network').Response), message: 'server.Response' },- { count: await queryObjectCount(require('../../packages/playwright-core/lib/server/dispatchers/networkDispatchers').RequestDispatcher), message: 'dispatchers.RequestDispatcher' },- { count: await queryObjectCount(require('../../packages/playwright-core/lib/server/dispatchers/networkDispatchers').ResponseDispatcher), message: 'dispatchers.ResponseDispatcher' },+ { count: await queryObjectCount(sever.Request), message: 'server.Request' },+ { count: await queryObjectCount(sever.Response), message: 'server.Response' },+ { count: await queryObjectCount(sever.RequestDispatcher), message: 'dispatchers.RequestDispatcher' },+ { count: await queryObjectCount(sever.ResponseDispatcher), message: 'dispatchers.ResponseDispatcher' },];for (const { count, message } of counts) {expect(count, { message }).toBeGreaterThan(50);@@ -113,6 +114,6 @@ test.describe(() => {});test.afterEach(() => {- require('../../packages/playwright-core/lib/server/dispatchers/dispatcher').setMaxDispatchersForTest(null);+ sever.setMaxDispatchersForTest(null);});});diff --git a/tests/tsconfig.json b/tests/tsconfig.jsonindex 2ffc326c74..2512b062de 100644--- a/tests/tsconfig.json+++ b/tests/tsconfig.json@@ -1,25 +1,38 @@{- "compilerOptions": {- "allowJs": true,- "checkJs": false,- "noEmit": true,- "moduleResolution": "node",- "target": "ESNext",- "strictNullChecks": false,- "strictBindCallApply": true,- "allowSyntheticDefaultImports": true,- "useUnknownInCatchVariables": false,- "baseUrl": "..",- "paths": {- "@dvtools/*": ["packages/devtools/src/*"],- "@isomorphic/*": ["packages/playwright-core/src/utils/isomorphic/*"],- "@testIsomorphic/*": ["packages/playwright/src/isomorphic/*"],- "@protocol/*": ["packages/protocol/src/*"],- "@recorder/*": ["packages/recorder/src/*"],- "@trace/*": ["packages/trace/src/*"],- "@web/*": ["packages/web/src/*"],- },+ "compilerOptions": {+ "target": "ESNext",+ "module": "ESNext",+ "moduleResolution": "bundler",+ "lib": [+ "ESNext",+ "DOM",+ "DOM.Iterable"+ ],+ "baseUrl": "..",+ "paths": {+ "@dashboard/*": ["packages/dashboard/src/*"],+ "@dvtools/*": ["packages/devtools/src/*"],+ "@injected/*": ["packages/injected/src/*"],+ "@isomorphic/*": ["packages/playwright-core/src/utils/isomorphic/*"],+ "@testIsomorphic/*": ["packages/playwright/src/isomorphic/*"],+ "@protocol/*": ["packages/protocol/src/*"],+ "@recorder/*": ["packages/recorder/src/*"],+ "@trace/*": ["packages/trace/src/*"],+ "@web/*": ["packages/web/src/*"],},- "include": ["**/*.spec.js", "**/*.ts"],- "exclude": ["components/", "installation/fixture-scripts/"]+ "esModuleInterop": true,+ "allowSyntheticDefaultImports": true,+ "allowJs": false,+ "jsx": "react-jsx",+ "resolveJsonModule": true,+ "isolatedModules": true,+ "noEmit": true,+ "noImplicitOverride": true,+ "strictNullChecks": false,+ "useUnknownInCatchVariables": false,+ "useDefineForClassFields": false,+ "skipLibCheck": true,+ },+ "include": ["**/*.spec.js", "**/*.ts"],+ "exclude": ["components/", "installation/fixture-scripts/", "packages/playwright-core/lib/", "config/ghaMarkdownReporter.ts"]}diff --git a/utils/build/build.js b/utils/build/build.jsindex 70ace25544..e3f9d4ed22 100644--- a/utils/build/build.js+++ b/utils/build/build.js@@ -385,10 +385,11 @@ steps.push(new ProgramStep({class EsbuildStep extends Step {/** @type {import('esbuild').BuildOptions} */- constructor(options) {+ constructor(options, watchPaths = []) {// Starting esbuild steps in parallel showed longer overall time.super({ concurrent: false });this._options = options;+ this._watchPaths = watchPaths;}/** @override */@@ -410,7 +411,7 @@ class EsbuildStep extends Step {this._context = await context(this._options);disposables.push(() => this._context?.dispose());- const watcher = chokidar.watch(this._options.entryPoints);+ const watcher = chokidar.watch([...this._options.entryPoints, ...(this._watchPaths || [])]);await new Promise(x => watcher.once('ready', x));watcher.on('all', () => this._rebuild());@@ -481,6 +482,8 @@ for (const pkg of workspace.packages()) {// playwright-client is built as a bundle.if (['@playwright/client'].includes(pkg.name))continue;+ if (pkg.name === 'playwright-core')+ continue;steps.push(new EsbuildStep({entryPoints: [path.join(pkg.path, 'src/**/*.ts')],@@ -492,6 +495,100 @@ for (const pkg of workspace.packages()) {}));}+// Build playwright-core exported entry points.+steps.push(new EsbuildStep({+ entryPoints: [+ // Performance analysis tool.+ filePath('packages/playwright-core/src/bootstrap.ts'),++ // Entry points for oop execution.+ filePath('packages/playwright-core/src/entry/cliDaemon.ts'),+ filePath('packages/playwright-core/src/entry/dashboardApp.ts'),+ filePath('packages/playwright-core/src/entry/mcp.ts'),+ filePath('packages/playwright-core/src/entry/oopBrowserDownload.ts'),++ // CLI client tools, should be a separate bundle.+ filePath('packages/playwright-core/src/tools/cli-client/*.ts'),+ filePath('packages/playwright-core/src/package.ts'),+ filePath('packages/playwright-core/src/serverRegistry.ts'),+ filePath('packages/playwright-core/src/tools/utils/socketConnection.ts'),++ // Bundle entry points otherwise inlined in coreBundle, figure this out.+ filePath('packages/playwright-core/src/utilsBundle.ts'),+ filePath('packages/playwright-core/src/mcpBundle.ts'),+ filePath('packages/playwright-core/src/zodBundle.ts'),+ filePath('packages/playwright-core/src/zipBundle.ts'),+ ],+ outdir: filePath('packages/playwright-core/lib'),+ sourcemap: withSourceMaps ? 'linked' : false,+ platform: 'node',+ format: 'cjs',+}));++const playwrightCoreSrc = filePath('packages/playwright-core/src');++// Build playwright-core as a single bundle.+steps.push(new EsbuildStep({+ bundle: true,+ entryPoints: [filePath('packages/playwright-core/src/coreBundle.ts')],+ outfile: filePath('packages/playwright-core/lib/coreBundle.js'),+ sourcemap: withSourceMaps ? 'linked' : false,+ platform: 'node',+ format: 'cjs',+ external: [+ './utilsBundleImpl',+ './utilsBundleImpl/*',+ './mcpBundleImpl',+ './zodBundleImpl',+ './zipBundleImpl',+ '../../api.json',+ './help.json',+ // TODO: await import plugin is incompatible with esbuild, remove it+ 'electron',+ 'electron/*',+ 'chromium-bidi',+ 'chromium-bidi/*',+ 'mitt',+ ],+ plugins: [dynamicImportToRequirePlugin],+}, [playwrightCoreSrc]));++function assertCoreBundleHasNoNodeModules() {+ const bundlePath = filePath('packages/playwright-core/lib/coreBundle.js');+ const contents = fs.readFileSync(bundlePath, 'utf8');+ const lines = contents.split('\n');+ const offenders = [];+ for (let i = 0; i < lines.length; i++) {+ const idx = lines[i].indexOf('node_modules/');+ if (idx !== -1)+ offenders.push(` ${bundlePath}:${i + 1}: ${lines[i].slice(Math.max(0, idx - 10), idx + 80)}`);+ }+ if (offenders.length) {+ console.error(`\n==== coreBundle.js contains 'node_modules/' references (${offenders.length} lines) ====`);+ console.error(offenders.slice(0, 20).join('\n'));+ if (offenders.length > 20)+ console.error(` ... and ${offenders.length - 20} more`);+ console.error('Mark the offending package as external in the coreBundle esbuild config (utils/build/build.js).');+ process.exit(1);+ }+ console.log('==== coreBundle.js: no node_modules/ references');+}++steps.push(new CustomCallbackStep(assertCoreBundleHasNoNodeModules));++// Build the Electron preload loader as a standalone CJS file. It runs inside+// the Electron process (via `electron -r loader.js`) and must not depend on+// coreBundle. `electron` is resolved at runtime by the Electron process.+steps.push(new EsbuildStep({+ bundle: true,+ entryPoints: [filePath('packages/playwright-core/src/server/electron/loader.ts')],+ outfile: filePath('packages/playwright-core/lib/server/electron/loader.js'),+ sourcemap: withSourceMaps ? 'linked' : false,+ platform: 'node',+ format: 'cjs',+ external: ['electron'],+}, [playwrightCoreSrc]));+function copyXdgOpen() {const outdir = filePath('packages/playwright-core/lib/utilsBundleImpl');if (!fs.existsSync(outdir))diff --git a/utils/generate_cli_help.js b/utils/generate_cli_help.jsindex af15daa775..7a1e816404 100644--- a/utils/generate_cli_help.js+++ b/utils/generate_cli_help.js@@ -19,18 +19,18 @@const fs = require('fs')const path = require('path')-const { generateHelp, generateReadme, generateHelpJSON } = require('../packages/playwright-core/lib/tools/cli-daemon/helpGenerator.js');+const { tools } = require('../packages/playwright-core/lib/coreBundle');if (process.argv[2] === '--readme') {- console.log(generateReadme());+ console.log(tools.generateReadme());process.exit(0);}if (process.argv[2] === '--print') {- console.log(generateHelp());+ console.log(tools.generateHelp());process.exit(0);}const fileName = path.resolve(__dirname, '../packages/playwright-core/lib/tools/cli-client/help.json');console.log('Writing ', path.relative(process.cwd(), fileName));-fs.writeFileSync(fileName, JSON.stringify(generateHelpJSON(), null, 2));+fs.writeFileSync(fileName, JSON.stringify(tools.generateHelpJSON(), null, 2));diff --git a/utils/roll_browser.js b/utils/roll_browser.jsindex 4aeb992e26..499f89f023 100755--- a/utils/roll_browser.js+++ b/utils/roll_browser.js@@ -17,7 +17,7 @@*/const path = require('path');-const { Registry } = require('../packages/playwright-core/lib/server');+const { Registry } = require('../packages/playwright-core/lib/coreBundle').registry;const fs = require('fs');const protocolGenerator = require('./protocol-types-generator');const {execSync} = require('child_process');