siga-checker

This commit is contained in:
kl3z00
2026-10-26 15:40:57 +00:00
commit ac028376a1
36 changed files with 15596 additions and 0 deletions
+78
View File
@@ -0,0 +1,78 @@
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var reportActions_exports = {};
__export(reportActions_exports, {
mergeReports: () => mergeReports,
showReport: () => showReport
});
module.exports = __toCommonJS(reportActions_exports);
var import_fs = __toESM(require("fs"));
var import_path = __toESM(require("path"));
var import_common = require("../common");
var import_runner = require("../runner");
const { gracefullyProcessExitDoNotHang } = require("playwright-core/lib/coreBundle").utils;
async function showReport(report, host, port) {
await import_runner.html.showHTMLReport(report, host, port);
}
async function mergeReports(reportDir, opts) {
const configFile = opts.config;
const config = configFile ? await import_common.configLoader.loadConfigFromFile(configFile) : await import_common.configLoader.loadEmptyConfigForMergeReports();
const dir = import_path.default.resolve(process.cwd(), reportDir || "");
const dirStat = await import_fs.default.promises.stat(dir).catch((e) => null);
if (!dirStat)
throw new Error("Directory does not exist: " + dir);
if (!dirStat.isDirectory())
throw new Error(`"${dir}" is not a directory`);
let reporterDescriptions = resolveReporterOption(opts.reporter);
if (!reporterDescriptions && configFile)
reporterDescriptions = config.config.reporter;
if (!reporterDescriptions)
reporterDescriptions = [[import_common.config.defaultReporter]];
const rootDirOverride = configFile ? config.config.rootDir : void 0;
const result = await import_runner.merge.createMergedReport(config, dir, reporterDescriptions, rootDirOverride);
gracefullyProcessExitDoNotHang(result === "failed" ? 1 : 0);
}
function resolveReporterOption(reporter) {
if (!reporter || !reporter.length)
return void 0;
return reporter.split(",").map((r) => [resolveReporter(r)]);
}
function resolveReporter(id) {
if (import_common.builtInReporters.includes(id))
return id;
const localPath = import_path.default.resolve(process.cwd(), id);
if (import_fs.default.existsSync(localPath))
return localPath;
return require.resolve(id, { paths: [process.cwd()] });
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
mergeReports,
showReport
});
+214
View File
@@ -0,0 +1,214 @@
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var testActions_exports = {};
__export(testActions_exports, {
clearCache: () => clearCache,
runTestServerAction: () => runTestServerAction,
runTests: () => runTests
});
module.exports = __toCommonJS(testActions_exports);
var import_fs = __toESM(require("fs"));
var import_path = __toESM(require("path"));
var import_common = require("../common");
var import_runner = require("../runner");
const { gracefullyProcessExitDoNotHang } = require("playwright-core/lib/coreBundle").utils;
const { startProfiling, stopProfiling } = require("playwright-core/lib/coreBundle").utils;
async function runTests(args, opts) {
await startProfiling();
const cliOverrides = overridesFromOptions(opts);
cliOverrides.argv = process.argv;
const config = await import_common.configLoader.loadConfigFromFile(opts.config, cliOverrides, opts.deps === false);
const options = {
locations: args.length ? args : void 0,
grep: opts.grep,
grepInvert: opts.grepInvert,
onlyChanged: opts.onlyChanged === true ? "HEAD" : opts.onlyChanged,
listMode: !!opts.list,
projectFilter: opts.project || void 0,
passWithNoTests: !!opts.passWithNoTests,
lastFailed: !!opts.lastFailed,
lastFailedFile: opts.lastFailedFile,
testList: opts.testList ? import_path.default.resolve(process.cwd(), opts.testList) : void 0,
testListInvert: opts.testListInvert ? import_path.default.resolve(process.cwd(), opts.testListInvert) : void 0,
shardWeights: resolveShardWeightsOption()
};
import_runner.projectUtils.filterProjects(config.projects, options.projectFilter);
if (opts.ui || opts.uiHost || opts.uiPort) {
if (opts.onlyChanged)
throw new Error(`--only-changed is not supported in UI mode. If you'd like that to change, see https://github.com/microsoft/playwright/issues/15075 for more details.`);
const status2 = await import_runner.testServer.runUIMode(opts.config, cliOverrides, {
host: opts.uiHost,
port: opts.uiPort ? +opts.uiPort : void 0,
args,
grep: opts.grep,
grepInvert: opts.grepInvert,
project: opts.project || void 0,
reporter: Array.isArray(opts.reporter) ? opts.reporter : opts.reporter ? [opts.reporter] : void 0
});
await stopProfiling("runner");
const exitCode2 = status2 === "interrupted" ? 130 : status2 === "passed" ? 0 : 1;
gracefullyProcessExitDoNotHang(exitCode2);
return;
}
if (process.env.PWTEST_WATCH) {
if (opts.onlyChanged)
throw new Error(`--only-changed is not supported in watch mode. If you'd like that to change, file an issue and let us know about your usecase for it.`);
const status2 = await import_runner.watchMode.runWatchModeLoop(
import_common.configLoader.resolveConfigLocation(opts.config),
{
projects: opts.project,
files: args,
grep: opts.grep
}
);
await stopProfiling("runner");
const exitCode2 = status2 === "interrupted" ? 130 : status2 === "passed" ? 0 : 1;
gracefullyProcessExitDoNotHang(exitCode2);
return;
}
const status = await import_runner.testRunner.runAllTestsWithConfig(config, options);
await stopProfiling("runner");
const exitCode = status === "interrupted" ? 130 : status === "passed" ? 0 : 1;
gracefullyProcessExitDoNotHang(exitCode);
}
async function runTestServerAction(opts) {
const host = opts.host;
const port = opts.port ? +opts.port : void 0;
const status = await import_runner.testServer.runTestServer(opts.config, {}, { host, port });
const exitCode = status === "interrupted" ? 130 : status === "passed" ? 0 : 1;
gracefullyProcessExitDoNotHang(exitCode);
}
async function clearCache(opts) {
const runner = new import_runner.testRunner.TestRunner(import_common.configLoader.resolveConfigLocation(opts.config), {});
const { status } = await runner.clearCache(import_runner.runnerReporters.createErrorCollectingReporter(import_runner.base.terminalScreen));
const exitCode = status === "interrupted" ? 130 : status === "passed" ? 0 : 1;
gracefullyProcessExitDoNotHang(exitCode);
}
function overridesFromOptions(options) {
if (options.ui) {
options.debug = void 0;
options.trace = void 0;
}
const overrides = {
debug: options.debug,
failOnFlakyTests: options.failOnFlakyTests ? true : void 0,
forbidOnly: options.forbidOnly ? true : void 0,
fullyParallel: options.fullyParallel ? true : void 0,
globalTimeout: options.globalTimeout ? parseInt(options.globalTimeout, 10) : void 0,
maxFailures: options.x ? 1 : options.maxFailures ? parseInt(options.maxFailures, 10) : void 0,
outputDir: options.output ? import_path.default.resolve(process.cwd(), options.output) : void 0,
pause: !!process.env.PWPAUSE,
quiet: options.quiet ? options.quiet : void 0,
repeatEach: options.repeatEach ? parseInt(options.repeatEach, 10) : void 0,
retries: options.retries ? parseInt(options.retries, 10) : void 0,
reporter: resolveReporterOption(options.reporter),
additionalReporters: resolveReporterOption(options.addReporter),
shard: resolveShardOption(options.shard),
timeout: options.timeout ? parseInt(options.timeout, 10) : void 0,
tsconfig: options.tsconfig ? import_path.default.resolve(process.cwd(), options.tsconfig) : void 0,
ignoreSnapshots: options.ignoreSnapshots ? !!options.ignoreSnapshots : void 0,
updateSnapshots: options.updateSnapshots,
updateSourceMethod: options.updateSourceMethod,
use: {
trace: options.trace
},
workers: options.workers
};
if (options.browser) {
const browserOpt = options.browser.toLowerCase();
if (!["all", "chromium", "firefox", "webkit"].includes(browserOpt))
throw new Error(`Unsupported browser "${options.browser}", must be one of "all", "chromium", "firefox" or "webkit"`);
const browserNames = browserOpt === "all" ? ["chromium", "firefox", "webkit"] : [browserOpt];
overrides.projects = browserNames.map((browserName) => {
return {
name: browserName,
use: { browserName }
};
});
}
if (options.headed)
overrides.use.headless = false;
if (options.debug === "inspector") {
overrides.use.headless = false;
process.env.PWDEBUG = "1";
}
if (overrides.tsconfig && !import_fs.default.existsSync(overrides.tsconfig))
throw new Error(`--tsconfig "${options.tsconfig}" does not exist`);
return overrides;
}
function resolveReporterOption(reporter) {
if (!reporter || !reporter.length)
return void 0;
return reporter.split(",").map((r) => [resolveReporter(r)]);
}
function resolveShardOption(shard) {
if (!shard)
return void 0;
const shardPair = shard.split("/");
if (shardPair.length !== 2) {
throw new Error(
`--shard "${shard}", expected format is "current/all", 1-based, for example "3/5".`
);
}
const current = parseInt(shardPair[0], 10);
const total = parseInt(shardPair[1], 10);
if (isNaN(total) || total < 1)
throw new Error(`--shard "${shard}" total must be a positive number`);
if (isNaN(current) || current < 1 || current > total) {
throw new Error(
`--shard "${shard}" current must be a positive number, not greater than shard total`
);
}
return { current, total };
}
function resolveShardWeightsOption() {
const shardWeights = process.env.PWTEST_SHARD_WEIGHTS;
if (!shardWeights)
return void 0;
return shardWeights.split(":").map((w) => {
const weight = parseInt(w, 10);
if (isNaN(weight) || weight < 0)
throw new Error(`PWTEST_SHARD_WEIGHTS="${shardWeights}" weights must be non-negative numbers`);
return weight;
});
}
function resolveReporter(id) {
if (import_common.builtInReporters.includes(id))
return id;
const localPath = import_path.default.resolve(process.cwd(), id);
if (import_fs.default.existsSync(localPath))
return localPath;
return require.resolve(id, { paths: [process.cwd()] });
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
clearCache,
runTestServerAction,
runTests
});
+58
View File
@@ -0,0 +1,58 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var globals_exports = {};
__export(globals_exports, {
currentTestInfo: () => currentTestInfo,
currentlyLoadingFileSuite: () => currentlyLoadingFileSuite,
isWorkerProcess: () => isWorkerProcess,
setCurrentTestInfo: () => setCurrentTestInfo,
setCurrentlyLoadingFileSuite: () => setCurrentlyLoadingFileSuite,
setIsWorkerProcess: () => setIsWorkerProcess
});
module.exports = __toCommonJS(globals_exports);
let currentTestInfoValue = null;
function setCurrentTestInfo(testInfo) {
currentTestInfoValue = testInfo;
}
function currentTestInfo() {
return currentTestInfoValue;
}
let currentFileSuite;
function setCurrentlyLoadingFileSuite(suite) {
currentFileSuite = suite;
}
function currentlyLoadingFileSuite() {
return currentFileSuite;
}
let _isWorkerProcess = false;
function setIsWorkerProcess() {
_isWorkerProcess = true;
}
function isWorkerProcess() {
return _isWorkerProcess;
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
currentTestInfo,
currentlyLoadingFileSuite,
isWorkerProcess,
setCurrentTestInfo,
setCurrentlyLoadingFileSuite,
setIsWorkerProcess
});
+815
View File
@@ -0,0 +1,815 @@
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var index_exports = {};
__export(index_exports, {
_baseTest: () => _baseTest,
_utilityTest: () => _utilityTest,
defineConfig: () => import_common2.defineConfig,
expect: () => import_expect.expect,
mergeExpects: () => import_expect2.mergeExpects,
mergeTests: () => import_common2.mergeTests,
test: () => test
});
module.exports = __toCommonJS(index_exports);
var import_fs = __toESM(require("fs"));
var import_path = __toESM(require("path"));
var playwrightLibrary = __toESM(require("playwright-core"));
var import_errorContext = require("./errorContext");
var import_common = require("./common");
var globals = __toESM(require("./globals"));
var import_browserBackend = require("./mcp/test/browserBackend");
var import_expect = require("./matchers/expect");
var import_common2 = require("./common");
var import_expect2 = require("./matchers/expect");
const { getActionGroup, renderParamsForCall, renderSubtitleForCall, renderTitleForCall, truncateParam } = require("playwright-core/lib/coreBundle").iso;
const { escapeHTML } = require("playwright-core/lib/coreBundle").iso;
const { jsonStringifyForceASCII } = require("playwright-core/lib/coreBundle").utils;
const { createGuid } = require("playwright-core/lib/coreBundle").utils;
const { debugMode } = require("playwright-core/lib/coreBundle").utils;
const { debugLogger } = require("playwright-core/lib/coreBundle").utils;
const { currentZone } = require("playwright-core/lib/coreBundle").utils;
const _baseTest = import_common.testType.rootTestType.test;
if (process["__pw_initiator__"]) {
const originalStackTraceLimit = Error.stackTraceLimit;
Error.stackTraceLimit = 200;
try {
throw new Error("Requiring @playwright/test second time, \nFirst:\n" + process["__pw_initiator__"] + "\n\nSecond: ");
} finally {
Error.stackTraceLimit = originalStackTraceLimit;
}
} else {
process["__pw_initiator__"] = new Error().stack;
}
const utilityFixtures = {
playwright: [async ({}, use) => {
await use(require("playwright-core"));
}, { scope: "worker", box: true }],
screenshot: ["off", { scope: "worker", option: true, box: true }],
trace: ["off", { scope: "worker", option: true, box: true }],
testIdAttribute: ["data-testid", { option: true, box: true }],
_combinedContextOptions: [{}, { box: true }],
_setupArtifacts: [async ({ playwright, screenshot, _combinedContextOptions }, use, testInfo) => {
testInfo.setTimeout(testInfo.project.timeout);
const artifactsRecorder = new ArtifactsRecorder(playwright, tracing().artifactsDir(), screenshot);
await artifactsRecorder.willStartTest(testInfo);
const tracingGroupSteps = [];
const pausedContexts = /* @__PURE__ */ new Set();
const csiListener = {
onApiCallBegin: (data, channel) => {
const testInfo2 = globals.currentTestInfo();
if (!testInfo2)
return;
if (channel.type === "Tracing" && channel.method === "tracingGroupEnd") {
data.userData = (error) => tracingGroupSteps.pop()?.complete({ error });
return;
}
const zone = currentZone().data("stepZone");
const isExpectCall = channel.type === "Frame" && channel.method === "expect" || channel.type === "Page" && channel.method === "expectScreenshot";
if (zone && zone.category === "expect" && isExpectCall) {
data.stepId = zone.stepId;
return;
}
const params = renderParamsForCall({ type: channel.type, method: channel.method, params: channel.params });
const step = testInfo2._addStep({
location: data.frames[0],
category: "pw:api",
title: renderTitle(channel.type, channel.method, channel.params, data.title),
subtitle: renderSubtitle(channel.type, channel.method, channel.params),
params,
group: getActionGroup({ type: channel.type, method: channel.method })
}, tracingGroupSteps[tracingGroupSteps.length - 1]);
data.stepId = step.stepId;
if (channel.type === "Tracing" && channel.method === "tracingGroup") {
tracingGroupSteps.push(step);
} else {
data.userData = (error) => step.complete({ error });
}
},
onApiCallEnd: (data) => {
const completeStep = data.userData;
completeStep?.(data.error);
},
onWillPause: ({ keepTestTimeout }) => {
if (!keepTestTimeout)
globals.currentTestInfo()?._setIgnoreTimeouts(true);
},
runBeforeCreateBrowserContext: async (options) => {
for (const [key, value] of Object.entries(_combinedContextOptions)) {
if (!(key in options))
options[key] = value;
}
},
runBeforeCreateRequestContext: async (options) => {
for (const [key, value] of Object.entries(_combinedContextOptions)) {
if (!(key in options))
options[key] = value;
}
},
runAfterCreateBrowserContext: async (context) => {
context.debugger.on("pausedstatechanged", () => {
const paused = !!context.debugger.pausedDetails();
if (pausedContexts.has(context) && !paused) {
pausedContexts.delete(context);
testInfo._setIgnoreTimeouts(false);
} else if (!pausedContexts.has(context) && paused) {
pausedContexts.add(context);
testInfo._setIgnoreTimeouts(true);
}
});
await artifactsRecorder.didCreateBrowserContext(context);
const currentTestInfo = globals.currentTestInfo();
if (currentTestInfo) {
attachConnectedHeaderIfNeeded(currentTestInfo, context.browser());
currentTestInfo._onCustomMessageCallback = (0, import_browserBackend.createCustomMessageHandler)(currentTestInfo, context);
await (0, import_browserBackend.runDaemonForContext)(currentTestInfo, context);
}
},
runAfterCreateRequestContext: async (context) => {
await artifactsRecorder.didCreateRequestContext(context);
},
runBeforeCloseBrowserContext: async (context) => {
await artifactsRecorder.willCloseBrowserContext(context);
},
runBeforeCloseRequestContext: async (context) => {
await artifactsRecorder.willCloseRequestContext(context);
}
};
const clientInstrumentation = playwright._instrumentation;
clientInstrumentation.addListener(csiListener);
await use();
clientInstrumentation.removeListener(csiListener);
await artifactsRecorder.didFinishTest();
}, { auto: "all-hooks-included", title: "trace recording", box: true, timeout: 0 }],
request: async ({ playwright }, use) => {
const request = await playwright.request.newContext();
await use(request);
const hook = test.info()._currentHookType();
if (hook === "beforeAll") {
await request.dispose({ reason: [
`Fixture { request } from beforeAll cannot be reused in a test.`,
` - Recommended fix: use a separate { request } in the test.`,
` - Alternatively, manually create APIRequestContext in beforeAll and dispose it in afterAll.`,
`See https://playwright.dev/docs/api-testing#sending-api-requests-from-ui-tests for more details.`
].join("\n") });
} else {
await request.dispose();
}
}
};
const _utilityTest = _baseTest.extend(utilityFixtures);
const playwrightFixtures = {
defaultBrowserType: ["chromium", { scope: "worker", option: true, box: true }],
browserName: [({ defaultBrowserType }, use) => use(defaultBrowserType), { scope: "worker", option: true, box: true }],
headless: [({ launchOptions }, use) => use(launchOptions.headless ?? true), { scope: "worker", option: true, box: true }],
channel: [({ launchOptions }, use) => use(launchOptions.channel), { scope: "worker", option: true, box: true }],
launchOptions: [{}, { scope: "worker", option: true, box: true }],
connectOptions: [async ({ _optionConnectOptions }, use) => {
await use(connectOptionsFromEnv() || _optionConnectOptions);
}, { scope: "worker", option: true, box: true }],
video: ["off", { scope: "worker", option: true, box: true }],
_browserOptions: [async ({ playwright, headless, channel, launchOptions }, use) => {
const options = {
handleSIGINT: false,
...launchOptions,
tracesDir: tracing().tracesDir(),
artifactsDir: tracing().artifactsDir()
};
if (headless !== void 0)
options.headless = headless;
if (channel !== void 0)
options.channel = channel;
playwright._defaultLaunchOptions = options;
await use(options);
playwright._defaultLaunchOptions = void 0;
}, { scope: "worker", auto: true, box: true }],
browser: [async ({ playwright, browserName, _browserOptions, connectOptions }, use, workerInfo) => {
if (!["chromium", "firefox", "webkit"].includes(browserName))
throw new Error(`Unexpected browserName "${browserName}", must be one of "chromium", "firefox" or "webkit"`);
if (connectOptions) {
const browser2 = await playwright[browserName].connect(connectOptions.wsEndpoint, {
...connectOptions,
exposeNetwork: connectOptions.exposeNetwork,
headers: {
// HTTP headers are ASCII only (not UTF-8).
"x-playwright-launch-options": jsonStringifyForceASCII(_browserOptions),
...connectOptions.headers
}
});
await use(browser2);
await browser2.close({ reason: "Test ended." });
return;
}
const browser = await playwright[browserName].launch();
if (process.env.PLAYWRIGHT_DASHBOARD)
await browser.bind(`worker-${workerInfo.parallelIndex}`);
await use(browser);
await browser.close({ reason: "Test ended." });
}, { scope: "worker", timeout: 0 }],
acceptDownloads: [({ contextOptions }, use) => use(contextOptions.acceptDownloads ?? true), { option: true, box: true }],
bypassCSP: [({ contextOptions }, use) => use(contextOptions.bypassCSP ?? false), { option: true, box: true }],
colorScheme: [({ contextOptions }, use) => use(contextOptions.colorScheme === void 0 ? "light" : contextOptions.colorScheme), { option: true, box: true }],
contrast: [({ contextOptions }, use) => use(contextOptions.contrast === void 0 ? "no-preference" : contextOptions.contrast), { option: true, box: true }],
deviceScaleFactor: [({ contextOptions }, use) => use(contextOptions.deviceScaleFactor), { option: true, box: true }],
extraHTTPHeaders: [({ contextOptions }, use) => use(contextOptions.extraHTTPHeaders), { option: true, box: true }],
forcedColors: [({ contextOptions }, use) => use(contextOptions.forcedColors === void 0 ? "none" : contextOptions.forcedColors), { option: true, box: true }],
geolocation: [({ contextOptions }, use) => use(contextOptions.geolocation), { option: true, box: true }],
hasTouch: [({ contextOptions }, use) => use(contextOptions.hasTouch ?? false), { option: true, box: true }],
httpCredentials: [({ contextOptions }, use) => use(contextOptions.httpCredentials), { option: true, box: true }],
ignoreHTTPSErrors: [({ contextOptions }, use) => use(contextOptions.ignoreHTTPSErrors ?? false), { option: true, box: true }],
isMobile: [({ contextOptions }, use) => use(contextOptions.isMobile ?? false), { option: true, box: true }],
javaScriptEnabled: [({ contextOptions }, use) => use(contextOptions.javaScriptEnabled ?? true), { option: true, box: true }],
locale: [({ contextOptions }, use) => use(contextOptions.locale ?? "en-US"), { option: true, box: true }],
offline: [({ contextOptions }, use) => use(contextOptions.offline ?? false), { option: true, box: true }],
permissions: [({ contextOptions }, use) => use(contextOptions.permissions), { option: true, box: true }],
proxy: [({ contextOptions }, use) => use(contextOptions.proxy), { option: true, box: true }],
reducedMotion: [({ contextOptions }, use) => use(contextOptions.reducedMotion === void 0 ? "no-preference" : contextOptions.reducedMotion), { option: true, box: true }],
storageState: [({ contextOptions }, use) => use(contextOptions.storageState), { option: true, box: true }],
clientCertificates: [({ contextOptions }, use) => use(contextOptions.clientCertificates), { option: true, box: true }],
timezoneId: [({ contextOptions }, use) => use(contextOptions.timezoneId), { option: true, box: true }],
userAgent: [({ contextOptions }, use) => use(contextOptions.userAgent), { option: true, box: true }],
viewport: [({ contextOptions }, use) => use(contextOptions.viewport === void 0 ? { width: 1280, height: 720 } : contextOptions.viewport), { option: true, box: true }],
actionTimeout: [0, { option: true, box: true }],
navigationTimeout: [0, { option: true, box: true }],
baseURL: [async ({}, use) => {
await use(process.env.PLAYWRIGHT_TEST_BASE_URL);
}, { option: true, box: true }],
serviceWorkers: [({ contextOptions }, use) => use(contextOptions.serviceWorkers ?? "allow"), { option: true, box: true }],
contextOptions: [{}, { option: true, box: true }],
_combinedContextOptions: [async ({
acceptDownloads,
bypassCSP,
clientCertificates,
colorScheme,
contrast,
deviceScaleFactor,
extraHTTPHeaders,
forcedColors,
hasTouch,
geolocation,
httpCredentials,
ignoreHTTPSErrors,
isMobile,
javaScriptEnabled,
locale,
offline,
permissions,
proxy,
reducedMotion,
storageState,
viewport,
timezoneId,
userAgent,
baseURL,
contextOptions,
serviceWorkers
}, use, testInfo) => {
const options = {};
if (acceptDownloads !== void 0)
options.acceptDownloads = acceptDownloads;
if (bypassCSP !== void 0)
options.bypassCSP = bypassCSP;
if (colorScheme !== void 0)
options.colorScheme = colorScheme;
if (contrast !== void 0)
options.contrast = contrast;
if (deviceScaleFactor !== void 0)
options.deviceScaleFactor = deviceScaleFactor;
if (extraHTTPHeaders !== void 0)
options.extraHTTPHeaders = extraHTTPHeaders;
if (forcedColors !== void 0)
options.forcedColors = forcedColors;
if (geolocation !== void 0)
options.geolocation = geolocation;
if (hasTouch !== void 0)
options.hasTouch = hasTouch;
if (httpCredentials !== void 0)
options.httpCredentials = httpCredentials;
if (ignoreHTTPSErrors !== void 0)
options.ignoreHTTPSErrors = ignoreHTTPSErrors;
if (isMobile !== void 0)
options.isMobile = isMobile;
if (javaScriptEnabled !== void 0)
options.javaScriptEnabled = javaScriptEnabled;
if (locale !== void 0)
options.locale = locale;
if (offline !== void 0)
options.offline = offline;
if (permissions !== void 0)
options.permissions = permissions;
if (proxy !== void 0)
options.proxy = proxy;
if (reducedMotion !== void 0)
options.reducedMotion = reducedMotion;
if (storageState !== void 0)
options.storageState = storageState;
if (clientCertificates?.length)
options.clientCertificates = resolveClientCerticates(clientCertificates);
if (timezoneId !== void 0)
options.timezoneId = timezoneId;
if (userAgent !== void 0)
options.userAgent = userAgent;
if (viewport !== void 0)
options.viewport = viewport;
if (baseURL !== void 0)
options.baseURL = baseURL;
if (serviceWorkers !== void 0)
options.serviceWorkers = serviceWorkers;
await use({
...contextOptions,
...options
});
}, { scope: "test", box: true }],
_setupContextOptions: [async ({ playwright, actionTimeout, navigationTimeout, testIdAttribute }, use, _testInfo) => {
const testInfo = _testInfo;
if (testIdAttribute)
playwrightLibrary.selectors.setTestIdAttribute(testIdAttribute);
testInfo.snapshotSuffix = process.platform;
testInfo._onCustomMessageCallback = () => Promise.reject(new Error("Only tests that use default Playwright context or page fixture support test_debug"));
if (debugMode() === "inspector")
testInfo._setIgnoreTimeouts(true);
playwright._defaultContextTimeout = actionTimeout || 0;
playwright._defaultContextNavigationTimeout = navigationTimeout || 0;
await use();
playwright._defaultContextTimeout = void 0;
playwright._defaultContextNavigationTimeout = void 0;
}, { auto: "all-hooks-included", title: "context configuration", box: true }],
_contextFactory: [async ({
browser,
video,
_reuseContext,
_combinedContextOptions
/** mitigate dep-via-auto lack of traceability */
}, use, testInfo) => {
const testInfoImpl = testInfo;
const videoMode = normalizeVideoMode(video);
const captureVideo = shouldCaptureVideo(videoMode, testInfo) && !_reuseContext;
const contexts = /* @__PURE__ */ new Map();
let counter = 0;
await use(async (options) => {
const hook = testInfoImpl._currentHookType();
if (hook === "beforeAll" || hook === "afterAll") {
throw new Error([
`"context" and "page" fixtures are not supported in "${hook}" since they are created on a per-test basis.`,
`If you would like to reuse a single page between tests, create context manually with browser.newContext(). See https://aka.ms/playwright/reuse-page for details.`,
`If you would like to configure your page before each test, do that in beforeEach hook instead.`
].join("\n"));
}
const show = typeof video === "string" ? void 0 : video.show;
const videoOptions = captureVideo ? {
recordVideo: {
dir: tracing().artifactsDir(),
size: typeof video === "string" ? void 0 : video.size,
showActions: show?.actions
}
} : {};
const context = await browser.newContext({ ...videoOptions, ...options });
let closed = false;
const close = async () => {
if (closed)
return;
closed = true;
const closeReason = testInfo.status === "timedOut" ? "Test timeout of " + testInfo.timeout + "ms exceeded." : "Test ended.";
await context.close({ reason: closeReason });
const preserveVideo = captureVideo && shouldPreserveVideo(videoMode, testInfo);
if (preserveVideo) {
const { pagesWithVideo: pagesForVideo } = contexts.get(context);
const videos = pagesForVideo.map((p) => p.video()).filter((video2) => !!video2);
await Promise.all(videos.map(async (v) => {
try {
const savedPath = testInfo.outputPath(`video${counter ? "-" + counter : ""}.webm`);
++counter;
await v.saveAs(savedPath);
testInfo.attachments.push({ name: "video", path: savedPath, contentType: "video/webm" });
} catch (e) {
}
}));
}
};
const contextData = { close, pagesWithVideo: [] };
if (captureVideo)
context.on("page", (page) => contextData.pagesWithVideo.push(page));
contexts.set(context, contextData);
return { context, close };
});
await Promise.all([...contexts.values()].map((data) => data.close()));
}, { scope: "test", title: "context", box: true }],
_optionContextReuseMode: ["none", { scope: "worker", option: true, box: true }],
_optionConnectOptions: [void 0, { scope: "worker", option: true, box: true }],
reuseContext: [false, { scope: "worker", option: true, box: true }],
_reuseContext: [async ({ video, _optionContextReuseMode, reuseContext }, use) => {
let mode = _optionContextReuseMode;
if (process.env.PW_TEST_REUSE_CONTEXT || reuseContext)
mode = "when-possible";
const reuse = mode === "when-possible" && normalizeVideoMode(video) === "off";
await use(reuse);
}, { scope: "worker", title: "context", box: true }],
context: async ({ browser, video, _reuseContext, _contextFactory }, use, testInfoPublic) => {
const browserImpl = browser;
const testInfo = testInfoPublic;
const show = typeof video === "string" ? void 0 : video.show;
attachConnectedHeaderIfNeeded(testInfo, browserImpl);
if (!_reuseContext) {
const { context: context2, close } = await _contextFactory();
await installScreencastTitleUpdater(testInfo, context2, show?.test);
await use(context2);
await close();
return;
}
const context = await browserImpl._wrapApiCall(() => browserImpl._newContextForReuse(), { internal: true });
await installScreencastTitleUpdater(testInfo, context, show?.test);
await use(context);
const closeReason = testInfo.status === "timedOut" ? "Test timeout of " + testInfo.timeout + "ms exceeded." : "Test ended.";
await browserImpl._wrapApiCall(() => browserImpl._disconnectFromReusedContext(closeReason), { internal: true });
},
page: async ({ context, _reuseContext }, use) => {
if (!_reuseContext) {
await use(await context.newPage());
return;
}
let [page] = context.pages();
if (!page)
page = await context.newPage();
await use(page);
},
mount: async ({ page, baseURL }, use) => {
const callMount = (params) => page.evaluate(async (p) => {
const w = window;
if (typeof w.mount !== "function")
throw new Error("The gallery page does not define window.mount().");
await w.mount(p);
}, params, { exposeFunctions: true });
await use(async (storyId, props) => {
if (!baseURL)
throw new Error("mount() requires `baseURL` to point at the component gallery. Set it in your Playwright config.");
await page.goto(baseURL);
await callMount({ story: storyId, props });
return Object.assign(page.locator("#root"), {
// update() re-renders the same story with new props without navigating; if the gallery
// reuses its root/instance, the framework reconciles and component state is preserved.
update: (newProps) => callMount({ story: storyId, props: newProps }),
unmount: () => page.evaluate(async () => {
await window.unmount?.();
})
});
});
}
};
function normalizeVideoMode(video) {
if (!video)
return "off";
let videoMode = typeof video === "string" ? video : video.mode;
if (videoMode === "retry-with-video")
videoMode = "on-first-retry";
return videoMode;
}
function shouldCaptureVideo(videoMode, testInfo) {
return videoMode === "on" || videoMode === "retain-on-failure" || videoMode === "retain-on-failure-and-retries" || videoMode === "on-first-retry" && testInfo.retry === 1 || videoMode === "on-all-retries" && testInfo.retry > 0 || videoMode === "retain-on-first-failure" && testInfo.retry === 0;
}
function shouldPreserveVideo(videoMode, testInfo) {
const testFailed = testInfo.status !== testInfo.expectedStatus;
switch (videoMode) {
case "on":
case "on-first-retry":
case "on-all-retries":
return true;
case "retain-on-failure":
case "retain-on-first-failure":
return testFailed;
case "retain-on-failure-and-retries":
return testFailed || testInfo.retry > 0;
default:
return false;
}
}
function normalizeScreenshotMode(screenshot) {
if (!screenshot)
return "off";
return typeof screenshot === "string" ? screenshot : screenshot.mode;
}
function attachConnectedHeaderIfNeeded(testInfo, browser) {
const connectHeaders = browser?._connection.headers;
if (!connectHeaders)
return;
for (const header of connectHeaders) {
if (header.name !== "x-playwright-attachment")
continue;
const [name, value] = header.value.split("=");
if (!name || !value)
continue;
if (testInfo.attachments.some((attachment) => attachment.name === name))
continue;
testInfo.attachments.push({ name, contentType: "text/plain", body: Buffer.from(value) });
}
}
function resolveFileToConfig(file) {
const config2 = test.info().config.configFile;
if (!config2 || !file)
return file;
if (import_path.default.isAbsolute(file))
return file;
return import_path.default.resolve(import_path.default.dirname(config2), file);
}
function resolveClientCerticates(clientCertificates) {
for (const cert of clientCertificates) {
cert.certPath = resolveFileToConfig(cert.certPath);
cert.keyPath = resolveFileToConfig(cert.keyPath);
cert.pfxPath = resolveFileToConfig(cert.pfxPath);
}
return clientCertificates;
}
const kTracingStarted = /* @__PURE__ */ Symbol("kTracingStarted");
function connectOptionsFromEnv() {
const wsEndpoint = process.env.PW_TEST_CONNECT_WS_ENDPOINT;
if (!wsEndpoint)
return void 0;
const headers = process.env.PW_TEST_CONNECT_HEADERS ? JSON.parse(process.env.PW_TEST_CONNECT_HEADERS) : void 0;
return {
wsEndpoint,
headers,
exposeNetwork: process.env.PW_TEST_CONNECT_EXPOSE_NETWORK
};
}
class SnapshotRecorder {
constructor(_artifactsRecorder, _mode, _name, _contentType, _extension, _doSnapshot) {
this._artifactsRecorder = _artifactsRecorder;
this._mode = _mode;
this._name = _name;
this._contentType = _contentType;
this._extension = _extension;
this._doSnapshot = _doSnapshot;
this._ordinal = 0;
this._temporary = [];
}
fixOrdinal() {
this._ordinal = this.testInfo.attachments.filter((a) => a.name === this._name).length;
}
shouldCaptureUponFinish() {
return this._mode === "on" || this._mode === "only-on-failure" && this.testInfo._isFailure() || this._mode === "on-first-failure" && this.testInfo._isFailure() && this.testInfo.retry === 0;
}
async maybeCapture() {
if (!this.shouldCaptureUponFinish())
return;
await Promise.all(this._artifactsRecorder._playwright._allPages().map((page) => this._snapshotPage(page, false)));
}
async persistTemporary() {
if (this.shouldCaptureUponFinish()) {
await Promise.all(this._temporary.map(async (file) => {
try {
const path2 = this._createAttachmentPath();
await import_fs.default.promises.rename(file, path2);
this._attach(path2);
} catch {
}
}));
}
}
async captureTemporary(context) {
if (this._mode === "on" || this._mode === "only-on-failure" || this._mode === "on-first-failure" && this.testInfo.retry === 0)
await Promise.all(context.pages().map((page) => this._snapshotPage(page, true)));
}
_attach(screenshotPath) {
this.testInfo.attachments.push({ name: this._name, path: screenshotPath, contentType: this._contentType });
}
_createAttachmentPath() {
const testFailed = this.testInfo._isFailure();
const index = this._ordinal + 1;
++this._ordinal;
const path2 = this.testInfo.outputPath(`test-${testFailed ? "failed" : "finished"}-${index}${this._extension}`);
return path2;
}
_createTemporaryArtifact(...name) {
const file = import_path.default.join(this._artifactsRecorder._artifactsDir, ...name);
return file;
}
async _snapshotPage(page, temporary) {
if (page[this.testInfo._uniqueSymbol])
return;
page[this.testInfo._uniqueSymbol] = true;
try {
const path2 = temporary ? this._createTemporaryArtifact(createGuid() + this._extension) : this._createAttachmentPath();
await this._doSnapshot(page, path2);
if (temporary)
this._temporary.push(path2);
else
this._attach(path2);
} catch {
}
}
get testInfo() {
return this._artifactsRecorder._testInfo;
}
}
class ArtifactsRecorder {
constructor(playwright, artifactsDir, screenshot) {
this._playwright = playwright;
this._artifactsDir = artifactsDir;
const screenshotOptions = typeof screenshot === "string" ? void 0 : screenshot;
this._startedCollectingArtifacts = /* @__PURE__ */ Symbol("startedCollectingArtifacts");
this._screenshotRecorder = new SnapshotRecorder(this, normalizeScreenshotMode(screenshot), "screenshot", "image/png", ".png", async (page, path2) => {
await page._wrapApiCall(async () => {
await page.screenshot({ ...screenshotOptions, timeout: 5e3, path: path2, caret: "initial" });
}, { internal: true });
});
}
async willStartTest(testInfo) {
this._testInfo = testInfo;
testInfo._onDidFinishTestFunctionCallbacks.add(() => this.didFinishTestFunction());
this._screenshotRecorder.fixOrdinal();
await Promise.all(this._playwright._allContexts().map((context) => this.didCreateBrowserContext(context)));
const existingApiRequests = Array.from(this._playwright.request._contexts);
await Promise.all(existingApiRequests.map((c) => this.didCreateRequestContext(c)));
}
async didCreateBrowserContext(context) {
await this._startTraceChunkOnContextCreation(context, context.tracing);
await this._startTraceChunkOnContextCreation(context.request, context.request.tracing);
}
async willCloseBrowserContext(context) {
await this._stopTracing(context, context.tracing);
await this._screenshotRecorder.captureTemporary(context);
await this._takePageSnapshot(context);
}
async _takePageSnapshot(context) {
if (process.env.PLAYWRIGHT_NO_COPY_PROMPT)
return;
if (this._testInfo.errors.length === 0)
return;
if (this._testInfo.errors.some((e) => e.errorContext))
return;
if (this._pageSnapshot)
return;
const page = context.pages()[0];
if (!page)
return;
try {
await page._wrapApiCall(async () => {
this._pageSnapshot = await page.ariaSnapshot({ mode: "ai", timeout: 5e3 });
}, { internal: true });
} catch (error) {
debugLogger.log("error", `failed to capture aria snapshot: ${error}`);
}
}
async didCreateRequestContext(context) {
await this._startTraceChunkOnContextCreation(context, context.tracing);
}
async willCloseRequestContext(context) {
await this._stopTracing(context, context.tracing);
}
async didFinishTestFunction() {
await this._screenshotRecorder.maybeCapture();
}
async didFinishTest() {
await this.didFinishTestFunction();
const leftoverContexts = this._playwright._allContexts();
const leftoverApiRequests = Array.from(this._playwright.request._contexts);
await Promise.all(leftoverContexts.map(async (context2) => {
await this._stopTracing(context2.request, context2.request.tracing);
await this._stopTracing(context2, context2.tracing);
}).concat(leftoverApiRequests.map(async (context2) => {
await this._stopTracing(context2, context2.tracing);
})));
await this._screenshotRecorder.persistTemporary();
const context = leftoverContexts[0];
if (context)
await this._takePageSnapshot(context);
if (this._testInfo.errors.length > 0) {
const hasMatcherAriaSnapshot = this._testInfo.errors.some((e) => e.errorContext);
const errorContextContent = (0, import_errorContext.buildErrorContext)({
titlePath: this._testInfo.titlePath,
location: { file: this._testInfo.file, line: this._testInfo.line, column: this._testInfo.column },
errors: this._testInfo.errors,
pageSnapshot: hasMatcherAriaSnapshot ? void 0 : this._pageSnapshot
});
if (errorContextContent) {
const filePath = this._testInfo.outputPath("error-context.md");
await import_fs.default.promises.writeFile(filePath, errorContextContent, "utf8");
this._testInfo._attach({
name: "error-context",
contentType: "text/markdown",
path: filePath
}, void 0);
}
}
}
async _startTraceChunkOnContextCreation(channelOwner, tracing2) {
await channelOwner._wrapApiCall(async () => {
const options = this._testInfo._tracing.traceOptions();
if (options) {
const title = this._testInfo._tracing.traceTitle();
const name = this._testInfo._tracing.generateNextTraceRecordingName();
if (!tracing2[kTracingStarted]) {
await tracing2.start({ ...options, title, name });
tracing2[kTracingStarted] = true;
} else {
await tracing2.startChunk({ title, name });
}
} else {
if (tracing2[kTracingStarted]) {
tracing2[kTracingStarted] = false;
await tracing2.stop();
}
}
}, { internal: true });
}
async _stopTracing(channelOwner, tracing2) {
await channelOwner._wrapApiCall(async () => {
if (tracing2[this._startedCollectingArtifacts])
return;
tracing2[this._startedCollectingArtifacts] = true;
if (this._testInfo._tracing.traceOptions() && tracing2[kTracingStarted])
await tracing2.stopChunk({ path: this._testInfo._tracing.maybeGenerateNextTraceRecordingPath() });
}, { internal: true });
}
}
async function installScreencastTitleUpdater(testInfo, context, testAnnotate) {
if (!testAnnotate)
return;
const testTitle = testAnnotate.level === "file" ? [testInfo.titlePath[0]] : testInfo.titlePath;
const stepStack = [];
const overlays = /* @__PURE__ */ new Map();
const position = testAnnotate.position ?? "top-left";
const fontSize = testAnnotate.fontSize ?? 14;
const level = testAnnotate.level ?? "step";
const updateOverlay = async () => {
const parts = level === "step" ? [...testTitle, ...stepStack] : testTitle;
const html = createTestOverlay(parts, position, fontSize);
for (const page of context.pages()) {
await overlays.get(page)?.dispose();
overlays.delete(page);
const disposable = await page.screencast.showOverlay(html);
overlays.set(page, disposable);
}
};
testInfo._onUserStepBegin = async (title) => {
stepStack.push(title);
await updateOverlay();
};
testInfo._onUserStepEnd = async () => {
stepStack.pop();
await updateOverlay();
};
context.on("page", async () => {
void updateOverlay();
});
await updateOverlay();
}
function createTestOverlay(parts, position, fontSize) {
const positionStyles = {
"top-left": "top: 6px; left: 6px;",
"top": "top: 6px; left: 50%; transform: translateX(-50%);",
"top-right": "top: 6px; right: 6px;",
"bottom-left": "bottom: 6px; left: 6px;",
"bottom": "bottom: 6px; left: 50%; transform: translateX(-50%);",
"bottom-right": "bottom: 6px; right: 6px;"
};
const posStyle = positionStyles[position] ?? positionStyles["top-left"];
return `<div style="white-space: nowrap; font-size: ${fontSize}px; padding: 3px 6px; background: rgba(0,0,0,0.5); color: white; border-radius: 4px; position: absolute; ${posStyle}">
${parts.map((p) => `<div>${escapeHTML(p)}</div>`).join("")}
</div>`;
}
function renderTitle(type, method, params, title) {
return renderTitleForCall({ title, type, method, params });
}
function renderSubtitle(type, method, params) {
const subtitle = renderSubtitleForCall({ type, method, params });
return subtitle === void 0 ? void 0 : truncateParam(subtitle);
}
function tracing() {
return test.info()._tracing;
}
const test = _utilityTest.extend(playwrightFixtures);
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
_baseTest,
_utilityTest,
defineConfig,
expect,
mergeExpects,
mergeTests,
test
});
+9
View File
@@ -0,0 +1,9 @@
# packages/playwright/lib/isomorphic.js
# total: 8.0 KB
## Inlined (3)
1.3 KB packages/playwright/src/isomorphic/events.ts
0.3 KB packages/playwright/src/isomorphic/index.ts
5.3 KB packages/playwright/src/isomorphic/testServerConnection.ts
## External (0)
+34
View File
@@ -0,0 +1,34 @@
"use strict";
// packages/playwright/src/loader/loaderProcessEntry.ts
var import_common2 = require("../common");
// packages/playwright/src/loader/loaderMain.ts
var import_common = require("../common");
var LoaderMain = class extends import_common.ProcessRunner {
constructor(serializedConfig) {
super();
this._poolBuilder = import_common.poolBuilder.PoolBuilder.createForLoader();
this._serializedConfig = serializedConfig;
}
_config() {
if (!this._configPromise)
this._configPromise = import_common.configLoader.deserializeConfig(this._serializedConfig);
return this._configPromise;
}
async loadTestFile(params) {
const testErrors = [];
const config = await this._config();
const fileSuite = await import_common.testLoader.loadTestFile(params.file, config, testErrors);
this._poolBuilder.buildPools(fileSuite);
return { fileSuite: fileSuite._deepSerialize(), testErrors };
}
async getCompilationCacheFromLoader() {
await import_common.transform.incorporateCompilationCache();
return import_common.cc.serializeCompilationCache();
}
};
var create = (config) => new LoaderMain(config);
// packages/playwright/src/loader/loaderProcessEntry.ts
(0, import_common2.startProcessRunner)(create);
+9
View File
@@ -0,0 +1,9 @@
# packages/playwright/lib/loader/loaderProcessEntry.js
# total: 1.2 KB
## Inlined (2)
1.0 KB packages/playwright/src/loader/loaderMain.ts
0.1 KB packages/playwright/src/loader/loaderProcessEntry.ts
## External (1)
../common
+135
View File
@@ -0,0 +1,135 @@
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var browserBackend_exports = {};
__export(browserBackend_exports, {
createCustomMessageHandler: () => createCustomMessageHandler,
runDaemonForContext: () => runDaemonForContext
});
module.exports = __toCommonJS(browserBackend_exports);
var import_crypto = __toESM(require("crypto"));
const { stripAnsiEscapes } = require("playwright-core/lib/coreBundle").iso;
function createCustomMessageHandler(testInfo, context) {
let backend;
const config = { capabilities: ["testing"] };
let tools;
context.once("close", () => {
void backend?.dispose();
backend = void 0;
});
return async (data) => {
if (!tools)
({ tools } = require("playwright-core/lib/coreBundle"));
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(tools, testInfo, context);
return { initialize: { pausedMessage } };
}
if (data.callTool) {
if (!backend)
throw new Error("MCP backend is not initialized");
return { callTool: await backend.callTool(data.callTool.name, data.callTool.arguments) };
}
if (data.close) {
await backend?.dispose();
backend = void 0;
return { close: {} };
}
throw new Error("Unknown MCP request");
};
}
async function generatePausedMessage(tools, testInfo, context) {
const lines = [];
if (testInfo.errors.length) {
lines.push(`### Paused on error:`);
for (const error of testInfo.errors)
lines.push(stripAnsiEscapes(error.message || ""));
} else {
lines.push(`### Paused at end of test. ready for interaction`);
}
for (let i = 0; i < context.pages().length; i++) {
const page = context.pages()[i];
const stateSuffix = context.pages().length > 1 ? i + 1 + " of " + context.pages().length : "state";
lines.push(
"",
`### Page ${stateSuffix}`,
`- Page URL: ${page.url()}`,
`- Page Title: ${await page.title()}`.trim()
);
let console2 = testInfo.errors.length ? await tools.Tab.collectConsoleMessages(page) : [];
console2 = console2.filter((msg) => msg.type === "error");
if (console2.length) {
lines.push("- Console Messages:");
for (const message of console2)
lines.push(` - ${message.toString()}`);
}
lines.push(
`- Page Snapshot:`,
"```yaml",
await page.ariaSnapshot({ mode: "ai" }),
"```"
);
}
lines.push("");
if (testInfo.errors.length)
lines.push(`### Task`, `Try recovering from the error prior to continuing`);
return lines.join("\n");
}
const kDaemonSymbol = /* @__PURE__ */ Symbol("daemon");
const kSessionNameSymbol = /* @__PURE__ */ Symbol("sessionName");
async function runDaemonForContext(testInfo, context) {
if (testInfo._configInternal.configCLIOverrides.debug !== "cli")
return false;
const browser = context.browser();
let sessionName = browser[kSessionNameSymbol];
if (!sessionName) {
sessionName = `tw-${import_crypto.default.randomBytes(3).toString("hex")}`;
await browser.bind(sessionName, { workspaceDir: testInfo.project.testDir });
browser[kSessionNameSymbol] = sessionName;
}
if (testInfo[kDaemonSymbol])
return false;
testInfo[kDaemonSymbol] = true;
console.log([
`### The test is currently paused at the start`,
``,
`### Debugging Instructions`,
`- Run "playwright-cli attach ${sessionName}" to attach to this test`
].join("\n"));
await context.debugger.requestPause();
return true;
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
createCustomMessageHandler,
runDaemonForContext
});
+122
View File
@@ -0,0 +1,122 @@
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var generatorTools_exports = {};
__export(generatorTools_exports, {
generatorReadLog: () => generatorReadLog,
generatorWriteTest: () => generatorWriteTest,
setupPage: () => setupPage
});
module.exports = __toCommonJS(generatorTools_exports);
var import_fs = __toESM(require("fs"));
var import_path = __toESM(require("path"));
var import_testTool = require("./testTool");
var import_testContext = require("./testContext");
const z = require("playwright-core/lib/utilsBundle").z;
const { isPathInside, resolveWithinRoot } = require("playwright-core/lib/coreBundle").utils;
const setupPage = (0, import_testTool.defineTestTool)({
schema: {
name: "generator_setup_page",
title: "Setup generator page",
description: "Setup the page for test.",
inputSchema: z.object({
plan: z.string().describe("The plan for the test. This should be the actual test plan with all the steps."),
project: z.string().optional().describe('Project to use for setup. For example: "chromium", if no project is provided uses the first project in the config.'),
seedFile: z.string().optional().describe('A seed file contains a single test that is used to setup the page for testing, for example: "tests/seed.spec.ts". If no seed file is provided, a default seed file is created.')
}),
type: "readOnly"
},
handle: async (context, params, signal) => {
const seed = await context.getOrCreateSeedFile(params.seedFile, params.project);
context.generatorJournal = new import_testContext.GeneratorJournal(context.rootPath, params.plan, seed);
const { output, status } = await context.runSeedTest(seed.file, seed.projectName, signal);
return { content: [{ type: "text", text: output }], isError: status !== "paused" };
}
});
const generatorReadLog = (0, import_testTool.defineTestTool)({
schema: {
name: "generator_read_log",
title: "Retrieve test log",
description: "Retrieve the performed test log",
inputSchema: z.object({}),
type: "readOnly"
},
handle: async (context) => {
if (!context.generatorJournal)
throw new Error(`Please setup page using "${setupPage.schema.name}" first.`);
const result = context.generatorJournal.journal();
return { content: [{
type: "text",
text: result
}] };
}
});
const generatorWriteTest = (0, import_testTool.defineTestTool)({
schema: {
name: "generator_write_test",
title: "Write test",
description: "Write the generated test to the test file",
inputSchema: z.object({
fileName: z.string().describe("The file to write the test to"),
code: z.string().describe("The generated test code")
}),
type: "readOnly"
},
handle: async (context, params) => {
if (!context.generatorJournal)
throw new Error(`Please setup page using "${setupPage.schema.name}" first.`);
const testRunner = context.existingTestRunner();
if (!testRunner)
throw new Error("No test runner found, please setup page and perform actions first.");
const config = await testRunner.loadConfig();
const resolvedFile = resolveWithinRoot(context.rootPath, params.fileName);
const dirs = [];
for (const project of config.projects) {
const projectTestDir = project.project.testDir;
if (resolvedFile && isPathInside(projectTestDir, resolvedFile)) {
await import_fs.default.promises.mkdir(import_path.default.dirname(resolvedFile), { recursive: true });
await import_fs.default.promises.writeFile(resolvedFile, params.code);
return {
content: [{
type: "text",
text: `### Result
Test written to ${params.fileName}`
}]
};
}
dirs.push(import_path.default.relative(context.rootPath, projectTestDir).replace(/\\/g, "/"));
}
throw new Error(`Test file did not match any of the test dirs: ${dirs.join(", ")}`);
}
});
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
generatorReadLog,
generatorWriteTest,
setupPage
});
+150
View File
@@ -0,0 +1,150 @@
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var plannerTools_exports = {};
__export(plannerTools_exports, {
saveTestPlan: () => saveTestPlan,
setupPage: () => setupPage,
submitTestPlan: () => submitTestPlan
});
module.exports = __toCommonJS(plannerTools_exports);
var import_fs = __toESM(require("fs"));
var import_path = __toESM(require("path"));
var import_testTool = require("./testTool");
const z = require("playwright-core/lib/utilsBundle").z;
const { resolveWithinRoot } = require("playwright-core/lib/coreBundle").utils;
const setupPage = (0, import_testTool.defineTestTool)({
schema: {
name: "planner_setup_page",
title: "Setup planner page",
description: "Setup the page for test planning",
inputSchema: z.object({
project: z.string().optional().describe('Project to use for setup. For example: "chromium", if no project is provided uses the first project in the config.'),
seedFile: z.string().optional().describe('A seed file contains a single test that is used to setup the page for testing, for example: "tests/seed.spec.ts". If no seed file is provided, a default seed file is created.')
}),
type: "readOnly"
},
handle: async (context, params, signal) => {
const seed = await context.getOrCreateSeedFile(params.seedFile, params.project);
const { output, status } = await context.runSeedTest(seed.file, seed.projectName, signal);
return { content: [{ type: "text", text: output }], isError: status !== "paused" };
}
});
const planSchema = z.object({
overview: z.string().describe("A brief overview of the application to be tested"),
suites: z.array(z.object({
name: z.string().describe("The name of the suite"),
seedFile: z.string().describe("A seed file that was used to setup the page for testing."),
tests: z.array(z.object({
name: z.string().describe("The name of the test"),
file: z.string().describe('The file the test should be saved to, for example: "tests/<suite-name>/<test-name>.spec.ts".'),
steps: z.array(z.object({
perform: z.string().optional().describe(`Action to perform. For example: 'Click on the "Submit" button'.`),
expect: z.string().array().describe(`Expected result of the action where appropriate. For example: 'The page should show the "Thank you for your submission" message'`)
}))
}))
}))
});
const submitTestPlan = (0, import_testTool.defineTestTool)({
schema: {
name: "planner_submit_plan",
title: "Submit test plan",
description: "Submit the test plan to the test planner",
inputSchema: planSchema,
type: "readOnly"
},
handle: async (context, params) => {
return {
content: [{
type: "text",
text: JSON.stringify(params, null, 2)
}]
};
}
});
const saveTestPlan = (0, import_testTool.defineTestTool)({
schema: {
name: "planner_save_plan",
title: "Save test plan as markdown file",
description: "Save the test plan as a markdown file",
inputSchema: planSchema.extend({
name: z.string().describe('The name of the test plan, for example: "Test Plan".'),
fileName: z.string().describe('The file to save the test plan to, for example: "spec/test.plan.md". Relative to the workspace root.')
}),
type: "readOnly"
},
handle: async (context, params) => {
const lines = [];
lines.push(`# ${params.name}`);
lines.push(``);
lines.push(`## Application Overview`);
lines.push(``);
lines.push(params.overview);
lines.push(``);
lines.push(`## Test Scenarios`);
for (let i = 0; i < params.suites.length; i++) {
lines.push(``);
const suite = params.suites[i];
lines.push(`### ${i + 1}. ${suite.name}`);
lines.push(``);
lines.push(`**Seed:** \`${suite.seedFile}\``);
for (let j = 0; j < suite.tests.length; j++) {
lines.push(``);
const test = suite.tests[j];
lines.push(`#### ${i + 1}.${j + 1}. ${test.name}`);
lines.push(``);
lines.push(`**File:** \`${test.file}\``);
lines.push(``);
lines.push(`**Steps:**`);
for (let k = 0; k < test.steps.length; k++) {
lines.push(` ${k + 1}. ${test.steps[k].perform ?? "-"}`);
for (const expect of test.steps[k].expect)
lines.push(` - expect: ${expect}`);
}
}
}
lines.push(``);
const resolvedFile = resolveWithinRoot(context.rootPath, params.fileName);
if (!resolvedFile)
throw new Error(`Plan file name must be a relative path inside the workspace: ${params.fileName}`);
await import_fs.default.promises.mkdir(import_path.default.dirname(resolvedFile), { recursive: true });
await import_fs.default.promises.writeFile(resolvedFile, lines.join("\n"));
return {
content: [{
type: "text",
text: `Test plan saved to ${params.fileName}`
}]
};
}
});
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
saveTestPlan,
setupPage,
submitTestPlan
});
+44
View File
@@ -0,0 +1,44 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var streams_exports = {};
__export(streams_exports, {
StringWriteStream: () => StringWriteStream
});
module.exports = __toCommonJS(streams_exports);
var import_stream = require("stream");
var import_util = require("../../util");
class StringWriteStream extends import_stream.Writable {
constructor(output, stdio) {
super();
this._output = output;
this._prefix = stdio === "stdout" ? "" : "[err] ";
}
_write(chunk, encoding, callback) {
let text = (0, import_util.stripAnsiEscapes)(chunk.toString());
if (text.endsWith("\n"))
text = text.slice(0, -1);
if (text)
this._output.push(this._prefix + text);
callback();
}
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
StringWriteStream
});
+306
View File
@@ -0,0 +1,306 @@
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var testContext_exports = {};
__export(testContext_exports, {
GeneratorJournal: () => GeneratorJournal,
TestContext: () => TestContext,
createScreen: () => createScreen
});
module.exports = __toCommonJS(testContext_exports);
var import_fs = __toESM(require("fs"));
var import_os = __toESM(require("os"));
var import_path = __toESM(require("path"));
var import_coreBundle = require("playwright-core/lib/coreBundle");
var import_runner = require("../../runner");
var import_streams = require("./streams");
var import_util = require("../../util");
var import_seed = require("./seed");
var import_common = require("../../common");
const debug = require("playwright-core/lib/utilsBundle").debug;
const { noColors } = require("playwright-core/lib/coreBundle").iso;
const { ManualPromise, signalToPromise } = require("playwright-core/lib/coreBundle").iso;
const { escapeRegExp } = require("playwright-core/lib/coreBundle").iso;
const { toPosixPath } = require("playwright-core/lib/coreBundle").utils;
class GeneratorJournal {
constructor(rootPath, plan, seed) {
this._rootPath = rootPath;
this._plan = plan;
this._seed = seed;
this._steps = [];
}
logStep(title, code) {
if (title)
this._steps.push({ title, code });
}
journal() {
const result = [];
result.push(`# Plan`);
result.push(this._plan);
result.push(`# Seed file: ${toPosixPath(import_path.default.relative(this._rootPath, this._seed.file))}`);
result.push("```ts");
result.push(this._seed.content);
result.push("```");
result.push(`# Steps`);
result.push(this._steps.map((step) => `### ${step.title}
\`\`\`ts
${step.code}
\`\`\``).join("\n\n"));
result.push(bestPracticesMarkdown);
return result.join("\n\n");
}
}
class TestContext {
constructor(clientInfo, configPath, options) {
this._testOpQueue = Promise.resolve();
this._clientInfo = clientInfo;
this._configLocation = import_common.configLoader.resolveConfigLocation(configPath || clientInfo.cwd);
this.rootPath = clientInfo.cwd || this._configLocation.configDir;
if (options?.headless !== void 0)
this.computedHeaded = !options.headless;
else
this.computedHeaded = !process.env.CI && !(import_os.default.platform() === "linux" && !process.env.DISPLAY);
}
async _enqueue(fn) {
const next = this._testOpQueue.then(fn);
this._testOpQueue = next.then(() => {
}, () => {
});
return await next;
}
existingTestRunner() {
return this._testRunnerAndScreen?.testRunner;
}
async _cleanupTestRunner() {
if (!this._testRunnerAndScreen)
return;
await this._testRunnerAndScreen.testRunner.stopTests();
this._testRunnerAndScreen.claimStdio();
try {
await this._testRunnerAndScreen.testRunner.runGlobalTeardown();
} finally {
this._testRunnerAndScreen.releaseStdio();
this._testRunnerAndScreen = void 0;
}
}
async createTestRunner() {
await this._cleanupTestRunner();
const runner = new import_runner.testRunner.TestRunner(this._configLocation, {});
await runner.initialize({});
const testPaused = new ManualPromise();
const testRunnerAndScreen = {
...createScreen(),
testRunner: runner,
waitForTestPaused: () => testPaused
};
this._testRunnerAndScreen = testRunnerAndScreen;
runner.on(import_runner.testRunner.TestRunnerEvent.TestPaused, (params) => {
testRunnerAndScreen.sendMessageToPausedTest = params.sendMessage;
testPaused.resolve();
});
return testRunnerAndScreen;
}
async getOrCreateSeedFile(seedFile, projectName) {
const configDir = this._configLocation.configDir;
const { testRunner: runner } = await this.createTestRunner();
const config = await runner.loadConfig();
const project = (0, import_seed.seedProject)(config, projectName);
if (!seedFile) {
seedFile = await (0, import_seed.ensureSeedFile)(project);
} else {
const candidateFiles = [];
const testDir = project.project.testDir;
candidateFiles.push(import_path.default.resolve(testDir, seedFile));
candidateFiles.push(import_path.default.resolve(configDir, seedFile));
candidateFiles.push(import_path.default.resolve(this.rootPath, seedFile));
let resolvedSeedFile;
for (const candidateFile of candidateFiles) {
if (await (0, import_util.fileExistsAsync)(candidateFile)) {
resolvedSeedFile = candidateFile;
break;
}
}
if (!resolvedSeedFile)
throw new Error("seed test not found.");
seedFile = resolvedSeedFile;
}
const seedFileContent = await import_fs.default.promises.readFile(seedFile, "utf8");
return {
file: seedFile,
content: seedFileContent,
projectName: project.project.name
};
}
async runSeedTest(seedFile, projectName, signal) {
const result = await this.runTestsWithGlobalSetupAndPossiblePause({
headed: this.computedHeaded,
locations: ["/" + escapeRegExp(seedFile) + "/"],
projects: [projectName],
timeout: 0,
workers: 1,
pauseAtEnd: true,
disableConfigReporters: true,
failOnLoadErrors: true
}, signal);
if (result.status === "passed")
result.output += "\nError: seed test not found.";
else if (result.status !== "paused")
result.output += "\nError while running the seed test.";
return result;
}
async runTestsWithGlobalSetupAndPossiblePause(params, signal) {
return this._enqueue(() => this._runTestsImpl(params, signal));
}
async _runTestsImpl(params, signal) {
const configDir = this._configLocation.configDir;
const testRunnerAndScreen = await this.createTestRunner();
const { testRunner: runner, screen, claimStdio, releaseStdio } = testRunnerAndScreen;
claimStdio();
try {
const setupReporter = new MCPListReporter({ configDir, screen, includeTestId: true });
const { status: status2 } = await runner.runGlobalSetup([setupReporter]);
if (status2 !== "passed")
return { output: testRunnerAndScreen.output.join("\n"), status: status2 };
} finally {
releaseStdio();
}
let status = "passed";
const cleanup = async () => {
claimStdio();
try {
const result = await runner.runGlobalTeardown();
if (status === "passed")
status = result.status;
} finally {
releaseStdio();
}
};
const abort = signal ? signalToPromise(signal) : void 0;
const abortPromise = abort ? abort.promise.then(() => "interrupted") : new Promise(() => {
});
try {
const reporter = new MCPListReporter({ configDir, screen, includeTestId: true });
status = await Promise.race([
runner.runTests(reporter, params).then((result) => result.status),
testRunnerAndScreen.waitForTestPaused().then(() => "paused"),
abortPromise
]);
if (status === "interrupted") {
await runner.stopTests();
await cleanup();
return { output: testRunnerAndScreen.output.join("\n"), status };
}
if (status === "paused") {
const response = await testRunnerAndScreen.sendMessageToPausedTest({ request: { initialize: { clientInfo: this._clientInfo } } });
if (response.error)
throw new Error(response.error.message);
testRunnerAndScreen.output.push(response.response.initialize.pausedMessage);
return { output: testRunnerAndScreen.output.join("\n"), status };
}
} catch (e) {
status = "failed";
testRunnerAndScreen.output.push(String(e));
await cleanup();
return { output: testRunnerAndScreen.output.join("\n"), status };
} finally {
abort?.dispose();
}
await cleanup();
return { output: testRunnerAndScreen.output.join("\n"), status };
}
async close() {
await this._enqueue(() => this._cleanupTestRunner()).catch((e) => debug("pw:mcp:error")(e));
}
async sendMessageToPausedTest(request) {
const sendMessage = this._testRunnerAndScreen?.sendMessageToPausedTest;
if (!sendMessage)
throw new Error("Must setup test before interacting with the page");
const result = await sendMessage({ request });
if (result.error)
throw new Error(result.error.message);
if (typeof request?.callTool?.arguments?.["intent"] === "string") {
const response = import_coreBundle.tools.parseResponse(result.response.callTool);
if (response && !response.isError && response.code)
this.generatorJournal?.logStep(request.callTool.arguments["intent"], response.code);
}
return result.response;
}
}
function createScreen() {
const output = [];
const stdout = new import_streams.StringWriteStream(output, "stdout");
const stderr = new import_streams.StringWriteStream(output, "stderr");
const screen = {
...import_runner.base.terminalScreen,
isTTY: false,
colors: noColors,
stdout,
stderr
};
const originalStdoutWrite = process.stdout.write;
const originalStderrWrite = process.stderr.write;
const claimStdio = () => {
process.stdout.write = (chunk) => {
stdout.write(chunk);
return true;
};
process.stderr.write = (chunk) => {
stderr.write(chunk);
return true;
};
};
const releaseStdio = () => {
process.stdout.write = originalStdoutWrite;
process.stderr.write = originalStderrWrite;
};
return { screen, claimStdio, releaseStdio, output };
}
const bestPracticesMarkdown = `
# Best practices
- Do not improvise, do not add directives that were not asked for
- Use clear, descriptive assertions to validate the expected behavior
- Use reliable locators from this log
- Use local variables for locators that are used multiple times
- Use Playwright waiting assertions and best practices from this log
- NEVER! use page.waitForLoadState()
- NEVER! use page.waitForNavigation()
- NEVER! use page.waitForTimeout()
- NEVER! use page.evaluate()
`;
class MCPListReporter extends import_runner.ListReporter {
async onTestPaused() {
await new Promise(() => {
});
}
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
GeneratorJournal,
TestContext,
createScreen
});
+30
View File
@@ -0,0 +1,30 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var testTool_exports = {};
__export(testTool_exports, {
defineTestTool: () => defineTestTool
});
module.exports = __toCommonJS(testTool_exports);
function defineTestTool(tool) {
return tool;
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
defineTestTool
});
+98
View File
@@ -0,0 +1,98 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var testTools_exports = {};
__export(testTools_exports, {
debugTest: () => debugTest,
listTests: () => listTests,
runTests: () => runTests
});
module.exports = __toCommonJS(testTools_exports);
var import_runner = require("../../runner");
var import_testTool = require("./testTool");
const z = require("playwright-core/lib/utilsBundle").z;
const listTests = (0, import_testTool.defineTestTool)({
schema: {
name: "test_list",
title: "List tests",
description: "List tests",
inputSchema: z.object({}),
type: "readOnly"
},
handle: async (context) => {
const { testRunner, screen, output } = await context.createTestRunner();
const reporter = new import_runner.ListModeReporter({ screen, includeTestId: true });
await testRunner.listTests(reporter, {});
return { content: output.map((text) => ({ type: "text", text })) };
}
});
const runTests = (0, import_testTool.defineTestTool)({
schema: {
name: "test_run",
title: "Run tests",
description: "Run tests",
inputSchema: z.object({
locations: z.array(z.string()).optional().describe('Folder, file or location to run: "test/e2e" or "test/e2e/file.spec.ts" or "test/e2e/file.spec.ts:20"'),
projects: z.array(z.string()).optional().describe('Projects to run, projects from playwright.config.ts, by default runs all projects. Running with "chromium" is a good start')
}),
type: "readOnly"
},
handle: async (context, params, signal) => {
const { output } = await context.runTestsWithGlobalSetupAndPossiblePause({
locations: params.locations ?? [],
projects: params.projects,
disableConfigReporters: true
}, signal);
return { content: [{ type: "text", text: output }] };
}
});
const debugTest = (0, import_testTool.defineTestTool)({
schema: {
name: "test_debug",
title: "Debug single test",
description: "Debug single test",
inputSchema: z.object({
test: z.object({
id: z.string().describe("Test ID to debug."),
title: z.string().describe("Human readable test title for granting permission to debug the test.")
})
}),
type: "readOnly"
},
handle: async (context, params, signal) => {
const { output, status } = await context.runTestsWithGlobalSetupAndPossiblePause({
headed: context.computedHeaded,
locations: [],
// we can make this faster by passing the test's location, so we don't need to scan all tests to find the ID
testIds: [params.test.id],
// For automatic recovery
timeout: 0,
workers: 1,
pauseOnError: true,
disableConfigReporters: true,
actionTimeout: 5e3
}, signal);
return { content: [{ type: "text", text: output }], isError: status !== "paused" && status !== "passed" };
}
});
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
debugTest,
listTests,
runTests
});
+47
View File
@@ -0,0 +1,47 @@
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var package_exports = {};
__export(package_exports, {
libPath: () => libPath,
packageJSON: () => packageJSON,
packageRoot: () => packageRoot
});
module.exports = __toCommonJS(package_exports);
var import_path = __toESM(require("path"));
const packageRoot = import_path.default.join(__dirname, "..");
const packageJSON = require(import_path.default.join(packageRoot, "package.json"));
function libPath(...parts) {
return import_path.default.join(packageRoot, "lib", ...parts);
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
libPath,
packageJSON,
packageRoot
});
+241
View File
@@ -0,0 +1,241 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var program_exports = {};
__export(program_exports, {
program: () => program
});
module.exports = __toCommonJS(program_exports);
var import_bootstrap = require("playwright-core/lib/bootstrap");
var import_coreBundle = require("playwright-core/lib/coreBundle");
var import_common = require("./common");
var import_testActions = require("./cli/testActions");
var import_reportActions = require("./cli/reportActions");
var import_testBackend = require("./mcp/test/testBackend");
var import_generateAgents = require("./agents/generateAgents");
var import_package = require("./package");
const { program } = require("playwright-core/lib/utilsBundle");
const { setBoxedStackPrefixes } = require("playwright-core/lib/coreBundle").utils;
const { gracefullyProcessExitDoNotHang } = require("playwright-core/lib/coreBundle").utils;
setBoxedStackPrefixes([import_package.packageRoot]);
import_coreBundle.libCli.decorateProgram(program);
function addTestCommand(program2) {
const command = program2.command("test [test-filter...]");
command.description("run tests with Playwright Test");
const options = testOptions.sort((a, b) => a[0].replace(/-/g, "").localeCompare(b[0].replace(/-/g, "")));
options.forEach(([name, { description, choices, preset }]) => {
const option = command.createOption(name, description);
if (choices)
option.choices(choices);
if (preset)
option.preset(preset);
command.addOption(option);
return command;
});
command.action(async (args, opts) => {
const dashDashIndex = process.argv.indexOf("--");
const postDashCount = dashDashIndex >= 0 ? process.argv.length - 1 - dashDashIndex : 0;
const testFilters = args.slice(0, args.length - postDashCount);
try {
await (0, import_testActions.runTests)(testFilters, opts);
} catch (e) {
console.error(e);
gracefullyProcessExitDoNotHang(1);
}
});
command.addHelpText("afterAll", `
Arguments [test-filter...]:
Pass arguments to filter test files. Each argument is treated as a regular expression. Matching is performed against the absolute file paths.
Examples:
$ npx playwright test my.spec.ts
$ npx playwright test some.spec.ts:42
$ npx playwright test --headed
$ npx playwright test --project=webkit`);
}
function addClearCacheCommand(program2) {
const command = program2.command("clear-cache");
command.description("clears build and test caches");
command.option("-c, --config <file>", `Configuration file, or a test directory with optional "playwright.config.{m,c}?{js,ts}"`);
command.action(async (opts) => {
await (0, import_testActions.clearCache)(opts);
});
}
function addTestServerCommand(program2) {
const command = program2.command("test-server", { hidden: true });
command.description("start test server");
command.option("-c, --config <file>", `Configuration file, or a test directory with optional "playwright.config.{m,c}?{js,ts}"`);
command.option("--host <host>", "Host to start the server on", "localhost");
command.option("--port <port>", "Port to start the server on", "0");
command.action(async (opts) => {
await (0, import_testActions.runTestServerAction)(opts);
});
}
function addShowReportCommand(program2) {
const command = program2.command("show-report [report]");
command.description("show HTML report");
command.action(async (report, options) => {
await (0, import_reportActions.showReport)(report, options.host, +options.port);
});
command.option("--host <host>", "Host to serve report on", "localhost");
command.option("--port <port>", "Port to serve report on", "9323");
command.addHelpText("afterAll", `
Arguments [report]:
When specified, opens given report, otherwise opens last generated report.
Accepts a directory or a .zip archive whose top-level entry is "index.html" (e.g. one downloaded from a CI artifact).
Examples:
$ npx playwright show-report
$ npx playwright show-report playwright-report
$ npx playwright show-report playwright-report.zip`);
}
function addMergeReportsCommand(program2) {
const command = program2.command("merge-reports [dir]");
command.description("merge multiple blob reports (for sharded tests) into a single report");
command.action(async (dir, options) => {
try {
await (0, import_reportActions.mergeReports)(dir, options);
} catch (e) {
console.error(e);
gracefullyProcessExitDoNotHang(1);
}
});
command.option("-c, --config <file>", `Configuration file. Can be used to specify additional configuration for the output report.`);
command.option("--reporter <reporter>", `Reporter to use, comma-separated, can be ${import_common.builtInReporters.map((name) => `"${name}"`).join(", ")} (default: "${import_common.config.defaultReporter}")`);
command.addHelpText("afterAll", `
Arguments [dir]:
Directory containing blob reports.
Examples:
$ npx playwright merge-reports playwright-report`);
}
function addTestMCPServerCommand(program2) {
const command = program2.command("run-test-mcp-server", { hidden: true });
command.description("Interact with the test runner over MCP");
command.option("--headless", "run browser in headless mode, headed by default");
command.option("-c, --config <file>", `Configuration file, or a test directory with optional "playwright.config.{m,c}?{js,ts}"`);
command.option("--host <host>", "host to bind server to. Default is localhost. Use 0.0.0.0 to bind to all interfaces.");
command.option("--port <port>", "port to listen on for SSE transport.");
command.action(async (options) => {
import_coreBundle.tools.setupExitWatchdog();
const factory = {
name: "Playwright Test Runner",
nameInConfig: "playwright-test-runner",
version: import_package.packageJSON.version,
toolSchemas: import_testBackend.testServerBackendTools.map((tool) => tool.schema),
create: async () => new import_testBackend.TestServerBackend(options.config, { muteConsole: options.port === void 0, headless: options.headless })
};
await import_coreBundle.tools.start(factory, { port: options.port === void 0 ? void 0 : +options.port, host: options.host });
});
}
function addInitAgentsCommand(program2) {
const command = program2.command("init-agents");
command.description("Initialize repository agents");
const option = command.createOption("--loop <loop>", "Agentic loop provider");
option.choices(["claude", "codex", "copilot", "opencode", "vscode", "vscode-legacy"]);
command.addOption(option);
command.option("-c, --config <file>", `Configuration file to find a project to use for seed test`);
command.option("--project <project>", "Project to use for seed test");
command.option("--prompts", "Whether to include prompts in the agent initialization");
command.action(async (opts) => {
const loadedConfig = await import_common.configLoader.loadConfigFromFile(opts.config);
if (opts.loop === "opencode") {
await import_generateAgents.OpencodeGenerator.init(loadedConfig, opts.project, opts.prompts);
} else if (opts.loop === "vscode-legacy") {
await import_generateAgents.VSCodeGenerator.init(loadedConfig, opts.project);
} else if (opts.loop === "claude") {
await import_generateAgents.ClaudeGenerator.init(loadedConfig, opts.project, opts.prompts);
} else if (opts.loop === "codex") {
await import_generateAgents.CodexGenerator.init(loadedConfig, opts.project, opts.prompts);
} else {
await import_generateAgents.CopilotGenerator.init(loadedConfig, opts.project, opts.prompts);
return;
}
});
}
function addInitSkillsCommand(program2) {
const command = program2.command("init-skills");
command.description("Install Playwright agent skills");
const option = command.createOption("--loop <loop>", "Agentic loop provider");
option.choices(["claude", "agents"]);
option.default("claude");
command.addOption(option);
command.action(async (opts) => {
try {
await import_coreBundle.tools.installSkills(import_coreBundle.tools.allSkills, opts.loop);
} catch (e) {
console.error(e);
gracefullyProcessExitDoNotHang(1);
}
});
}
const kTraceModes = ["on", "off", "on-first-retry", "on-all-retries", "retain-on-failure", "retain-on-first-failure", "retain-on-failure-and-retries"];
const testOptions = [
["--add-reporter <reporter>", { description: `Reporter to add on top of the configured reporters, comma-separated, can be ${import_common.builtInReporters.map((name) => `"${name}"`).join(", ")} or a path to a reporter module` }],
/* deprecated */
["--browser <browser>", { description: `Browser to use for tests, one of "all", "chromium", "firefox" or "webkit" (default: "chromium")` }],
["-c, --config <file>", { description: `Configuration file, or a test directory with optional "playwright.config.{m,c}?{js,ts}"` }],
["--debug [mode]", { description: `Run tests with Playwright Inspector. Shortcut for "PWDEBUG=1" environment variable and "--timeout=0 --max-failures=1 --headed --workers=1" options`, choices: ["inspector", "cli"], preset: "inspector" }],
["--fail-on-flaky-tests", { description: `Fail if any test is flagged as flaky (default: false)` }],
["--forbid-only", { description: `Fail if test.only is called (default: false)` }],
["--fully-parallel", { description: `Run all tests in parallel (default: false)` }],
["--global-timeout <timeout>", { description: `Maximum time this test suite can run in milliseconds (default: unlimited)` }],
["-g, --grep <grep>", { description: `Only run tests matching this regular expression (default: ".*")` }],
["-G, --grep-invert <grep>", { description: `Only run tests that do not match this regular expression` }],
["--headed", { description: `Run tests in headed browsers (default: headless)` }],
["--ignore-snapshots", { description: `Ignore screenshot and snapshot expectations` }],
["--last-failed", { description: `Only re-run the failures` }],
["--last-failed-file <file>", { description: `Override the default path for the last-run JSON file used with --last-failed (default: <outputDir>/.last-run.json). Same as PLAYWRIGHT_LAST_RUN_OUTPUT_FILE environment variable.` }],
["--list", { description: `Collect all the tests and report them, but do not run` }],
["--max-failures <N>", { description: `Stop after the first N failures` }],
["--no-deps", { description: `Do not run project dependencies` }],
["--output <dir>", { description: `Folder for output artifacts (default: "test-results")` }],
["--only-changed [ref]", { description: `Only run test files that have been changed between 'HEAD' and 'ref'. Defaults to running all uncommitted changes. Only supports Git.` }],
["--pass-with-no-tests", { description: `Makes test run succeed even if no tests were found` }],
["--project <project-name...>", { description: `Only run tests from the specified list of projects, supports '*' wildcard (default: run all projects)` }],
["--quiet", { description: `Suppress stdio` }],
["--repeat-each <N>", { description: `Run each test N times (default: 1)` }],
["--reporter <reporter>", { description: `Reporter to use, comma-separated, can be ${import_common.builtInReporters.map((name) => `"${name}"`).join(", ")} (default: "${import_common.config.defaultReporter}")` }],
["--retries <retries>", { description: `Maximum retry count for flaky tests, zero for no retries (default: no retries)` }],
["--run-agents <mode>", { description: `Run agents to generate the code for page.perform`, choices: ["missing", "all", "none"], preset: "none" }],
["--shard <shard>", { description: `Shard tests and execute only the selected shard, specify in the form "current/all", 1-based, for example "3/5"` }],
["--test-list <file>", { description: `Path to a file containing a list of tests to run. See https://playwright.dev/docs/test-cli for more details.` }],
["--test-list-invert <file>", { description: `Path to a file containing a list of tests to skip. See https://playwright.dev/docs/test-cli for more details.` }],
["--timeout <timeout>", { description: `Specify test timeout threshold in milliseconds, zero for unlimited (default: ${import_common.config.defaultTimeout})` }],
["--trace <mode>", { description: `Force tracing mode`, choices: kTraceModes }],
["--tsconfig <path>", { description: `Path to a single tsconfig applicable to all imported files (default: look up tsconfig for each imported file separately)` }],
["--ui", { description: `Run tests in interactive UI mode` }],
["--ui-host <host>", { description: `Host to serve UI on; specifying this option opens UI in a browser tab` }],
["--ui-port <port>", { description: `Port to serve UI on, 0 for any free port; specifying this option opens UI in a browser tab` }],
["-u, --update-snapshots [mode]", { description: `Update snapshots with actual results. Running tests without the flag defaults to "missing"`, choices: ["all", "changed", "missing", "none"], preset: "changed" }],
["--update-source-method <method>", { description: `Chooses the way source is updated (default: "patch")`, choices: ["overwrite", "3way", "patch"] }],
["-j, --workers <workers>", { description: `Number of concurrent workers or percentage of logical CPU cores, use 1 to run in a single worker (default: 50%)` }],
["-x", { description: `Stop after the first failure` }]
];
addTestCommand(program);
addShowReportCommand(program);
addMergeReportsCommand(program);
addClearCacheCommand(program);
addTestMCPServerCommand(program);
addTestServerCommand(program);
addInitAgentsCommand(program);
addInitSkillsCommand(program);
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
program
});