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(tools): ban `as any` via eslint and fix existing usages (#39709)
Pavel Feldman8dcb1c3af841
diff --git a/eslint.config.mjs b/eslint.config.mjsindex e9875fbfae..23dc500594 100644--- a/eslint.config.mjs+++ b/eslint.config.mjs@@ -367,6 +367,13 @@ export default [}],},],+ "no-restricted-syntax": [+ "error",+ {+ selector: "TSAsExpression > TSAnyKeyword",+ message: "Avoid 'as any' — risk of accidentally casting to client interfaces. Use a precise type or add an eslint-disable with justification.",+ },+ ],},},{diff --git a/packages/playwright-core/src/tools/backend/browserBackend.ts b/packages/playwright-core/src/tools/backend/browserBackend.tsindex 6ab579763a..222b6e26cb 100644--- a/packages/playwright-core/src/tools/backend/browserBackend.ts+++ b/packages/playwright-core/src/tools/backend/browserBackend.ts@@ -51,7 +51,7 @@ export class BrowserBackend implements ServerBackend {await this._context?.dispose().catch(e => debug('pw:tools:error')(e));}- async callTool(name: string, rawArguments: mcpServer.CallToolRequest['params']['arguments']) {+ async callTool(name: string, rawArguments: mcpServer.CallToolRequest['params']['arguments'] & { _meta?: Record<string, any> } = {}): Promise<mcpServer.CallToolResult> {const tool = this._tools.find(tool => tool.schema.name === name)!;if (!tool) {return {@@ -59,8 +59,9 @@ export class BrowserBackend implements ServerBackend {isError: true,};}- const parsedArguments = tool.schema.inputSchema.parse(rawArguments || {}) as any;- const cwd = rawArguments?._meta && typeof rawArguments?._meta === 'object' && (rawArguments._meta as any)?.cwd;+ // eslint-disable-next-line no-restricted-syntax+ const parsedArguments = tool.schema.inputSchema.parse(rawArguments) as any;+ const cwd = rawArguments._meta?.cwd;const context = this._context!;const response = new Response(context, name, parsedArguments, cwd);context.setRunningTool(name);diff --git a/packages/playwright-core/src/tools/backend/evaluate.ts b/packages/playwright-core/src/tools/backend/evaluate.tsindex 6e0ce373f4..30cf32f48f 100644--- a/packages/playwright-core/src/tools/backend/evaluate.ts+++ b/packages/playwright-core/src/tools/backend/evaluate.ts@@ -50,6 +50,7 @@ const evaluate = defineTabTool({}await tab.waitForCompletion(async () => {+ // eslint-disable-next-line no-restricted-syntaxconst func = new Function() as any;func.toString = () => params.function;const result = locator?.locator ? await locator?.locator.evaluate(func) : await tab.page.evaluate(func);diff --git a/packages/playwright-core/src/tools/backend/response.ts b/packages/playwright-core/src/tools/backend/response.tsindex d686353c66..c360348138 100644--- a/packages/playwright-core/src/tools/backend/response.ts+++ b/packages/playwright-core/src/tools/backend/response.ts@@ -276,9 +276,7 @@ function trimMiddle(text: string, maxLength: number) {* Replaces lone surrogates with U+FFFD using String.prototype.toWellFormed().*/function sanitizeUnicode(text: string): string {- if ((String.prototype as any).toWellFormed)- return text.toWellFormed();- return text;+ return text.toWellFormed?.() ?? text;}function parseSections(text: string): Map<string, string> {diff --git a/packages/playwright-core/src/tools/backend/screenshot.ts b/packages/playwright-core/src/tools/backend/screenshot.tsindex b2273965a1..4cfa23e760 100644--- a/packages/playwright-core/src/tools/backend/screenshot.ts+++ b/packages/playwright-core/src/tools/backend/screenshot.ts@@ -86,6 +86,7 @@ export function scaleImageToFitMessage(buffer: Buffer, imageType: 'png' | 'jpeg'const width = image.width * shrink | 0;const height = image.height * shrink | 0;const scaledImage = scaleImageToSize(image, { width, height });+ // eslint-disable-next-line no-restricted-syntaxreturn imageType === 'png' ? PNG.sync.write(scaledImage as any) : jpegjs.encode(scaledImage, 80).data;}diff --git a/packages/playwright-core/src/tools/backend/sessionLog.ts b/packages/playwright-core/src/tools/backend/sessionLog.tsindex 8e213031d2..f4497a2ccd 100644--- a/packages/playwright-core/src/tools/backend/sessionLog.ts+++ b/packages/playwright-core/src/tools/backend/sessionLog.ts@@ -41,10 +41,7 @@ export class SessionLog {}logResponse(toolName: string, toolArgs: Record<string, any>, responseObject: any) {- const parsed = parseResponse(responseObject) as any;- if (parsed)- delete parsed.text;-+ const parsed = { ...parseResponse(responseObject), text: undefined };const lines: string[] = [''];lines.push(`### Tool call: ${toolName}`,diff --git a/packages/playwright-core/src/tools/backend/tab.ts b/packages/playwright-core/src/tools/backend/tab.tsindex be8b823e98..89d4241044 100644--- a/packages/playwright-core/src/tools/backend/tab.ts+++ b/packages/playwright-core/src/tools/backend/tab.ts@@ -132,6 +132,7 @@ export class Tab extends EventEmitter<TabEventsInterface> {void this._downloadStarted(download);}),];+ // eslint-disable-next-line no-restricted-syntax(page as any)[tabSymbol] = this;const wallTime = Date.now();this._consoleLog = new LogFile(this.context, wallTime, 'console', 'Console');@@ -147,6 +148,7 @@ export class Tab extends EventEmitter<TabEventsInterface> {}static forPage(page: playwright.Page): Tab | undefined {+ // eslint-disable-next-line no-restricted-syntaxreturn (page as any)[tabSymbol];}diff --git a/packages/playwright-core/src/tools/backend/tracing.ts b/packages/playwright-core/src/tools/backend/tracing.tsindex 9b1eeeba15..2d8090c0d4 100644--- a/packages/playwright-core/src/tools/backend/tracing.ts+++ b/packages/playwright-core/src/tools/backend/tracing.ts@@ -43,6 +43,7 @@ const tracingStart = defineTool({response.addFileLink('Action log', `${tracesDir}/${name}.trace`);response.addFileLink('Network log', `${tracesDir}/${name}.network`);response.addFileLink('Resources', `${tracesDir}/resources`);+ // eslint-disable-next-line no-restricted-syntax(browserContext.tracing as any)[traceLegendSymbol] = { tracesDir, name };},});@@ -61,6 +62,7 @@ const tracingStop = defineTool({handle: async (context, params, response) => {const browserContext = await context.ensureBrowserContext();await browserContext.tracing.stop();+ // eslint-disable-next-line no-restricted-syntaxconst traceLegend = (browserContext.tracing as any)[traceLegendSymbol];response.addTextResult(`Trace recording stopped.`);response.addFileLink('Trace', `${traceLegend.tracesDir}/${traceLegend.name}.trace`);diff --git a/packages/playwright-core/src/tools/backend/utils.ts b/packages/playwright-core/src/tools/backend/utils.tsindex b235de4d9b..2b1a4a6599 100644--- a/packages/playwright-core/src/tools/backend/utils.ts+++ b/packages/playwright-core/src/tools/backend/utils.ts@@ -59,7 +59,9 @@ export function eventWaiter<T>(page: playwright.Page, event: string, timeout: nuconst disposables: (() => void)[] = [];const eventPromise = new Promise<T | undefined>((resolve, reject) => {+ // eslint-disable-next-line no-restricted-syntaxpage.on(event as any, resolve as any);+ // eslint-disable-next-line no-restricted-syntaxdisposables.push(() => page.off(event as any, resolve as any));});diff --git a/packages/playwright-core/src/tools/backend/verify.ts b/packages/playwright-core/src/tools/backend/verify.tsindex b153575679..60b65272a4 100644--- a/packages/playwright-core/src/tools/backend/verify.ts+++ b/packages/playwright-core/src/tools/backend/verify.ts@@ -18,6 +18,7 @@ import { z } from '../../mcpBundle';import { escapeWithQuotes } from '../../utils/isomorphic/stringUtils';import { defineTabTool } from './tool';+import type * as playwright from '../../..';const verifyElement = defineTabTool({capability: 'testing',@@ -34,7 +35,7 @@ const verifyElement = defineTabTool({handle: async (tab, params, response) => {for (const frame of tab.page.frames()) {- const locator = frame.getByRole(params.role as any, { name: params.accessibleName });+ const locator = frame.getByRole(params.role as Parameters<playwright.Frame['getByRole']>[0], { name: params.accessibleName });if (await locator.count() > 0) {const resolved = await locator.toCode();response.addCode(`await expect(page.${resolved}).toBeVisible();`);diff --git a/packages/playwright-core/src/tools/cli-daemon/command.ts b/packages/playwright-core/src/tools/cli-daemon/command.tsindex 04de065bad..bd60bf7bf7 100644--- a/packages/playwright-core/src/tools/cli-daemon/command.ts+++ b/packages/playwright-core/src/tools/cli-daemon/command.ts@@ -65,7 +65,7 @@ function zodParse(schema: zodType.ZodAny, data: unknown, type: 'option' | 'argumreturn schema.parse(data);} catch (e) {throw new Error((e as zodType.ZodError).issues.map(issue => {- const keys: string[] = (issue as any).keys || [''];+ const keys: string[] = issue.code === 'unrecognized_keys' ? issue.keys : [''];const props = keys.map(key => [...issue.path, key].filter(Boolean).join('.'));return props.map(prop => {const label = type === 'option' ? `'--${prop}' option` : `'${prop}' argument`;diff --git a/packages/playwright-core/src/tools/dashboard/dashboardApp.ts b/packages/playwright-core/src/tools/dashboard/dashboardApp.tsindex becbc59342..f2d8d336c6 100644--- a/packages/playwright-core/src/tools/dashboard/dashboardApp.ts+++ b/packages/playwright-core/src/tools/dashboard/dashboardApp.ts@@ -216,7 +216,8 @@ async function launchApp(appName: string) {const image = await fs.promises.readFile(path.join(__dirname, 'appIcon.png'));// This is local Playwright, so I can access private methods.- await (page as any)._setDockTile(image);+ // eslint-disable-next-line no-restricted-syntax -- it is not essential, can regress.+ await (page as any)._setDockTile?.(image);await syncLocalStorageWithSettings(page, appName);return { context, page };}@@ -238,7 +239,9 @@ export async function syncLocalStorageWithSettings(page: api.Page, appName: striif (window.top !== window)return;Object.entries(settings).map(([k, v]) => localStorage[k] = v);+ // eslint-disable-next-line no-restricted-syntax(window as any).saveSettings = () => {+ // eslint-disable-next-line no-restricted-syntax(window as any)._saveSerializedSettings(JSON.stringify({ ...localStorage }));};})})(${settings});diff --git a/packages/playwright-core/src/tools/dashboard/dashboardController.ts b/packages/playwright-core/src/tools/dashboard/dashboardController.tsindex a20cb91420..d8cf805566 100644--- a/packages/playwright-core/src/tools/dashboard/dashboardController.ts+++ b/packages/playwright-core/src/tools/dashboard/dashboardController.ts@@ -106,6 +106,7 @@ export class DashboardConnection implements Transport, DashboardChannel {async dispatch(method: string, params: any): Promise<any> {await this._initPromise;+ // eslint-disable-next-line no-restricted-syntaxreturn (this as any)[method]?.(params);}@@ -260,10 +261,12 @@ export class DashboardConnection implements Transport, DashboardChannel {}private _pageId(p: api.Page): string {+ // eslint-disable-next-line no-restricted-syntax -- _guid is very conservative.return (p as any)._guid;}private async _devtoolsUrl(page: api.Page) {+ // eslint-disable-next-line no-restricted-syntax -- cdpPort is not in the public LaunchOptions type, fine if regresses.const cdpPort = (this._browserDescriptor.browser.launchOptions as any).cdpPort;if (cdpPort)return new URL(`http://localhost:${cdpPort}/devtools/`);@@ -327,7 +330,7 @@ export class CDPConnection implements Transport {await this._initializePromise;if (!this._rawSession)throw new Error('CDP session is not initialized');- return await this._rawSession.send(method as any, params);+ return await this._rawSession.send(method as Parameters<api.CDPSession['send']>[0], params);}onclose() {diff --git a/packages/playwright-core/src/tools/mcp/browserFactory.ts b/packages/playwright-core/src/tools/mcp/browserFactory.tsindex 26a1605494..6b3f9b2c95 100644--- a/packages/playwright-core/src/tools/mcp/browserFactory.ts+++ b/packages/playwright-core/src/tools/mcp/browserFactory.ts@@ -151,6 +151,7 @@ async function createUserDataDir(config: FullConfig, clientInfo: ClientInfo) {async function injectCdpPort(browserConfig: FullConfig['browser']) {if (browserConfig.browserName === 'chromium')+ // eslint-disable-next-line no-restricted-syntax(browserConfig.launchOptions as any).cdpPort = await findFreePort();}