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: add PW_INSTRUMENT_MODULES for module load profiling (#39884)
Pavel Feldmana8ea6558c5f2
diff --git a/packages/playwright-core/package.json b/packages/playwright-core/package.jsonindex be160162ee..78e95d4431 100644--- a/packages/playwright-core/package.json+++ b/packages/playwright-core/package.json@@ -22,6 +22,7 @@"default": "./index.js"},"./package.json": "./package.json",+ "./lib/bootstrap": "./lib/bootstrap.js","./lib/outofprocess": "./lib/outofprocess.js","./lib/cli/program": "./lib/cli/program.js","./lib/tools/cli-client/program": "./lib/tools/cli-client/program.js",diff --git a/packages/playwright-core/src/bootstrap.ts b/packages/playwright-core/src/bootstrap.tsnew file mode 100644index 0000000000..7ca2fa35c4--- /dev/null+++ b/packages/playwright-core/src/bootstrap.ts@@ -0,0 +1,97 @@+/**+ * 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.+ */++if (process.env.PW_INSTRUMENT_MODULES) {+ const Module = require('module');+ const originalLoad = Module._load;++ type TreeNode = { name: string, selfMs: number, totalMs: number, childrenMs: number, children: TreeNode[] };+ const root: TreeNode = { name: '<root>', selfMs: 0, totalMs: 0, childrenMs: 0, children: [] };+ let current = root;+ const stack: TreeNode[] = [];++ Module._load = function(request: any, _parent: any, _isMain: any) {+ const node: TreeNode = { name: request, selfMs: 0, totalMs: 0, childrenMs: 0, children: [] };+ current.children.push(node);+ stack.push(current);+ current = node;+ const start = performance.now();+ let result;+ try {+ result = originalLoad.apply(this, arguments);+ } catch (e) {+ // Module load failed (e.g. optional dep not found) — unwind stack.+ current = stack.pop()!;+ current.children.pop();+ throw e;+ }+ const duration = performance.now() - start;+ node.totalMs = duration;+ node.selfMs = Math.max(0, duration - node.childrenMs);+ current = stack.pop()!;+ current.childrenMs += duration;+ return result;+ };++ process.on('exit', () => {+ function printTree(node: TreeNode, prefix: string, isLast: boolean, lines: string[], depth: number) {+ if (node.totalMs < 1 && depth > 0)+ return;+ const connector = depth === 0 ? '' : isLast ? '└── ' : '├── ';+ const time = `${node.totalMs.toFixed(1).padStart(8)}ms`;+ const self = node.children.length ? ` (self: ${node.selfMs.toFixed(1)}ms)` : '';+ lines.push(`${time} ${prefix}${connector}${node.name}${self}`);+ const childPrefix = prefix + (depth === 0 ? '' : isLast ? ' ' : '│ ');+ const sorted = node.children.slice().sort((a, b) => b.totalMs - a.totalMs);+ for (let i = 0; i < sorted.length; i++)+ printTree(sorted[i], childPrefix, i === sorted.length - 1, lines, depth + 1);+ }++ let totalModules = 0;+ function count(n: TreeNode) { totalModules++; n.children.forEach(count); }+ root.children.forEach(count);++ const lines: string[] = [];+ const sorted = root.children.slice().sort((a, b) => b.totalMs - a.totalMs);+ for (let i = 0; i < sorted.length; i++)+ printTree(sorted[i], '', i === sorted.length - 1, lines, 0);++ const totalMs = root.children.reduce((s, c) => s + c.totalMs, 0);+ // eslint-disable-next-line no-restricted-properties+ process.stderr.write(`\n--- Module load tree: ${totalModules} modules, ${totalMs.toFixed(0)}ms total ---\n` + lines.join('\n') + '\n');++ // Flat list: aggregate selfMs across all tree nodes by name.+ const flat = new Map<string, { selfMs: number, totalMs: number, count: number }>();+ function gather(n: TreeNode) {+ const existing = flat.get(n.name);+ if (existing) {+ existing.selfMs += n.selfMs;+ existing.totalMs += n.totalMs;+ existing.count++;+ } else {+ flat.set(n.name, { selfMs: n.selfMs, totalMs: n.totalMs, count: 1 });+ }+ n.children.forEach(gather);+ }+ root.children.forEach(gather);+ const top50 = [...flat.entries()].sort((a, b) => b[1].selfMs - a[1].selfMs).slice(0, 50);+ const flatLines = top50.map(([mod, { selfMs, totalMs, count }]) =>+ `${selfMs.toFixed(1).padStart(8)}ms self ${totalMs.toFixed(1).padStart(8)}ms total (x${String(count).padStart(3)}) ${mod}`+ );+ // eslint-disable-next-line no-restricted-properties+ process.stderr.write(`\n--- Top 50 modules by self time ---\n` + flatLines.join('\n') + '\n');+ });+}diff --git a/packages/playwright-core/src/cli/DEPS.list b/packages/playwright-core/src/cli/DEPS.listindex c14a86f58e..7bc1c0cdf0 100644--- a/packages/playwright-core/src/cli/DEPS.list+++ b/packages/playwright-core/src/cli/DEPS.list@@ -11,3 +11,4 @@../tools/trace/traceCli.ts./browserActions.ts./installActions.ts+../bootstrap.tsdiff --git a/packages/playwright-core/src/cli/program.ts b/packages/playwright-core/src/cli/program.tsindex fad903e04d..558ddb8170 100644--- a/packages/playwright-core/src/cli/program.ts+++ b/packages/playwright-core/src/cli/program.ts@@ -16,6 +16,7 @@/* eslint-disable no-console */+import '../bootstrap';import { gracefullyProcessExitDoNotHang, getPackageManagerExecCommand } from '../utils';import { addTraceCommands } from '../tools/trace/traceCli';import { program } from '../utilsBundle';diff --git a/packages/playwright-core/src/server/har/harRecorder.ts b/packages/playwright-core/src/server/har/harRecorder.tsindex 7d99a37790..29965fbd2d 100644--- a/packages/playwright-core/src/server/har/harRecorder.ts+++ b/packages/playwright-core/src/server/har/harRecorder.ts@@ -21,7 +21,6 @@ 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';@@ -52,6 +51,7 @@ 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/localUtils.ts b/packages/playwright-core/src/server/localUtils.tsindex 6e4e0b4e41..4b8480fbf6 100644--- a/packages/playwright-core/src/server/localUtils.ts+++ b/packages/playwright-core/src/server/localUtils.ts@@ -22,7 +22,6 @@ import { calculateSha1 } from './utils/crypto';import { HarBackend } from './harBackend';import { ManualPromise } from '../utils/isomorphic/manualPromise';import { ZipFile } from './utils/zipFile';-import { yauzl, yazl } from '../zipBundle';import { serializeClientSideCallMetadata } from '../utils/isomorphic/trace/traceUtils';import { assert } from '../utils/isomorphic/assert';import { removeFolders } from './utils/fileUtils';@@ -43,6 +42,7 @@ export type StackSession = {export async function zip(progress: Progress, stackSessions: Map<string, StackSession>, params: channels.LocalUtilsZipParams): Promise<void> {const promise = new ManualPromise<void>();+ const { yauzl, yazl } = await import('../zipBundle');const zipFile = new yazl.ZipFile();(zipFile as any as EventEmitter).on('error', error => promise.reject(error));diff --git a/packages/playwright-core/src/server/utils/fileUtils.ts b/packages/playwright-core/src/server/utils/fileUtils.tsindex 7317677981..2b7de307b6 100644--- a/packages/playwright-core/src/server/utils/fileUtils.ts+++ b/packages/playwright-core/src/server/utils/fileUtils.ts@@ -21,7 +21,6 @@ import path from 'path';import { calculateSha1 } from './crypto';import { ManualPromise } from '../../utils/isomorphic/manualPromise';-import { yazl } from '../../zipBundle';import type { EventEmitter } from 'events';@@ -201,6 +200,7 @@ export class SerializedFS {return;}case 'zip': {+ const { yazl } = await import('playwright-core/lib/zipBundle');const zipFile = new yazl.ZipFile();const result = new ManualPromise<void>();(zipFile as any as EventEmitter).on('error', error => result.reject(error));diff --git a/packages/playwright-core/src/server/utils/zipFile.ts b/packages/playwright-core/src/server/utils/zipFile.tsindex 43b5a3430c..b803d6bd56 100644--- a/packages/playwright-core/src/server/utils/zipFile.ts+++ b/packages/playwright-core/src/server/utils/zipFile.ts@@ -14,8 +14,6 @@* limitations under the License.*/-import { yauzl } from '../../zipBundle';-import type { Entry, UnzipFile } from '../../zipBundle';export class ZipFile {@@ -30,6 +28,7 @@ export class ZipFile {}private async _open() {+ const { yauzl } = await import('../../zipBundle');await new Promise<UnzipFile>((fulfill, reject) => {yauzl.open(this._fileName, { autoClose: false }, (e, z) => {if (e) {diff --git a/packages/playwright-core/src/utils.ts b/packages/playwright-core/src/utils.tsindex 405ea86d5d..bdc4d7679d 100644--- a/packages/playwright-core/src/utils.ts+++ b/packages/playwright-core/src/utils.ts@@ -19,6 +19,7 @@ export * from './utils/isomorphic/assert';export * from './utils/isomorphic/colors';export * from './utils/isomorphic/headers';export * from './utils/isomorphic/imageUtils';+export * from './utils/isomorphic/jsonSchema';export * from './utils/isomorphic/locatorGenerators';export * from './utils/isomorphic/manualPromise';export * from './utils/isomorphic/mimeType';diff --git a/packages/playwright-core/src/utils/isomorphic/jsonSchema.ts b/packages/playwright-core/src/utils/isomorphic/jsonSchema.tsnew file mode 100644index 0000000000..684404c7ab--- /dev/null+++ b/packages/playwright-core/src/utils/isomorphic/jsonSchema.ts@@ -0,0 +1,97 @@+/**+ * 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 type JsonSchema = {+ type?: string;+ properties?: Record<string, JsonSchema>;+ required?: string[];+ items?: JsonSchema;+ oneOf?: JsonSchema[];+ pattern?: string;+ patternError?: string;+};++const regexCache = new Map<string, RegExp>();++export function validate(value: unknown, schema: JsonSchema, path: string): string[] {+ const errors: string[] = [];++ if (schema.oneOf) {+ let bestErrors: string[] | undefined;+ for (const variant of schema.oneOf) {+ const variantErrors = validate(value, variant, path);+ if (variantErrors.length === 0)+ return [];+ // Prefer the variant with fewest errors (closest match).+ if (!bestErrors || variantErrors.length < bestErrors.length)+ bestErrors = variantErrors;+ }+ // If the best match has only top-level type mismatches, use a generic message.+ if (bestErrors!.length === 1 && bestErrors![0].startsWith(`${path}: expected `))+ return [`${path}: does not match any of the expected types`];+ return bestErrors!;+ }++ if (schema.type === 'string') {+ if (typeof value !== 'string') {+ errors.push(`${path}: expected string, got ${typeof value}`);+ return errors;+ }+ if (schema.pattern && !cachedRegex(schema.pattern).test(value))+ errors.push(schema.patternError || `${path}: must match pattern "${schema.pattern}"`);+ return errors;+ }++ if (schema.type === 'array') {+ if (!Array.isArray(value)) {+ errors.push(`${path}: expected array, got ${typeof value}`);+ return errors;+ }+ if (schema.items) {+ for (let i = 0; i < value.length; i++)+ errors.push(...validate(value[i], schema.items, `${path}[${i}]`));+ }+ return errors;+ }++ if (schema.type === 'object') {+ if (!value || typeof value !== 'object' || Array.isArray(value)) {+ errors.push(`${path}: expected object, got ${Array.isArray(value) ? 'array' : typeof value}`);+ return errors;+ }+ const obj = value as Record<string, unknown>;+ for (const key of schema.required || []) {+ if (obj[key] === undefined)+ errors.push(`${path}.${key}: required`);+ }+ for (const [key, propSchema] of Object.entries(schema.properties || {})) {+ if (obj[key] !== undefined)+ errors.push(...validate(obj[key], propSchema, `${path}.${key}`));+ }+ return errors;+ }++ return errors;+}++function cachedRegex(pattern: string): RegExp {+ let regex = regexCache.get(pattern);+ if (!regex) {+ regex = new RegExp(pattern);+ regexCache.set(pattern, regex);+ }+ return regex;+}diff --git a/packages/playwright/src/common/process.ts b/packages/playwright/src/common/process.tsindex 80fddc4a41..727c1d9968 100644--- a/packages/playwright/src/common/process.ts+++ b/packages/playwright/src/common/process.ts@@ -14,6 +14,7 @@* limitations under the License.*/+import 'playwright-core/lib/bootstrap';import { ManualPromise, setTimeOrigin, startProfiling, stopProfiling } from 'playwright-core/lib/utils';import { serializeError } from '../util';diff --git a/packages/playwright/src/common/validators.ts b/packages/playwright/src/common/validators.tsindex 40fff8b365..5ab1bd803a 100644--- a/packages/playwright/src/common/validators.ts+++ b/packages/playwright/src/common/validators.ts@@ -14,37 +14,38 @@* limitations under the License.*/-import { z as zod } from 'playwright-core/lib/zodBundle';+import { validate } from 'playwright-core/lib/utils';-import type { TestAnnotation, TestDetailsAnnotation } from '../../types/test';+import type { TestDetailsAnnotation } from '../../types/test';import type { Location } from '../../types/testReporter';-import type { ZodError } from 'zod';+import type { JsonSchema } from 'playwright-core/lib/utils';-const testAnnotationSchema = zod.object({- type: zod.string(),- description: zod.string().optional(),-});--const testDetailsSchema = zod.object({- tag: zod.union([- zod.string().optional(),- zod.array(zod.string())- ]).transform(val => Array.isArray(val) ? val : val !== undefined ? [val] : []).refine(val => val.every(v => v.startsWith('@')), {- message: "Tag must start with '@'"- }),- annotation: zod.union([- testAnnotationSchema,- zod.array(testAnnotationSchema).optional()- ]).transform(val => Array.isArray(val) ? val : val !== undefined ? [val] : []),-});+const testAnnotationSchema: JsonSchema = {+ type: 'object',+ properties: {+ type: { type: 'string' },+ description: { type: 'string' },+ },+ required: ['type'],+};-export function validateTestAnnotation(annotation: unknown): TestAnnotation {- try {- return testAnnotationSchema.parse(annotation);- } catch (error) {- throwZodError(error);- }-}+const testDetailsSchema: JsonSchema = {+ type: 'object',+ properties: {+ tag: {+ oneOf: [+ { type: 'string', pattern: '^@', patternError: "Tag must start with '@'" },+ { type: 'array', items: { type: 'string', pattern: '^@', patternError: "Tag must start with '@'" } },+ ]+ },+ annotation: {+ oneOf: [+ testAnnotationSchema,+ { type: 'array', items: testAnnotationSchema },+ ]+ },+ },+};type ValidTestDetails = {tags: string[];@@ -53,18 +54,20 @@ type ValidTestDetails = {};export function validateTestDetails(details: unknown, location: Location): ValidTestDetails {- try {- const parsedDetails = testDetailsSchema.parse(details);- return {- annotations: parsedDetails.annotation.map(a => ({ ...a, location })),- tags: parsedDetails.tag,- location,- };- } catch (error) {- throwZodError(error);- }-}+ const errors = validate(details, testDetailsSchema, 'details');+ if (errors.length)+ throw new Error(errors.join('\n'));++ const obj = details as Record<string, unknown>;+ const tag = obj.tag;+ const tags: string[] = tag === undefined ? [] : typeof tag === 'string' ? [tag] : tag as string[];++ const annotation = obj.annotation;+ const annotations: TestDetailsAnnotation[] = annotation === undefined ? [] : Array.isArray(annotation) ? annotation : [annotation as TestDetailsAnnotation];-function throwZodError(error: any): never {- throw new Error((error as ZodError).issues.map(i => i.message).join('\n'));+ return {+ annotations: annotations.map(a => ({ ...a, location })),+ tags,+ location,+ };}diff --git a/packages/playwright/src/mcp/test/browserBackend.ts b/packages/playwright/src/mcp/test/browserBackend.tsindex 9097254c3e..72a16f0e52 100644--- a/packages/playwright/src/mcp/test/browserBackend.ts+++ b/packages/playwright/src/mcp/test/browserBackend.ts@@ -14,11 +14,10 @@* limitations under the License.*/-import { createGuid } from 'playwright-core/lib/utils';-import * as tools from 'playwright-core/lib/tools/exports';--import { stripAnsiEscapes } from '../../util';+import crypto from 'crypto';+import { stripAnsiEscapes } from 'playwright-core/lib/utils';+import type * as tools from 'playwright-core/lib/tools/exports';import type * as playwright from '../../../index';import type { TestInfoImpl } from '../../worker/testInfo';import type { Browser } from '../../../../playwright-core/src/client/browser';@@ -39,15 +38,18 @@ export type BrowserMCPResponse = {export function createCustomMessageHandler(testInfo: TestInfoImpl, context: playwright.BrowserContext) {let backend: tools.BrowserBackend | undefined;const config: tools.ContextConfig = { capabilities: ['testing'] };- const toolList = tools.filteredTools(config);+ let tools: typeof import('playwright-core/lib/tools/exports') | undefined;return async (data: BrowserMCPRequest): Promise<BrowserMCPResponse> => {+ if (!tools)+ tools = await import('playwright-core/lib/tools/exports');+ const toolList = tools.filteredTools(config);if (data.initialize) {if (backend)throw new Error('MCP backend is already initialized');backend = new tools.BrowserBackend(config, context, toolList);await backend.initialize(data.initialize.clientInfo);- const pausedMessage = await generatePausedMessage(testInfo, context);+ const pausedMessage = await generatePausedMessage(tools, testInfo, context);return { initialize: { pausedMessage } };}@@ -67,7 +69,7 @@ export function createCustomMessageHandler(testInfo: TestInfoImpl, context: play};}-async function generatePausedMessage(testInfo: TestInfoImpl, context: playwright.BrowserContext) {+async function generatePausedMessage(tools: typeof import('playwright-core/lib/tools/exports'), testInfo: TestInfoImpl, context: playwright.BrowserContext) {const lines: string[] = [];if (testInfo.errors.length) {@@ -114,7 +116,7 @@ export async function runDaemonForContext(testInfo: TestInfoImpl, context: playwif (testInfo._configInternal.configCLIOverrides.debug !== 'cli')return false;- const sessionName = `tw-${createGuid().slice(0, 6)}`;+ const sessionName = `tw-${crypto.randomBytes(3).toString('hex')}`;await (context.browser() as Browser)!._register(sessionName, { workspaceDir: testInfo.project.testDir });/* eslint-disable-next-line no-console */diff --git a/packages/playwright/src/program.ts b/packages/playwright/src/program.tsindex 5e7ff6e652..6951be727f 100644--- a/packages/playwright/src/program.ts+++ b/packages/playwright/src/program.ts@@ -16,6 +16,7 @@/* eslint-disable no-console */+import 'playwright-core/lib/bootstrap';import { gracefullyProcessExitDoNotHang } from 'playwright-core/lib/utils';import { program } from 'playwright-core/lib/cli/program';diff --git a/packages/playwright/src/reporters/blob.ts b/packages/playwright/src/reporters/blob.tsindex 50884a0ee9..844d14b292 100644--- a/packages/playwright/src/reporters/blob.ts+++ b/packages/playwright/src/reporters/blob.ts@@ -21,7 +21,6 @@ import { Readable } from 'stream';import { removeFolders, sanitizeForFilePath } from 'playwright-core/lib/utils';import { ManualPromise, calculateSha1, createGuid, getUserAgent } from 'playwright-core/lib/utils';import { mime } from 'playwright-core/lib/utilsBundle';-import { yazl } from 'playwright-core/lib/zipBundle';import { resolveOutputFile, CommonReporterOptions } from './base';import { TeleReporterEmitter } from './teleEmitter';@@ -76,6 +75,7 @@ export class BlobReporter extends TeleReporterEmitter {const zipFileName = await this._prepareOutputFile();+ const { yazl } = await import('playwright-core/lib/zipBundle');const zipFile = new yazl.ZipFile();const zipFinishPromise = new ManualPromise<undefined>();const finishPromise = zipFinishPromise.catch(e => {diff --git a/packages/playwright/src/reporters/html.ts b/packages/playwright/src/reporters/html.tsindex a72587bcb2..e9c3ca8393 100644--- a/packages/playwright/src/reporters/html.ts+++ b/packages/playwright/src/reporters/html.ts@@ -22,7 +22,6 @@ import { HttpServer, MultiMap, assert, calculateSha1, getPackageManagerExecCommaimport { colors } from 'playwright-core/lib/utils';import { open } from 'playwright-core/lib/utilsBundle';import { mime } from 'playwright-core/lib/utilsBundle';-import { yazl } from 'playwright-core/lib/zipBundle';import { CommonReporterOptions, formatError, formatResultFailure, internalScreen } from './base';import { codeFrameColumns } from '../transform/babelBundle';@@ -33,6 +32,7 @@ import type { HtmlReporterOptions as HtmlReporterConfigOptions, Metadata, TestAnimport type * as api from '../../types/testReporter';import type { HTMLReport, HTMLReportOptions, Location, Stats, TestAttachment, TestCase, TestCaseSummary, TestFile, TestFileSummary, TestResult, TestStep } from '@html-reporter/types';import type { TransformCallback } from 'stream';+import type { ZipFile } from 'playwright-core/lib/zipBundle';type TestEntry = {testCase: TestCase;@@ -145,7 +145,8 @@ class HtmlReporter implements ReporterV2 {const noCopyPrompt = parseBooleanEnvVar('PLAYWRIGHT_HTML_NO_COPY_PROMPT') ?? this._options.noCopyPrompt;const doNotInlineAssets = parseBooleanEnvVar('PLAYWRIGHT_HTML_DO_NOT_INLINE_ASSETS') ?? this._options.doNotInlineAssets ?? false;- const builder = new HtmlBuilder(this.config, this._outputFolder, this._attachmentsBaseURL, doNotInlineAssets, {+ const { yazl } = await import('playwright-core/lib/zipBundle');+ const builder = new HtmlBuilder(yazl, this.config, this._outputFolder, this._attachmentsBaseURL, doNotInlineAssets, {title: process.env.PLAYWRIGHT_HTML_TITLE || this._options.title,noSnippets,noCopyPrompt,@@ -253,13 +254,14 @@ class HtmlBuilder {private _config: api.FullConfig;private _reportFolder: string;private _stepsInFile = new MultiMap<string, TestStep>();- private _dataZipFile = new yazl.ZipFile();+ private _dataZipFile: ZipFile;private _hasTraces = false;private _attachmentsBaseURL: string;private _options: HTMLReportOptions;private _doNotInlineAssets: boolean;- constructor(config: api.FullConfig, outputDir: string, attachmentsBaseURL: string, doNotInlineAssets: boolean, options: HTMLReportOptions) {+ constructor(yazl: typeof import('playwright-core/lib/zipBundle').yazl, config: api.FullConfig, outputDir: string, attachmentsBaseURL: string, doNotInlineAssets: boolean, options: HTMLReportOptions) {+ this._dataZipFile = new yazl.ZipFile();this._config = config;this._reportFolder = outputDir;this._options = options;diff --git a/packages/playwright/src/worker/testTracing.ts b/packages/playwright/src/worker/testTracing.tsindex 2781187450..65367a1062 100644--- a/packages/playwright/src/worker/testTracing.ts+++ b/packages/playwright/src/worker/testTracing.ts@@ -18,7 +18,6 @@ import fs from 'fs';import path from 'path';import { ManualPromise, SerializedFS, calculateSha1, createGuid, getPlaywrightVersion, monotonicTime } from 'playwright-core/lib/utils';-import { yauzl, yazl } from 'playwright-core/lib/zipBundle';import { filteredStackTrace } from '../util';@@ -183,6 +182,7 @@ export class TestTracing {return;}+ const { yazl } = await import('playwright-core/lib/zipBundle');const zipFile = new yazl.ZipFile();if (!this._options?.attachments) {@@ -347,6 +347,7 @@ async function mergeTraceFiles(fileName: string, temporaryTraceFiles: string[])}const mergePromise = new ManualPromise();+ const { yazl, yauzl } = await import('playwright-core/lib/zipBundle');const zipFile = new yazl.ZipFile();const entryNames = new Set<string>();(zipFile as any as EventEmitter).on('error', error => mergePromise.reject(error));diff --git a/tests/library/unit/json-schema.spec.ts b/tests/library/unit/json-schema.spec.tsnew file mode 100644index 0000000000..e3b1d70a36--- /dev/null+++ b/tests/library/unit/json-schema.spec.ts@@ -0,0 +1,113 @@+/**+ * 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 { 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';++it('should validate string type', () => {+ expect(validate('hello', { type: 'string' }, '$')).toEqual([]);+ expect(validate(123, { type: 'string' }, '$')).toEqual(['$: expected string, got number']);+});++it('should validate string pattern', () => {+ expect(validate('@tag', { type: 'string', pattern: '^@' }, '$')).toEqual([]);+ expect(validate('tag', { type: 'string', pattern: '^@' }, '$')).toEqual(['$: must match pattern "^@"']);+});++it('should validate array type', () => {+ expect(validate([], { type: 'array' }, '$')).toEqual([]);+ expect(validate('not-array', { type: 'array' }, '$')).toEqual(['$: expected array, got string']);+});++it('should validate array items', () => {+ const schema: JsonSchema = { type: 'array', items: { type: 'string' } };+ expect(validate(['a', 'b'], schema, '$')).toEqual([]);+ expect(validate(['a', 1], schema, '$')).toEqual(['$[1]: expected string, got number']);+});++it('should validate object type', () => {+ expect(validate({}, { type: 'object' }, '$')).toEqual([]);+ expect(validate(null, { type: 'object' }, '$')).toEqual(['$: expected object, got object']);+ expect(validate([], { type: 'object' }, '$')).toEqual(['$: expected object, got array']);+ expect(validate('str', { type: 'object' }, '$')).toEqual(['$: expected object, got string']);+});++it('should validate required properties', () => {+ const schema: JsonSchema = { type: 'object', properties: { name: { type: 'string' } }, required: ['name'] };+ expect(validate({ name: 'test' }, schema, '$')).toEqual([]);+ expect(validate({}, schema, '$')).toEqual(['$.name: required']);+});++it('should validate optional properties', () => {+ const schema: JsonSchema = { type: 'object', properties: { name: { type: 'string' } } };+ expect(validate({}, schema, '$')).toEqual([]);+ expect(validate({ name: 'test' }, schema, '$')).toEqual([]);+ expect(validate({ name: 123 }, schema, '$')).toEqual(['$.name: expected string, got number']);+});++it('should validate oneOf', () => {+ const schema: JsonSchema = { oneOf: [{ type: 'string' }, { type: 'array', items: { type: 'string' } }] };+ expect(validate('hello', schema, '$')).toEqual([]);+ expect(validate(['a', 'b'], schema, '$')).toEqual([]);+ expect(validate(123, schema, '$')).toEqual(['$: does not match any of the expected types']);+});++it('should validate nested objects', () => {+ const schema: JsonSchema = {+ type: 'object',+ properties: {+ annotation: {+ type: 'object',+ properties: { type: { type: 'string' } },+ required: ['type'],+ }+ }+ };+ expect(validate({ annotation: { type: 'info' } }, schema, '$')).toEqual([]);+ expect(validate({ annotation: {} }, schema, '$')).toEqual(['$.annotation.type: required']);+ expect(validate({ annotation: { type: 123 } }, schema, '$')).toEqual(['$.annotation.type: expected string, got number']);+});++it('should validate test details schema', () => {+ const testAnnotationSchema: JsonSchema = {+ type: 'object',+ properties: { type: { type: 'string' }, description: { type: 'string' } },+ required: ['type'],+ };+ const testDetailsSchema: JsonSchema = {+ type: 'object',+ properties: {+ tag: { oneOf: [{ type: 'string', pattern: '^@' }, { type: 'array', items: { type: 'string', pattern: '^@' } }] },+ annotation: { oneOf: [testAnnotationSchema, { type: 'array', items: testAnnotationSchema }] },+ },+ };++ // Valid cases.+ expect(validate({}, testDetailsSchema, '$')).toEqual([]);+ expect(validate({ tag: '@fast' }, testDetailsSchema, '$')).toEqual([]);+ expect(validate({ tag: ['@fast', '@slow'] }, testDetailsSchema, '$')).toEqual([]);+ expect(validate({ annotation: { type: 'issue' } }, testDetailsSchema, '$')).toEqual([]);+ expect(validate({ annotation: { type: 'issue', description: 'bug' } }, testDetailsSchema, '$')).toEqual([]);+ expect(validate({ annotation: [{ type: 'a' }, { type: 'b' }] }, testDetailsSchema, '$')).toEqual([]);+ expect(validate({ tag: '@fast', annotation: { type: 'issue' } }, testDetailsSchema, '$')).toEqual([]);++ // Invalid cases.+ expect(validate({ tag: 'no-at' }, testDetailsSchema, '$').length).toBeGreaterThan(0);+ expect(validate({ tag: ['@ok', 'no-at'] }, testDetailsSchema, '$').length).toBeGreaterThan(0);+ expect(validate({ annotation: 'not-object' }, testDetailsSchema, '$').length).toBeGreaterThan(0);+ expect(validate({ annotation: { description: 'missing type' } }, testDetailsSchema, '$').length).toBeGreaterThan(0);+});diff --git a/tests/playwright-test/perf.spec.ts b/tests/playwright-test/perf.spec.tsnew file mode 100644index 0000000000..d8cb05abdb--- /dev/null+++ b/tests/playwright-test/perf.spec.ts@@ -0,0 +1,33 @@+/**+ * 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 { test, expect } from './playwright-test-fixtures';++test('should not load rare bundles during test run', async ({ runInlineTest }) => {+ const result = await runInlineTest({+ 'a.spec.ts': `+ import { test, expect } from '@playwright/test';+ test('pass', async ({ page }) => {});+ `+ }, {}, { PW_INSTRUMENT_MODULES: '1' });+ expect(result.exitCode).toBe(0);+ expect(result.passed).toBe(1);+ const output = result.output;+ expect(output).toContain('utilsBundle');+ expect(output).not.toContain('mcpBundle');+ expect(output).not.toContain('zodBundle');+ expect(output).not.toContain('zipBundle');+});