Skip to content

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

fix(registry): evaluate `defaultCacheDirectory` lazily (#41942)

Devin Rousso3e14efd6b76d
diff --git a/packages/playwright-core/src/server/registry/index.ts b/packages/playwright-core/src/server/registry/index.ts
index 2b6e0141a7..9b1583e3f3 100644
--- a/packages/playwright-core/src/server/registry/index.ts
+++ b/packages/playwright-core/src/server/registry/index.ts
@@ -495,7 +495,7 @@ const DOWNLOAD_PATHS: Record<string, DownloadPaths> = {
},
};
-export const defaultCacheDirectory = (() => {
+function computeDefaultCacheDirectory(): string {
if (process.platform === 'linux')
return process.env.XDG_CACHE_HOME || path.join(os.homedir(), '.cache');
if (process.platform === 'darwin')
@@ -503,9 +503,17 @@ export const defaultCacheDirectory = (() => {
if (process.platform === 'win32')
return process.env.LOCALAPPDATA || path.join(os.homedir(), 'AppData', 'Local');
throw new Error('Unsupported platform: ' + process.platform);
-})();
+}
+
+let _defaultCacheDirectory: string | undefined;
-export const defaultRegistryDirectory = path.join(defaultCacheDirectory, 'ms-playwright');
+export function defaultCacheDirectory(): string {
+ return _defaultCacheDirectory ??= computeDefaultCacheDirectory();
+}
+
+export function defaultRegistryDirectory(): string {
+ return path.join(defaultCacheDirectory(), 'ms-playwright');
+}
export const registryDirectory = (() => {
let result: string;
@@ -516,7 +524,7 @@ export const registryDirectory = (() => {
else if (envDefined)
result = envDefined;
else
- result = defaultRegistryDirectory;
+ result = defaultRegistryDirectory();
if (!path.isAbsolute(result)) {
// It is important to resolve to the absolute path:
diff --git a/packages/playwright-core/src/serverRegistry.ts b/packages/playwright-core/src/serverRegistry.ts
index 3f5ddb0a74..3f43ad8d79 100644
--- a/packages/playwright-core/src/serverRegistry.ts
+++ b/packages/playwright-core/src/serverRegistry.ts
@@ -171,7 +171,7 @@ class ServerRegistry extends EventEmitter {
}
private _browsersDir() {
- return process.env.PWTEST_SERVER_REGISTRY || registryDirectory;
+ return process.env.PWTEST_SERVER_REGISTRY || registryDirectory();
}
private _startWatcher() {
@@ -242,7 +242,7 @@ async function canConnectTo(descriptor: BrowserDescriptor): Promise<boolean> {
});
}
-const defaultCacheDirectory = (() => {
+function computeDefaultCacheDirectory(): string {
if (process.platform === 'linux')
return process.env.XDG_CACHE_HOME || path.join(os.homedir(), '.cache');
if (process.platform === 'darwin')
@@ -250,8 +250,16 @@ const defaultCacheDirectory = (() => {
if (process.platform === 'win32')
return process.env.LOCALAPPDATA || path.join(os.homedir(), 'AppData', 'Local');
throw new Error('Unsupported platform: ' + process.platform);
-})();
+}
+
+let _defaultCacheDirectory: string | undefined;
-const registryDirectory = path.join(defaultCacheDirectory, 'ms-playwright', 'b');
+function defaultCacheDirectory(): string {
+ return _defaultCacheDirectory ??= computeDefaultCacheDirectory();
+}
+
+function registryDirectory(): string {
+ return path.join(defaultCacheDirectory(), 'ms-playwright', 'b');
+}
export const serverRegistry = new ServerRegistry();
diff --git a/packages/playwright-core/src/tools/cli-client/registry.ts b/packages/playwright-core/src/tools/cli-client/registry.ts
index 76de68c4a6..a9edb03236 100644
--- a/packages/playwright-core/src/tools/cli-client/registry.ts
+++ b/packages/playwright-core/src/tools/cli-client/registry.ts
@@ -115,9 +115,9 @@ export class Registry {
static async load(): Promise<Registry> {
const sessions = new Map<string, SessionFile[]>();
- const hashDirs = await fs.promises.readdir(baseDaemonDir).catch(() => []);
+ const hashDirs = await fs.promises.readdir(baseDaemonDir()).catch(() => []);
for (const workspaceDirHash of hashDirs) {
- const daemonDir = path.join(baseDaemonDir, workspaceDirHash);
+ const daemonDir = path.join(baseDaemonDir(), workspaceDirHash);
const stat = await fs.promises.stat(daemonDir);
if (!stat.isDirectory())
continue;
@@ -142,7 +142,7 @@ export class Registry {
}
}
-export const baseDaemonDir = (() => {
+function computeBaseDaemonDir(): string {
if (process.env.PWTEST_DAEMON_SESSION_DIR)
return process.env.PWTEST_DAEMON_SESSION_DIR;
@@ -156,7 +156,13 @@ export const baseDaemonDir = (() => {
if (!localCacheDir)
throw new Error('Unsupported platform: ' + process.platform);
return path.join(localCacheDir, 'ms-playwright', 'daemon');
-})();
+}
+
+let _baseDaemonDir: string | undefined;
+
+export function baseDaemonDir(): string {
+ return _baseDaemonDir ??= computeBaseDaemonDir();
+}
export function createClientInfo(): ClientInfo {
const workspaceDir = findWorkspaceDir(process.cwd());
@@ -189,7 +195,7 @@ function findWorkspaceDir(startDir: string): string | undefined {
}
const daemonProfilesDir = (workspaceDirHash: string) => {
- return path.join(baseDaemonDir, workspaceDirHash);
+ return path.join(baseDaemonDir(), workspaceDirHash);
};
export function explicitSessionName(sessionName?: string): string | undefined {
diff --git a/packages/playwright-core/src/tools/mcp/browserFactory.ts b/packages/playwright-core/src/tools/mcp/browserFactory.ts
index 9f593c31c0..eef9c2d903 100644
--- a/packages/playwright-core/src/tools/mcp/browserFactory.ts
+++ b/packages/playwright-core/src/tools/mcp/browserFactory.ts
@@ -195,7 +195,7 @@ async function createPersistentBrowser(config: FullConfig, clientInfo: ClientInf
}
async function createUserDataDir(config: FullConfig, clientInfo: ClientInfo) {
- const dir = process.env.PWMCP_PROFILES_DIR_FOR_TEST ?? path.join(defaultCacheDirectory, 'ms-playwright-mcp');
+ const dir = process.env.PWMCP_PROFILES_DIR_FOR_TEST ?? path.join(defaultCacheDirectory(), 'ms-playwright-mcp');
const browserToken = config.browser.launchOptions?.channel ?? config.browser?.browserName;
// Hesitant putting hundreds of files into the user's workspace, so using it for hashing instead.
const rootPathToken = createHash(clientInfo.cwd);
diff --git a/tests/library/browsers-path.spec.ts b/tests/library/browsers-path.spec.ts
new file mode 100644
index 0000000000..e2d055c35d
--- /dev/null
+++ b/tests/library/browsers-path.spec.ts
@@ -0,0 +1,55 @@
+/**
+ * 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 { playwrightTest as test, expect } from '../config/browserTest';
+import { spawnSync } from 'child_process';
+import path from 'path';
+
+const playwrightCorePath = path.join(__dirname, '..', '..', 'packages', 'playwright-core');
+
+// Importing playwright-core while pretending to run on an unsupported platform
+// (e.g. Android/Termux, where `process.platform === 'android'`).
+function requireCoreOnAndroid(browsersPath: string | undefined): { status: number | null, output: string } {
+ const script = [
+ `Object.defineProperty(process, 'platform', { value: 'android' });`,
+ `require(${JSON.stringify(playwrightCorePath)});`,
+ `console.log('PLAYWRIGHT_CORE_LOADED');`,
+ ].join('\n');
+ const env = { ...process.env };
+ delete env.PLAYWRIGHT_BROWSERS_PATH;
+ if (browsersPath !== undefined)
+ env.PLAYWRIGHT_BROWSERS_PATH = browsersPath;
+ const result = spawnSync(process.execPath, ['-e', script], { encoding: 'utf-8', env });
+ return { status: result.status, output: (result.stdout || '') + (result.stderr || '') };
+}
+
+test('should import on an unsupported platform when PLAYWRIGHT_BROWSERS_PATH=0', {
+ annotation: { type: 'issue', description: 'https://github.com/microsoft/playwright/issues/41852' },
+}, () => {
+ const { status, output } = requireCoreOnAndroid('0');
+ expect(output).not.toContain('Unsupported platform');
+ expect(output).toContain('PLAYWRIGHT_CORE_LOADED');
+ expect(status).toBe(0);
+});
+
+test('should import on an unsupported platform with an explicit PLAYWRIGHT_BROWSERS_PATH', {
+ annotation: { type: 'issue', description: 'https://github.com/microsoft/playwright/issues/41852' },
+}, () => {
+ const { status, output } = requireCoreOnAndroid(path.join(test.info().outputDir, 'pw-browsers'));
+ expect(output).not.toContain('Unsupported platform');
+ expect(output).toContain('PLAYWRIGHT_CORE_LOADED');
+ expect(status).toBe(0);
+});