feat(auth): implement user authentication system
This commit is contained in:
parent
4847ab793a
commit
25cea4fbe8
12051 changed files with 1462377 additions and 0 deletions
329
backend/node_modules/playwright/lib/mcp/browser/browserContextFactory.js
generated
vendored
Normal file
329
backend/node_modules/playwright/lib/mcp/browser/browserContextFactory.js
generated
vendored
Normal file
|
|
@ -0,0 +1,329 @@
|
|||
"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 browserContextFactory_exports = {};
|
||||
__export(browserContextFactory_exports, {
|
||||
SharedContextFactory: () => SharedContextFactory,
|
||||
contextFactory: () => contextFactory,
|
||||
identityBrowserContextFactory: () => identityBrowserContextFactory
|
||||
});
|
||||
module.exports = __toCommonJS(browserContextFactory_exports);
|
||||
var import_crypto = __toESM(require("crypto"));
|
||||
var import_fs = __toESM(require("fs"));
|
||||
var import_net = __toESM(require("net"));
|
||||
var import_path = __toESM(require("path"));
|
||||
var playwright = __toESM(require("playwright-core"));
|
||||
var import_registry = require("playwright-core/lib/server/registry/index");
|
||||
var import_server = require("playwright-core/lib/server");
|
||||
var import_log = require("../log");
|
||||
var import_config = require("./config");
|
||||
var import_server2 = require("../sdk/server");
|
||||
function contextFactory(config) {
|
||||
if (config.sharedBrowserContext)
|
||||
return SharedContextFactory.create(config);
|
||||
if (config.browser.remoteEndpoint)
|
||||
return new RemoteContextFactory(config);
|
||||
if (config.browser.cdpEndpoint)
|
||||
return new CdpContextFactory(config);
|
||||
if (config.browser.isolated)
|
||||
return new IsolatedContextFactory(config);
|
||||
return new PersistentContextFactory(config);
|
||||
}
|
||||
function identityBrowserContextFactory(browserContext) {
|
||||
return {
|
||||
createContext: async (clientInfo, abortSignal, options) => {
|
||||
return {
|
||||
browserContext,
|
||||
close: async () => {
|
||||
}
|
||||
};
|
||||
}
|
||||
};
|
||||
}
|
||||
class BaseContextFactory {
|
||||
constructor(name, config) {
|
||||
this._logName = name;
|
||||
this.config = config;
|
||||
}
|
||||
async _obtainBrowser(clientInfo, options) {
|
||||
if (this._browserPromise)
|
||||
return this._browserPromise;
|
||||
(0, import_log.testDebug)(`obtain browser (${this._logName})`);
|
||||
this._browserPromise = this._doObtainBrowser(clientInfo, options);
|
||||
void this._browserPromise.then((browser) => {
|
||||
browser.on("disconnected", () => {
|
||||
this._browserPromise = void 0;
|
||||
});
|
||||
}).catch(() => {
|
||||
this._browserPromise = void 0;
|
||||
});
|
||||
return this._browserPromise;
|
||||
}
|
||||
async _doObtainBrowser(clientInfo, options) {
|
||||
throw new Error("Not implemented");
|
||||
}
|
||||
async createContext(clientInfo, _, options) {
|
||||
(0, import_log.testDebug)(`create browser context (${this._logName})`);
|
||||
const browser = await this._obtainBrowser(clientInfo, options);
|
||||
const browserContext = await this._doCreateContext(browser, clientInfo);
|
||||
await addInitScript(browserContext, this.config.browser.initScript);
|
||||
return {
|
||||
browserContext,
|
||||
close: () => this._closeBrowserContext(browserContext, browser)
|
||||
};
|
||||
}
|
||||
async _doCreateContext(browser, clientInfo) {
|
||||
throw new Error("Not implemented");
|
||||
}
|
||||
async _closeBrowserContext(browserContext, browser) {
|
||||
(0, import_log.testDebug)(`close browser context (${this._logName})`);
|
||||
if (browser.contexts().length === 1)
|
||||
this._browserPromise = void 0;
|
||||
await browserContext.close().catch(import_log.logUnhandledError);
|
||||
if (browser.contexts().length === 0) {
|
||||
(0, import_log.testDebug)(`close browser (${this._logName})`);
|
||||
await browser.close().catch(import_log.logUnhandledError);
|
||||
}
|
||||
}
|
||||
}
|
||||
class IsolatedContextFactory extends BaseContextFactory {
|
||||
constructor(config) {
|
||||
super("isolated", config);
|
||||
}
|
||||
async _doObtainBrowser(clientInfo, options) {
|
||||
await injectCdpPort(this.config.browser);
|
||||
const browserType = playwright[this.config.browser.browserName];
|
||||
const tracesDir = await computeTracesDir(this.config, clientInfo);
|
||||
if (tracesDir && this.config.saveTrace)
|
||||
await startTraceServer(this.config, tracesDir);
|
||||
return browserType.launch({
|
||||
tracesDir,
|
||||
...this.config.browser.launchOptions,
|
||||
handleSIGINT: false,
|
||||
handleSIGTERM: false,
|
||||
...options.forceHeadless !== void 0 ? { headless: options.forceHeadless === "headless" } : {}
|
||||
}).catch((error) => {
|
||||
if (error.message.includes("Executable doesn't exist"))
|
||||
throw new Error(`Browser specified in your config is not installed. Either install it (likely) or change the config.`);
|
||||
throw error;
|
||||
});
|
||||
}
|
||||
async _doCreateContext(browser, clientInfo) {
|
||||
return browser.newContext(await browserContextOptionsFromConfig(this.config, clientInfo));
|
||||
}
|
||||
}
|
||||
class CdpContextFactory extends BaseContextFactory {
|
||||
constructor(config) {
|
||||
super("cdp", config);
|
||||
}
|
||||
async _doObtainBrowser() {
|
||||
return playwright.chromium.connectOverCDP(this.config.browser.cdpEndpoint, {
|
||||
headers: this.config.browser.cdpHeaders,
|
||||
timeout: this.config.browser.cdpTimeout
|
||||
});
|
||||
}
|
||||
async _doCreateContext(browser) {
|
||||
return this.config.browser.isolated ? await browser.newContext() : browser.contexts()[0];
|
||||
}
|
||||
}
|
||||
class RemoteContextFactory extends BaseContextFactory {
|
||||
constructor(config) {
|
||||
super("remote", config);
|
||||
}
|
||||
async _doObtainBrowser() {
|
||||
const url = new URL(this.config.browser.remoteEndpoint);
|
||||
url.searchParams.set("browser", this.config.browser.browserName);
|
||||
if (this.config.browser.launchOptions)
|
||||
url.searchParams.set("launch-options", JSON.stringify(this.config.browser.launchOptions));
|
||||
return playwright[this.config.browser.browserName].connect(String(url));
|
||||
}
|
||||
async _doCreateContext(browser) {
|
||||
return browser.newContext();
|
||||
}
|
||||
}
|
||||
class PersistentContextFactory {
|
||||
constructor(config) {
|
||||
this.name = "persistent";
|
||||
this.description = "Create a new persistent browser context";
|
||||
this._userDataDirs = /* @__PURE__ */ new Set();
|
||||
this.config = config;
|
||||
}
|
||||
async createContext(clientInfo, abortSignal, options) {
|
||||
await injectCdpPort(this.config.browser);
|
||||
(0, import_log.testDebug)("create browser context (persistent)");
|
||||
const userDataDir = this.config.browser.userDataDir ?? await this._createUserDataDir(clientInfo);
|
||||
const tracesDir = await computeTracesDir(this.config, clientInfo);
|
||||
if (tracesDir && this.config.saveTrace)
|
||||
await startTraceServer(this.config, tracesDir);
|
||||
this._userDataDirs.add(userDataDir);
|
||||
(0, import_log.testDebug)("lock user data dir", userDataDir);
|
||||
const browserType = playwright[this.config.browser.browserName];
|
||||
for (let i = 0; i < 5; i++) {
|
||||
const launchOptions = {
|
||||
tracesDir,
|
||||
...this.config.browser.launchOptions,
|
||||
...await browserContextOptionsFromConfig(this.config, clientInfo),
|
||||
handleSIGINT: false,
|
||||
handleSIGTERM: false,
|
||||
ignoreDefaultArgs: [
|
||||
"--disable-extensions"
|
||||
],
|
||||
assistantMode: true,
|
||||
...options.forceHeadless !== void 0 ? { headless: options.forceHeadless === "headless" } : {}
|
||||
};
|
||||
try {
|
||||
const browserContext = await browserType.launchPersistentContext(userDataDir, launchOptions);
|
||||
await addInitScript(browserContext, this.config.browser.initScript);
|
||||
const close = () => this._closeBrowserContext(browserContext, userDataDir);
|
||||
return { browserContext, close };
|
||||
} catch (error) {
|
||||
if (error.message.includes("Executable doesn't exist"))
|
||||
throw new Error(`Browser specified in your config is not installed. Either install it (likely) or change the config.`);
|
||||
if (error.message.includes("cannot open shared object file: No such file or directory")) {
|
||||
const browserName = launchOptions.channel ?? this.config.browser.browserName;
|
||||
throw new Error(`Missing system dependencies required to run browser ${browserName}. Install them with: sudo npx playwright install-deps ${browserName}`);
|
||||
}
|
||||
if (error.message.includes("ProcessSingleton") || // On Windows the process exits silently with code 21 when the profile is in use.
|
||||
error.message.includes("exitCode=21")) {
|
||||
await new Promise((resolve) => setTimeout(resolve, 1e3));
|
||||
continue;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
throw new Error(`Browser is already in use for ${userDataDir}, use --isolated to run multiple instances of the same browser`);
|
||||
}
|
||||
async _closeBrowserContext(browserContext, userDataDir) {
|
||||
(0, import_log.testDebug)("close browser context (persistent)");
|
||||
(0, import_log.testDebug)("release user data dir", userDataDir);
|
||||
await browserContext.close().catch(() => {
|
||||
});
|
||||
this._userDataDirs.delete(userDataDir);
|
||||
if (process.env.PWMCP_PROFILES_DIR_FOR_TEST && userDataDir.startsWith(process.env.PWMCP_PROFILES_DIR_FOR_TEST))
|
||||
await import_fs.default.promises.rm(userDataDir, { recursive: true }).catch(import_log.logUnhandledError);
|
||||
(0, import_log.testDebug)("close browser context complete (persistent)");
|
||||
}
|
||||
async _createUserDataDir(clientInfo) {
|
||||
const dir = process.env.PWMCP_PROFILES_DIR_FOR_TEST ?? import_registry.registryDirectory;
|
||||
const browserToken = this.config.browser.launchOptions?.channel ?? this.config.browser?.browserName;
|
||||
const rootPath = (0, import_server2.firstRootPath)(clientInfo);
|
||||
const rootPathToken = rootPath ? `-${createHash(rootPath)}` : "";
|
||||
const result = import_path.default.join(dir, `mcp-${browserToken}${rootPathToken}`);
|
||||
await import_fs.default.promises.mkdir(result, { recursive: true });
|
||||
return result;
|
||||
}
|
||||
}
|
||||
async function injectCdpPort(browserConfig) {
|
||||
if (browserConfig.browserName === "chromium")
|
||||
browserConfig.launchOptions.cdpPort = await findFreePort();
|
||||
}
|
||||
async function findFreePort() {
|
||||
return new Promise((resolve, reject) => {
|
||||
const server = import_net.default.createServer();
|
||||
server.listen(0, () => {
|
||||
const { port } = server.address();
|
||||
server.close(() => resolve(port));
|
||||
});
|
||||
server.on("error", reject);
|
||||
});
|
||||
}
|
||||
async function startTraceServer(config, tracesDir) {
|
||||
if (!config.saveTrace)
|
||||
return;
|
||||
const server = await (0, import_server.startTraceViewerServer)();
|
||||
const urlPrefix = server.urlPrefix("human-readable");
|
||||
const url = urlPrefix + "/trace/index.html?trace=" + tracesDir + "/trace.json";
|
||||
console.error("\nTrace viewer listening on " + url);
|
||||
}
|
||||
function createHash(data) {
|
||||
return import_crypto.default.createHash("sha256").update(data).digest("hex").slice(0, 7);
|
||||
}
|
||||
async function addInitScript(browserContext, initScript) {
|
||||
for (const scriptPath of initScript ?? [])
|
||||
await browserContext.addInitScript({ path: import_path.default.resolve(scriptPath) });
|
||||
}
|
||||
class SharedContextFactory {
|
||||
static create(config) {
|
||||
if (SharedContextFactory._instance)
|
||||
throw new Error("SharedContextFactory already exists");
|
||||
const baseConfig = { ...config, sharedBrowserContext: false };
|
||||
const baseFactory = contextFactory(baseConfig);
|
||||
SharedContextFactory._instance = new SharedContextFactory(baseFactory);
|
||||
return SharedContextFactory._instance;
|
||||
}
|
||||
constructor(baseFactory) {
|
||||
this._baseFactory = baseFactory;
|
||||
}
|
||||
async createContext(clientInfo, abortSignal, options) {
|
||||
if (!this._contextPromise) {
|
||||
(0, import_log.testDebug)("create shared browser context");
|
||||
this._contextPromise = this._baseFactory.createContext(clientInfo, abortSignal, options);
|
||||
}
|
||||
const { browserContext } = await this._contextPromise;
|
||||
(0, import_log.testDebug)(`shared context client connected`);
|
||||
return {
|
||||
browserContext,
|
||||
close: async () => {
|
||||
(0, import_log.testDebug)(`shared context client disconnected`);
|
||||
}
|
||||
};
|
||||
}
|
||||
static async dispose() {
|
||||
await SharedContextFactory._instance?._dispose();
|
||||
}
|
||||
async _dispose() {
|
||||
const contextPromise = this._contextPromise;
|
||||
this._contextPromise = void 0;
|
||||
if (!contextPromise)
|
||||
return;
|
||||
const { close } = await contextPromise;
|
||||
await close();
|
||||
}
|
||||
}
|
||||
async function computeTracesDir(config, clientInfo) {
|
||||
if (!config.saveTrace && !config.capabilities?.includes("tracing"))
|
||||
return;
|
||||
return await (0, import_config.outputFile)(config, clientInfo, `traces`, { origin: "code", title: "Collecting trace" });
|
||||
}
|
||||
async function browserContextOptionsFromConfig(config, clientInfo) {
|
||||
const result = { ...config.browser.contextOptions };
|
||||
if (config.saveVideo) {
|
||||
const dir = await (0, import_config.outputFile)(config, clientInfo, `videos`, { origin: "code", title: "Saving video" });
|
||||
result.recordVideo = {
|
||||
dir,
|
||||
size: config.saveVideo
|
||||
};
|
||||
}
|
||||
return result;
|
||||
}
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
SharedContextFactory,
|
||||
contextFactory,
|
||||
identityBrowserContextFactory
|
||||
});
|
||||
84
backend/node_modules/playwright/lib/mcp/browser/browserServerBackend.js
generated
vendored
Normal file
84
backend/node_modules/playwright/lib/mcp/browser/browserServerBackend.js
generated
vendored
Normal file
|
|
@ -0,0 +1,84 @@
|
|||
"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 browserServerBackend_exports = {};
|
||||
__export(browserServerBackend_exports, {
|
||||
BrowserServerBackend: () => BrowserServerBackend
|
||||
});
|
||||
module.exports = __toCommonJS(browserServerBackend_exports);
|
||||
var import_context = require("./context");
|
||||
var import_log = require("../log");
|
||||
var import_response = require("./response");
|
||||
var import_sessionLog = require("./sessionLog");
|
||||
var import_tools = require("./tools");
|
||||
var import_tool = require("../sdk/tool");
|
||||
class BrowserServerBackend {
|
||||
constructor(config, factory) {
|
||||
this._config = config;
|
||||
this._browserContextFactory = factory;
|
||||
this._tools = (0, import_tools.filteredTools)(config);
|
||||
}
|
||||
async initialize(clientInfo) {
|
||||
this._sessionLog = this._config.saveSession ? await import_sessionLog.SessionLog.create(this._config, clientInfo) : void 0;
|
||||
this._context = new import_context.Context({
|
||||
config: this._config,
|
||||
browserContextFactory: this._browserContextFactory,
|
||||
sessionLog: this._sessionLog,
|
||||
clientInfo
|
||||
});
|
||||
}
|
||||
async listTools() {
|
||||
return this._tools.map((tool) => (0, import_tool.toMcpTool)(tool.schema));
|
||||
}
|
||||
async callTool(name, rawArguments) {
|
||||
const tool = this._tools.find((tool2) => tool2.schema.name === name);
|
||||
if (!tool) {
|
||||
return {
|
||||
content: [{ type: "text", text: `### Error
|
||||
Tool "${name}" not found` }],
|
||||
isError: true
|
||||
};
|
||||
}
|
||||
const parsedArguments = tool.schema.inputSchema.parse(rawArguments || {});
|
||||
const context = this._context;
|
||||
const response = import_response.Response.create(context, name, parsedArguments);
|
||||
context.setRunningTool(name);
|
||||
let responseObject;
|
||||
try {
|
||||
await tool.handle(context, parsedArguments, response);
|
||||
responseObject = await response.build();
|
||||
this._sessionLog?.logResponse(name, parsedArguments, responseObject);
|
||||
} catch (error) {
|
||||
return {
|
||||
content: [{ type: "text", text: `### Error
|
||||
${String(error)}` }],
|
||||
isError: true
|
||||
};
|
||||
} finally {
|
||||
context.setRunningTool(void 0);
|
||||
}
|
||||
return responseObject;
|
||||
}
|
||||
serverClosed() {
|
||||
void this._context?.dispose().catch(import_log.logUnhandledError);
|
||||
}
|
||||
}
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
BrowserServerBackend
|
||||
});
|
||||
421
backend/node_modules/playwright/lib/mcp/browser/config.js
generated
vendored
Normal file
421
backend/node_modules/playwright/lib/mcp/browser/config.js
generated
vendored
Normal file
|
|
@ -0,0 +1,421 @@
|
|||
"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 config_exports = {};
|
||||
__export(config_exports, {
|
||||
commaSeparatedList: () => commaSeparatedList,
|
||||
configFromCLIOptions: () => configFromCLIOptions,
|
||||
defaultConfig: () => defaultConfig,
|
||||
dotenvFileLoader: () => dotenvFileLoader,
|
||||
enumParser: () => enumParser,
|
||||
headerParser: () => headerParser,
|
||||
numberParser: () => numberParser,
|
||||
outputDir: () => outputDir,
|
||||
outputFile: () => outputFile,
|
||||
resolutionParser: () => resolutionParser,
|
||||
resolveCLIConfig: () => resolveCLIConfig,
|
||||
resolveConfig: () => resolveConfig,
|
||||
semicolonSeparatedList: () => semicolonSeparatedList
|
||||
});
|
||||
module.exports = __toCommonJS(config_exports);
|
||||
var import_fs = __toESM(require("fs"));
|
||||
var import_os = __toESM(require("os"));
|
||||
var import_path = __toESM(require("path"));
|
||||
var import_playwright_core = require("playwright-core");
|
||||
var import_utilsBundle = require("playwright-core/lib/utilsBundle");
|
||||
var import_util = require("../../util");
|
||||
var import_server = require("../sdk/server");
|
||||
const defaultConfig = {
|
||||
browser: {
|
||||
browserName: "chromium",
|
||||
launchOptions: {
|
||||
channel: "chrome",
|
||||
headless: import_os.default.platform() === "linux" && !process.env.DISPLAY,
|
||||
chromiumSandbox: true
|
||||
},
|
||||
contextOptions: {
|
||||
viewport: null
|
||||
}
|
||||
},
|
||||
console: {
|
||||
level: "info"
|
||||
},
|
||||
network: {
|
||||
allowedOrigins: void 0,
|
||||
blockedOrigins: void 0
|
||||
},
|
||||
server: {},
|
||||
saveTrace: false,
|
||||
snapshot: {
|
||||
mode: "incremental",
|
||||
output: "stdout"
|
||||
},
|
||||
timeouts: {
|
||||
action: 5e3,
|
||||
navigation: 6e4
|
||||
}
|
||||
};
|
||||
async function resolveConfig(config) {
|
||||
return mergeConfig(defaultConfig, config);
|
||||
}
|
||||
async function resolveCLIConfig(cliOptions) {
|
||||
const configInFile = await loadConfig(cliOptions.config);
|
||||
const envOverrides = configFromEnv();
|
||||
const cliOverrides = configFromCLIOptions(cliOptions);
|
||||
let result = defaultConfig;
|
||||
result = mergeConfig(result, configInFile);
|
||||
result = mergeConfig(result, envOverrides);
|
||||
result = mergeConfig(result, cliOverrides);
|
||||
await validateConfig(result);
|
||||
return result;
|
||||
}
|
||||
async function validateConfig(config) {
|
||||
if (config.browser.initScript) {
|
||||
for (const script of config.browser.initScript) {
|
||||
if (!await (0, import_util.fileExistsAsync)(script))
|
||||
throw new Error(`Init script file does not exist: ${script}`);
|
||||
}
|
||||
}
|
||||
if (config.browser.initPage) {
|
||||
for (const page of config.browser.initPage) {
|
||||
if (!await (0, import_util.fileExistsAsync)(page))
|
||||
throw new Error(`Init page file does not exist: ${page}`);
|
||||
}
|
||||
}
|
||||
if (config.sharedBrowserContext && config.saveVideo)
|
||||
throw new Error("saveVideo is not supported when sharedBrowserContext is true");
|
||||
}
|
||||
function configFromCLIOptions(cliOptions) {
|
||||
let browserName;
|
||||
let channel;
|
||||
switch (cliOptions.browser) {
|
||||
case "chrome":
|
||||
case "chrome-beta":
|
||||
case "chrome-canary":
|
||||
case "chrome-dev":
|
||||
case "chromium":
|
||||
case "msedge":
|
||||
case "msedge-beta":
|
||||
case "msedge-canary":
|
||||
case "msedge-dev":
|
||||
browserName = "chromium";
|
||||
channel = cliOptions.browser;
|
||||
break;
|
||||
case "firefox":
|
||||
browserName = "firefox";
|
||||
break;
|
||||
case "webkit":
|
||||
browserName = "webkit";
|
||||
break;
|
||||
}
|
||||
const launchOptions = {
|
||||
channel,
|
||||
executablePath: cliOptions.executablePath,
|
||||
headless: cliOptions.headless
|
||||
};
|
||||
if (cliOptions.sandbox === false)
|
||||
launchOptions.chromiumSandbox = false;
|
||||
if (cliOptions.proxyServer) {
|
||||
launchOptions.proxy = {
|
||||
server: cliOptions.proxyServer
|
||||
};
|
||||
if (cliOptions.proxyBypass)
|
||||
launchOptions.proxy.bypass = cliOptions.proxyBypass;
|
||||
}
|
||||
if (cliOptions.device && cliOptions.cdpEndpoint)
|
||||
throw new Error("Device emulation is not supported with cdpEndpoint.");
|
||||
const contextOptions = cliOptions.device ? import_playwright_core.devices[cliOptions.device] : {};
|
||||
if (cliOptions.storageState)
|
||||
contextOptions.storageState = cliOptions.storageState;
|
||||
if (cliOptions.userAgent)
|
||||
contextOptions.userAgent = cliOptions.userAgent;
|
||||
if (cliOptions.viewportSize)
|
||||
contextOptions.viewport = cliOptions.viewportSize;
|
||||
if (cliOptions.ignoreHttpsErrors)
|
||||
contextOptions.ignoreHTTPSErrors = true;
|
||||
if (cliOptions.blockServiceWorkers)
|
||||
contextOptions.serviceWorkers = "block";
|
||||
if (cliOptions.grantPermissions)
|
||||
contextOptions.permissions = cliOptions.grantPermissions;
|
||||
const result = {
|
||||
browser: {
|
||||
browserName,
|
||||
isolated: cliOptions.isolated,
|
||||
userDataDir: cliOptions.userDataDir,
|
||||
launchOptions,
|
||||
contextOptions,
|
||||
cdpEndpoint: cliOptions.cdpEndpoint,
|
||||
cdpHeaders: cliOptions.cdpHeader,
|
||||
initPage: cliOptions.initPage,
|
||||
initScript: cliOptions.initScript
|
||||
},
|
||||
server: {
|
||||
port: cliOptions.port,
|
||||
host: cliOptions.host,
|
||||
allowedHosts: cliOptions.allowedHosts
|
||||
},
|
||||
capabilities: cliOptions.caps,
|
||||
console: {
|
||||
level: cliOptions.consoleLevel
|
||||
},
|
||||
network: {
|
||||
allowedOrigins: cliOptions.allowedOrigins,
|
||||
blockedOrigins: cliOptions.blockedOrigins
|
||||
},
|
||||
allowUnrestrictedFileAccess: cliOptions.allowUnrestrictedFileAccess,
|
||||
codegen: cliOptions.codegen,
|
||||
saveSession: cliOptions.saveSession,
|
||||
saveTrace: cliOptions.saveTrace,
|
||||
saveVideo: cliOptions.saveVideo,
|
||||
secrets: cliOptions.secrets,
|
||||
sharedBrowserContext: cliOptions.sharedBrowserContext,
|
||||
snapshot: cliOptions.snapshotMode ? { mode: cliOptions.snapshotMode } : void 0,
|
||||
outputMode: cliOptions.outputMode,
|
||||
outputDir: cliOptions.outputDir,
|
||||
imageResponses: cliOptions.imageResponses,
|
||||
testIdAttribute: cliOptions.testIdAttribute,
|
||||
timeouts: {
|
||||
action: cliOptions.timeoutAction,
|
||||
navigation: cliOptions.timeoutNavigation
|
||||
}
|
||||
};
|
||||
return result;
|
||||
}
|
||||
function configFromEnv() {
|
||||
const options = {};
|
||||
options.allowedHosts = commaSeparatedList(process.env.PLAYWRIGHT_MCP_ALLOWED_HOSTNAMES);
|
||||
options.allowedOrigins = semicolonSeparatedList(process.env.PLAYWRIGHT_MCP_ALLOWED_ORIGINS);
|
||||
options.allowUnrestrictedFileAccess = envToBoolean(process.env.PLAYWRIGHT_MCP_ALLOW_UNRESTRICTED_FILE_ACCESS);
|
||||
options.blockedOrigins = semicolonSeparatedList(process.env.PLAYWRIGHT_MCP_BLOCKED_ORIGINS);
|
||||
options.blockServiceWorkers = envToBoolean(process.env.PLAYWRIGHT_MCP_BLOCK_SERVICE_WORKERS);
|
||||
options.browser = envToString(process.env.PLAYWRIGHT_MCP_BROWSER);
|
||||
options.caps = commaSeparatedList(process.env.PLAYWRIGHT_MCP_CAPS);
|
||||
options.cdpEndpoint = envToString(process.env.PLAYWRIGHT_MCP_CDP_ENDPOINT);
|
||||
options.cdpHeader = headerParser(process.env.PLAYWRIGHT_MCP_CDP_HEADERS, {});
|
||||
options.config = envToString(process.env.PLAYWRIGHT_MCP_CONFIG);
|
||||
if (process.env.PLAYWRIGHT_MCP_CONSOLE_LEVEL)
|
||||
options.consoleLevel = enumParser("--console-level", ["error", "warning", "info", "debug"], process.env.PLAYWRIGHT_MCP_CONSOLE_LEVEL);
|
||||
options.device = envToString(process.env.PLAYWRIGHT_MCP_DEVICE);
|
||||
options.executablePath = envToString(process.env.PLAYWRIGHT_MCP_EXECUTABLE_PATH);
|
||||
options.grantPermissions = commaSeparatedList(process.env.PLAYWRIGHT_MCP_GRANT_PERMISSIONS);
|
||||
options.headless = envToBoolean(process.env.PLAYWRIGHT_MCP_HEADLESS);
|
||||
options.host = envToString(process.env.PLAYWRIGHT_MCP_HOST);
|
||||
options.ignoreHttpsErrors = envToBoolean(process.env.PLAYWRIGHT_MCP_IGNORE_HTTPS_ERRORS);
|
||||
const initPage = envToString(process.env.PLAYWRIGHT_MCP_INIT_PAGE);
|
||||
if (initPage)
|
||||
options.initPage = [initPage];
|
||||
const initScript = envToString(process.env.PLAYWRIGHT_MCP_INIT_SCRIPT);
|
||||
if (initScript)
|
||||
options.initScript = [initScript];
|
||||
options.isolated = envToBoolean(process.env.PLAYWRIGHT_MCP_ISOLATED);
|
||||
if (process.env.PLAYWRIGHT_MCP_IMAGE_RESPONSES)
|
||||
options.imageResponses = enumParser("--image-responses", ["allow", "omit"], process.env.PLAYWRIGHT_MCP_IMAGE_RESPONSES);
|
||||
options.sandbox = envToBoolean(process.env.PLAYWRIGHT_MCP_SANDBOX);
|
||||
options.outputDir = envToString(process.env.PLAYWRIGHT_MCP_OUTPUT_DIR);
|
||||
options.port = numberParser(process.env.PLAYWRIGHT_MCP_PORT);
|
||||
options.proxyBypass = envToString(process.env.PLAYWRIGHT_MCP_PROXY_BYPASS);
|
||||
options.proxyServer = envToString(process.env.PLAYWRIGHT_MCP_PROXY_SERVER);
|
||||
options.saveTrace = envToBoolean(process.env.PLAYWRIGHT_MCP_SAVE_TRACE);
|
||||
options.saveVideo = resolutionParser("--save-video", process.env.PLAYWRIGHT_MCP_SAVE_VIDEO);
|
||||
options.secrets = dotenvFileLoader(process.env.PLAYWRIGHT_MCP_SECRETS_FILE);
|
||||
options.storageState = envToString(process.env.PLAYWRIGHT_MCP_STORAGE_STATE);
|
||||
options.testIdAttribute = envToString(process.env.PLAYWRIGHT_MCP_TEST_ID_ATTRIBUTE);
|
||||
options.timeoutAction = numberParser(process.env.PLAYWRIGHT_MCP_TIMEOUT_ACTION);
|
||||
options.timeoutNavigation = numberParser(process.env.PLAYWRIGHT_MCP_TIMEOUT_NAVIGATION);
|
||||
options.userAgent = envToString(process.env.PLAYWRIGHT_MCP_USER_AGENT);
|
||||
options.userDataDir = envToString(process.env.PLAYWRIGHT_MCP_USER_DATA_DIR);
|
||||
options.viewportSize = resolutionParser("--viewport-size", process.env.PLAYWRIGHT_MCP_VIEWPORT_SIZE);
|
||||
return configFromCLIOptions(options);
|
||||
}
|
||||
async function loadConfig(configFile) {
|
||||
if (!configFile)
|
||||
return {};
|
||||
try {
|
||||
return JSON.parse(await import_fs.default.promises.readFile(configFile, "utf8"));
|
||||
} catch (error) {
|
||||
throw new Error(`Failed to load config file: ${configFile}, ${error}`);
|
||||
}
|
||||
}
|
||||
function tmpDir() {
|
||||
return import_path.default.join(process.env.PW_TMPDIR_FOR_TEST ?? import_os.default.tmpdir(), "playwright-mcp-output");
|
||||
}
|
||||
function outputDir(config, clientInfo) {
|
||||
const rootPath = (0, import_server.firstRootPath)(clientInfo);
|
||||
return config.outputDir ?? (rootPath ? import_path.default.join(rootPath, ".playwright-mcp") : void 0) ?? import_path.default.join(tmpDir(), String(clientInfo.timestamp));
|
||||
}
|
||||
async function outputFile(config, clientInfo, fileName, options) {
|
||||
const file = await resolveFile(config, clientInfo, fileName, options);
|
||||
await import_fs.default.promises.mkdir(import_path.default.dirname(file), { recursive: true });
|
||||
(0, import_utilsBundle.debug)("pw:mcp:file")(options.title, file);
|
||||
return file;
|
||||
}
|
||||
async function resolveFile(config, clientInfo, fileName, options) {
|
||||
const dir = outputDir(config, clientInfo);
|
||||
if (options.origin === "code")
|
||||
return import_path.default.resolve(dir, fileName);
|
||||
if (options.origin === "llm") {
|
||||
fileName = fileName.split("\\").join("/");
|
||||
const resolvedFile = import_path.default.resolve(dir, fileName);
|
||||
if (!resolvedFile.startsWith(import_path.default.resolve(dir) + import_path.default.sep))
|
||||
throw new Error(`Resolved file path ${resolvedFile} is outside of the output directory ${dir}. Use relative file names to stay within the output directory.`);
|
||||
return resolvedFile;
|
||||
}
|
||||
return import_path.default.join(dir, sanitizeForFilePath(fileName));
|
||||
}
|
||||
function pickDefined(obj) {
|
||||
return Object.fromEntries(
|
||||
Object.entries(obj ?? {}).filter(([_, v]) => v !== void 0)
|
||||
);
|
||||
}
|
||||
function mergeConfig(base, overrides) {
|
||||
const browser = {
|
||||
...pickDefined(base.browser),
|
||||
...pickDefined(overrides.browser),
|
||||
browserName: overrides.browser?.browserName ?? base.browser?.browserName ?? "chromium",
|
||||
isolated: overrides.browser?.isolated ?? base.browser?.isolated ?? false,
|
||||
launchOptions: {
|
||||
...pickDefined(base.browser?.launchOptions),
|
||||
...pickDefined(overrides.browser?.launchOptions),
|
||||
...{ assistantMode: true }
|
||||
},
|
||||
contextOptions: {
|
||||
...pickDefined(base.browser?.contextOptions),
|
||||
...pickDefined(overrides.browser?.contextOptions)
|
||||
}
|
||||
};
|
||||
if (browser.browserName !== "chromium" && browser.launchOptions)
|
||||
delete browser.launchOptions.channel;
|
||||
return {
|
||||
...pickDefined(base),
|
||||
...pickDefined(overrides),
|
||||
browser,
|
||||
console: {
|
||||
...pickDefined(base.console),
|
||||
...pickDefined(overrides.console)
|
||||
},
|
||||
network: {
|
||||
...pickDefined(base.network),
|
||||
...pickDefined(overrides.network)
|
||||
},
|
||||
server: {
|
||||
...pickDefined(base.server),
|
||||
...pickDefined(overrides.server)
|
||||
},
|
||||
snapshot: {
|
||||
...pickDefined(base.snapshot),
|
||||
...pickDefined(overrides.snapshot)
|
||||
},
|
||||
timeouts: {
|
||||
...pickDefined(base.timeouts),
|
||||
...pickDefined(overrides.timeouts)
|
||||
}
|
||||
};
|
||||
}
|
||||
function semicolonSeparatedList(value) {
|
||||
if (!value)
|
||||
return void 0;
|
||||
return value.split(";").map((v) => v.trim());
|
||||
}
|
||||
function commaSeparatedList(value) {
|
||||
if (!value)
|
||||
return void 0;
|
||||
return value.split(",").map((v) => v.trim());
|
||||
}
|
||||
function dotenvFileLoader(value) {
|
||||
if (!value)
|
||||
return void 0;
|
||||
return import_utilsBundle.dotenv.parse(import_fs.default.readFileSync(value, "utf8"));
|
||||
}
|
||||
function numberParser(value) {
|
||||
if (!value)
|
||||
return void 0;
|
||||
return +value;
|
||||
}
|
||||
function resolutionParser(name, value) {
|
||||
if (!value)
|
||||
return void 0;
|
||||
if (value.includes("x")) {
|
||||
const [width, height] = value.split("x").map((v) => +v);
|
||||
if (isNaN(width) || isNaN(height) || width <= 0 || height <= 0)
|
||||
throw new Error(`Invalid resolution format: use ${name}="800x600"`);
|
||||
return { width, height };
|
||||
}
|
||||
if (value.includes(",")) {
|
||||
const [width, height] = value.split(",").map((v) => +v);
|
||||
if (isNaN(width) || isNaN(height) || width <= 0 || height <= 0)
|
||||
throw new Error(`Invalid resolution format: use ${name}="800x600"`);
|
||||
return { width, height };
|
||||
}
|
||||
throw new Error(`Invalid resolution format: use ${name}="800x600"`);
|
||||
}
|
||||
function headerParser(arg, previous) {
|
||||
if (!arg)
|
||||
return previous || {};
|
||||
const result = previous || {};
|
||||
const [name, value] = arg.split(":").map((v) => v.trim());
|
||||
result[name] = value;
|
||||
return result;
|
||||
}
|
||||
function enumParser(name, options, value) {
|
||||
if (!options.includes(value))
|
||||
throw new Error(`Invalid ${name}: ${value}. Valid values are: ${options.join(", ")}`);
|
||||
return value;
|
||||
}
|
||||
function envToBoolean(value) {
|
||||
if (value === "true" || value === "1")
|
||||
return true;
|
||||
if (value === "false" || value === "0")
|
||||
return false;
|
||||
return void 0;
|
||||
}
|
||||
function envToString(value) {
|
||||
return value ? value.trim() : void 0;
|
||||
}
|
||||
function sanitizeForFilePath(s) {
|
||||
const sanitize = (s2) => s2.replace(/[\x00-\x2C\x2E-\x2F\x3A-\x40\x5B-\x60\x7B-\x7F]+/g, "-");
|
||||
const separator = s.lastIndexOf(".");
|
||||
if (separator === -1)
|
||||
return sanitize(s);
|
||||
return sanitize(s.substring(0, separator)) + "." + sanitize(s.substring(separator + 1));
|
||||
}
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
commaSeparatedList,
|
||||
configFromCLIOptions,
|
||||
defaultConfig,
|
||||
dotenvFileLoader,
|
||||
enumParser,
|
||||
headerParser,
|
||||
numberParser,
|
||||
outputDir,
|
||||
outputFile,
|
||||
resolutionParser,
|
||||
resolveCLIConfig,
|
||||
resolveConfig,
|
||||
semicolonSeparatedList
|
||||
});
|
||||
244
backend/node_modules/playwright/lib/mcp/browser/context.js
generated
vendored
Normal file
244
backend/node_modules/playwright/lib/mcp/browser/context.js
generated
vendored
Normal file
|
|
@ -0,0 +1,244 @@
|
|||
"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 context_exports = {};
|
||||
__export(context_exports, {
|
||||
Context: () => Context
|
||||
});
|
||||
module.exports = __toCommonJS(context_exports);
|
||||
var import_utilsBundle = require("playwright-core/lib/utilsBundle");
|
||||
var import_utils = require("playwright-core/lib/utils");
|
||||
var import_playwright_core = require("playwright-core");
|
||||
var import_url = require("url");
|
||||
var import_os = __toESM(require("os"));
|
||||
var import_log = require("../log");
|
||||
var import_tab = require("./tab");
|
||||
var import_config = require("./config");
|
||||
const testDebug = (0, import_utilsBundle.debug)("pw:mcp:test");
|
||||
class Context {
|
||||
constructor(options) {
|
||||
this._tabs = [];
|
||||
this._abortController = new AbortController();
|
||||
this.config = options.config;
|
||||
this.sessionLog = options.sessionLog;
|
||||
this.options = options;
|
||||
this._browserContextFactory = options.browserContextFactory;
|
||||
this._clientInfo = options.clientInfo;
|
||||
testDebug("create context");
|
||||
Context._allContexts.add(this);
|
||||
}
|
||||
static {
|
||||
this._allContexts = /* @__PURE__ */ new Set();
|
||||
}
|
||||
static async disposeAll() {
|
||||
await Promise.all([...Context._allContexts].map((context) => context.dispose()));
|
||||
}
|
||||
tabs() {
|
||||
return this._tabs;
|
||||
}
|
||||
currentTab() {
|
||||
return this._currentTab;
|
||||
}
|
||||
currentTabOrDie() {
|
||||
if (!this._currentTab)
|
||||
throw new Error("No open pages available.");
|
||||
return this._currentTab;
|
||||
}
|
||||
async newTab() {
|
||||
const { browserContext } = await this._ensureBrowserContext({});
|
||||
const page = await browserContext.newPage();
|
||||
this._currentTab = this._tabs.find((t) => t.page === page);
|
||||
return this._currentTab;
|
||||
}
|
||||
async selectTab(index) {
|
||||
const tab = this._tabs[index];
|
||||
if (!tab)
|
||||
throw new Error(`Tab ${index} not found`);
|
||||
await tab.page.bringToFront();
|
||||
this._currentTab = tab;
|
||||
return tab;
|
||||
}
|
||||
async ensureTab(options = {}) {
|
||||
const { browserContext } = await this._ensureBrowserContext(options);
|
||||
if (!this._currentTab)
|
||||
await browserContext.newPage();
|
||||
return this._currentTab;
|
||||
}
|
||||
async closeTab(index) {
|
||||
const tab = index === void 0 ? this._currentTab : this._tabs[index];
|
||||
if (!tab)
|
||||
throw new Error(`Tab ${index} not found`);
|
||||
const url = tab.page.url();
|
||||
await tab.page.close();
|
||||
return url;
|
||||
}
|
||||
async outputFile(fileName, options) {
|
||||
return (0, import_config.outputFile)(this.config, this._clientInfo, fileName, options);
|
||||
}
|
||||
_onPageCreated(page) {
|
||||
const tab = new import_tab.Tab(this, page, (tab2) => this._onPageClosed(tab2));
|
||||
this._tabs.push(tab);
|
||||
if (!this._currentTab)
|
||||
this._currentTab = tab;
|
||||
}
|
||||
_onPageClosed(tab) {
|
||||
const index = this._tabs.indexOf(tab);
|
||||
if (index === -1)
|
||||
return;
|
||||
this._tabs.splice(index, 1);
|
||||
if (this._currentTab === tab)
|
||||
this._currentTab = this._tabs[Math.min(index, this._tabs.length - 1)];
|
||||
if (!this._tabs.length)
|
||||
void this.closeBrowserContext();
|
||||
}
|
||||
async closeBrowserContext() {
|
||||
if (!this._closeBrowserContextPromise)
|
||||
this._closeBrowserContextPromise = this._closeBrowserContextImpl().catch(import_log.logUnhandledError);
|
||||
await this._closeBrowserContextPromise;
|
||||
this._closeBrowserContextPromise = void 0;
|
||||
}
|
||||
isRunningTool() {
|
||||
return this._runningToolName !== void 0;
|
||||
}
|
||||
setRunningTool(name) {
|
||||
this._runningToolName = name;
|
||||
}
|
||||
async _closeBrowserContextImpl() {
|
||||
if (!this._browserContextPromise)
|
||||
return;
|
||||
testDebug("close context");
|
||||
const promise = this._browserContextPromise;
|
||||
this._browserContextPromise = void 0;
|
||||
this._browserContextOption = void 0;
|
||||
await promise.then(async ({ browserContext, close }) => {
|
||||
if (this.config.saveTrace)
|
||||
await browserContext.tracing.stop();
|
||||
await close();
|
||||
});
|
||||
}
|
||||
async dispose() {
|
||||
this._abortController.abort("MCP context disposed");
|
||||
await this.closeBrowserContext();
|
||||
Context._allContexts.delete(this);
|
||||
}
|
||||
async _setupRequestInterception(context) {
|
||||
if (this.config.network?.allowedOrigins?.length) {
|
||||
await context.route("**", (route) => route.abort("blockedbyclient"));
|
||||
for (const origin of this.config.network.allowedOrigins)
|
||||
await context.route(originOrHostGlob(origin), (route) => route.continue());
|
||||
}
|
||||
if (this.config.network?.blockedOrigins?.length) {
|
||||
for (const origin of this.config.network.blockedOrigins)
|
||||
await context.route(originOrHostGlob(origin), (route) => route.abort("blockedbyclient"));
|
||||
}
|
||||
}
|
||||
async ensureBrowserContext(options = {}) {
|
||||
const { browserContext } = await this._ensureBrowserContext(options);
|
||||
return browserContext;
|
||||
}
|
||||
_ensureBrowserContext(options) {
|
||||
if (this._browserContextPromise && (options.forceHeadless === void 0 || this._browserContextOption?.forceHeadless === options.forceHeadless))
|
||||
return this._browserContextPromise;
|
||||
const closePrework = this._browserContextPromise ? this.closeBrowserContext() : Promise.resolve();
|
||||
this._browserContextPromise = closePrework.then(() => this._setupBrowserContext(options));
|
||||
this._browserContextPromise.catch(() => {
|
||||
this._browserContextPromise = void 0;
|
||||
this._browserContextOption = void 0;
|
||||
});
|
||||
this._browserContextOption = options;
|
||||
return this._browserContextPromise;
|
||||
}
|
||||
async _setupBrowserContext(options) {
|
||||
if (this._closeBrowserContextPromise)
|
||||
throw new Error("Another browser context is being closed.");
|
||||
if (this.config.testIdAttribute)
|
||||
import_playwright_core.selectors.setTestIdAttribute(this.config.testIdAttribute);
|
||||
const result = await this._browserContextFactory.createContext(this._clientInfo, this._abortController.signal, { toolName: this._runningToolName, ...options });
|
||||
const { browserContext } = result;
|
||||
if (!this.config.allowUnrestrictedFileAccess) {
|
||||
browserContext._setAllowedProtocols(["http:", "https:", "about:", "data:"]);
|
||||
browserContext._setAllowedDirectories(allRootPaths(this._clientInfo));
|
||||
}
|
||||
await this._setupRequestInterception(browserContext);
|
||||
for (const page of browserContext.pages())
|
||||
this._onPageCreated(page);
|
||||
browserContext.on("page", (page) => this._onPageCreated(page));
|
||||
if (this.config.saveTrace) {
|
||||
await browserContext.tracing.start({
|
||||
name: "trace-" + Date.now(),
|
||||
screenshots: true,
|
||||
snapshots: true,
|
||||
_live: true
|
||||
});
|
||||
}
|
||||
return result;
|
||||
}
|
||||
lookupSecret(secretName) {
|
||||
if (!this.config.secrets?.[secretName])
|
||||
return { value: secretName, code: (0, import_utils.escapeWithQuotes)(secretName, "'") };
|
||||
return {
|
||||
value: this.config.secrets[secretName],
|
||||
code: `process.env['${secretName}']`
|
||||
};
|
||||
}
|
||||
firstRootPath() {
|
||||
return allRootPaths(this._clientInfo)[0];
|
||||
}
|
||||
}
|
||||
function allRootPaths(clientInfo) {
|
||||
const paths = [];
|
||||
for (const root of clientInfo.roots) {
|
||||
const url = new URL(root.uri);
|
||||
let rootPath;
|
||||
try {
|
||||
rootPath = (0, import_url.fileURLToPath)(url);
|
||||
} catch (e) {
|
||||
if (e.code === "ERR_INVALID_FILE_URL_PATH" && import_os.default.platform() === "win32")
|
||||
rootPath = decodeURIComponent(url.pathname);
|
||||
}
|
||||
if (!rootPath)
|
||||
continue;
|
||||
paths.push(rootPath);
|
||||
}
|
||||
if (paths.length === 0)
|
||||
paths.push(process.cwd());
|
||||
return paths;
|
||||
}
|
||||
function originOrHostGlob(originOrHost) {
|
||||
try {
|
||||
const url = new URL(originOrHost);
|
||||
if (url.origin !== "null")
|
||||
return `${url.origin}/**`;
|
||||
} catch {
|
||||
}
|
||||
return `*://${originOrHost}/**`;
|
||||
}
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
Context
|
||||
});
|
||||
278
backend/node_modules/playwright/lib/mcp/browser/response.js
generated
vendored
Normal file
278
backend/node_modules/playwright/lib/mcp/browser/response.js
generated
vendored
Normal file
|
|
@ -0,0 +1,278 @@
|
|||
"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 response_exports = {};
|
||||
__export(response_exports, {
|
||||
Response: () => Response,
|
||||
parseResponse: () => parseResponse,
|
||||
renderTabMarkdown: () => renderTabMarkdown,
|
||||
renderTabsMarkdown: () => renderTabsMarkdown,
|
||||
requestDebug: () => requestDebug
|
||||
});
|
||||
module.exports = __toCommonJS(response_exports);
|
||||
var import_fs = __toESM(require("fs"));
|
||||
var import_path = __toESM(require("path"));
|
||||
var import_utilsBundle = require("playwright-core/lib/utilsBundle");
|
||||
var import_tab = require("./tab");
|
||||
var import_utils = require("./tools/utils");
|
||||
const requestDebug = (0, import_utilsBundle.debug)("pw:mcp:request");
|
||||
class Response {
|
||||
constructor(ordinal, context, toolName, toolArgs) {
|
||||
this._results = [];
|
||||
this._errors = [];
|
||||
this._code = [];
|
||||
this._images = [];
|
||||
this._includeSnapshot = "none";
|
||||
this._ordinal = ordinal;
|
||||
this._context = context;
|
||||
this.toolName = toolName;
|
||||
this.toolArgs = toolArgs;
|
||||
}
|
||||
static {
|
||||
this._ordinal = 0;
|
||||
}
|
||||
static create(context, toolName, toolArgs) {
|
||||
return new Response(++Response._ordinal, context, toolName, toolArgs);
|
||||
}
|
||||
addTextResult(result) {
|
||||
this._results.push({ text: result });
|
||||
}
|
||||
async addResult(result) {
|
||||
if (result.data && !result.suggestedFilename)
|
||||
result.suggestedFilename = (0, import_utils.dateAsFileName)(result.ext ?? "bin");
|
||||
if (this._context.config.outputMode === "file") {
|
||||
if (!result.suggestedFilename)
|
||||
result.suggestedFilename = (0, import_utils.dateAsFileName)(result.ext ?? (result.text ? "txt" : "bin"));
|
||||
}
|
||||
const entry = { text: result.text, data: result.data, title: result.title };
|
||||
if (result.suggestedFilename)
|
||||
entry.filename = await this._context.outputFile(result.suggestedFilename, { origin: "llm", title: result.title ?? "Saved result" });
|
||||
this._results.push(entry);
|
||||
return { fileName: entry.filename };
|
||||
}
|
||||
addError(error) {
|
||||
this._errors.push(error);
|
||||
}
|
||||
addCode(code) {
|
||||
this._code.push(code);
|
||||
}
|
||||
addImage(image) {
|
||||
this._images.push(image);
|
||||
}
|
||||
setIncludeSnapshot() {
|
||||
this._includeSnapshot = this._context.config.snapshot.mode;
|
||||
}
|
||||
setIncludeFullSnapshot(includeSnapshotFileName) {
|
||||
this._includeSnapshot = "full";
|
||||
this._includeSnapshotFileName = includeSnapshotFileName;
|
||||
}
|
||||
async build() {
|
||||
const rootPath = this._context.firstRootPath();
|
||||
const sections = [];
|
||||
const addSection = (title) => {
|
||||
const section = { title, content: [] };
|
||||
sections.push(section);
|
||||
return section.content;
|
||||
};
|
||||
if (this._errors.length) {
|
||||
const text = addSection("Error");
|
||||
text.push("### Error");
|
||||
text.push(this._errors.join("\n"));
|
||||
}
|
||||
if (this._results.length) {
|
||||
const text = addSection("Result");
|
||||
for (const result of this._results) {
|
||||
if (result.filename) {
|
||||
text.push(`- [${result.title}](${rootPath ? import_path.default.relative(rootPath, result.filename) : result.filename})`);
|
||||
if (result.data)
|
||||
await import_fs.default.promises.writeFile(result.filename, result.data);
|
||||
else if (result.text)
|
||||
await import_fs.default.promises.writeFile(result.filename, this._redactText(result.text));
|
||||
} else if (result.text) {
|
||||
text.push(result.text);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (this._context.config.codegen !== "none" && this._code.length) {
|
||||
const text = addSection("Ran Playwright code");
|
||||
text.push(...this._code);
|
||||
}
|
||||
const tabSnapshot = this._context.currentTab() ? await this._context.currentTabOrDie().captureSnapshot() : void 0;
|
||||
const tabHeaders = await Promise.all(this._context.tabs().map((tab) => tab.headerSnapshot()));
|
||||
if (tabHeaders.some((header) => header.changed)) {
|
||||
if (tabHeaders.length !== 1) {
|
||||
const text2 = addSection("Open tabs");
|
||||
text2.push(...renderTabsMarkdown(tabHeaders));
|
||||
}
|
||||
const text = addSection("Page");
|
||||
text.push(...renderTabMarkdown(tabHeaders[0]));
|
||||
}
|
||||
if (tabSnapshot?.modalStates.length) {
|
||||
const text = addSection("Modal state");
|
||||
text.push(...(0, import_tab.renderModalStates)(tabSnapshot.modalStates));
|
||||
}
|
||||
if (tabSnapshot && this._includeSnapshot === "full") {
|
||||
let fileName;
|
||||
if (this._includeSnapshotFileName)
|
||||
fileName = await this._context.outputFile(this._includeSnapshotFileName, { origin: "llm", title: "Saved snapshot" });
|
||||
else if (this._context.config.outputMode === "file")
|
||||
fileName = await this._context.outputFile(`snapshot-${this._ordinal}.yml`, { origin: "code", title: "Saved snapshot" });
|
||||
if (fileName) {
|
||||
await import_fs.default.promises.writeFile(fileName, tabSnapshot.ariaSnapshot);
|
||||
const text = addSection("Snapshot");
|
||||
text.push(`- File: ${rootPath ? import_path.default.relative(rootPath, fileName) : fileName}`);
|
||||
} else {
|
||||
const text = addSection("Snapshot");
|
||||
text.push("```yaml");
|
||||
text.push(tabSnapshot.ariaSnapshot);
|
||||
text.push("```");
|
||||
}
|
||||
}
|
||||
if (tabSnapshot && this._includeSnapshot === "incremental") {
|
||||
const text = addSection("Snapshot");
|
||||
text.push("```yaml");
|
||||
if (tabSnapshot.ariaSnapshotDiff !== void 0)
|
||||
text.push(tabSnapshot.ariaSnapshotDiff);
|
||||
else
|
||||
text.push(tabSnapshot.ariaSnapshot);
|
||||
text.push("```");
|
||||
}
|
||||
if (tabSnapshot?.events.filter((event) => event.type !== "request").length) {
|
||||
const text = addSection("Events");
|
||||
for (const event of tabSnapshot.events) {
|
||||
if (event.type === "console") {
|
||||
if ((0, import_tab.shouldIncludeMessage)(this._context.config.console.level, event.message.type))
|
||||
text.push(`- ${trimMiddle(event.message.toString(), 100)}`);
|
||||
} else if (event.type === "download-start") {
|
||||
text.push(`- Downloading file ${event.download.download.suggestedFilename()} ...`);
|
||||
} else if (event.type === "download-finish") {
|
||||
text.push(`- Downloaded file ${event.download.download.suggestedFilename()} to "${rootPath ? import_path.default.relative(rootPath, event.download.outputFile) : event.download.outputFile}"`);
|
||||
}
|
||||
}
|
||||
}
|
||||
const allText = sections.flatMap((section) => {
|
||||
const content2 = [];
|
||||
content2.push(`### ${section.title}`);
|
||||
content2.push(...section.content);
|
||||
content2.push("");
|
||||
return content2;
|
||||
}).join("\n");
|
||||
const content = [
|
||||
{
|
||||
type: "text",
|
||||
text: this._redactText(allText)
|
||||
}
|
||||
];
|
||||
if (this._context.config.imageResponses !== "omit") {
|
||||
for (const image of this._images)
|
||||
content.push({ type: "image", data: image.data.toString("base64"), mimeType: image.contentType });
|
||||
}
|
||||
return {
|
||||
content,
|
||||
...this._errors.length > 0 ? { isError: true } : {}
|
||||
};
|
||||
}
|
||||
_redactText(text) {
|
||||
for (const [secretName, secretValue] of Object.entries(this._context.config.secrets ?? {}))
|
||||
text = text.replaceAll(secretValue, `<secret>${secretName}</secret>`);
|
||||
return text;
|
||||
}
|
||||
}
|
||||
function renderTabMarkdown(tab) {
|
||||
const lines = [`- Page URL: ${tab.url}`];
|
||||
if (tab.title)
|
||||
lines.push(`- Page Title: ${tab.title}`);
|
||||
return lines;
|
||||
}
|
||||
function renderTabsMarkdown(tabs) {
|
||||
if (!tabs.length)
|
||||
return ['No open tabs. Use the "browser_navigate" tool to navigate to a page first.'];
|
||||
const lines = [];
|
||||
for (let i = 0; i < tabs.length; i++) {
|
||||
const tab = tabs[i];
|
||||
const current = tab.current ? " (current)" : "";
|
||||
lines.push(`- ${i}:${current} [${tab.title}](${tab.url})`);
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
function trimMiddle(text, maxLength) {
|
||||
if (text.length <= maxLength)
|
||||
return text;
|
||||
return text.slice(0, Math.floor(maxLength / 2)) + "..." + text.slice(-3 - Math.floor(maxLength / 2));
|
||||
}
|
||||
function parseSections(text) {
|
||||
const sections = /* @__PURE__ */ new Map();
|
||||
const sectionHeaders = text.split(/^### /m).slice(1);
|
||||
for (const section of sectionHeaders) {
|
||||
const firstNewlineIndex = section.indexOf("\n");
|
||||
if (firstNewlineIndex === -1)
|
||||
continue;
|
||||
const sectionName = section.substring(0, firstNewlineIndex);
|
||||
const sectionContent = section.substring(firstNewlineIndex + 1).trim();
|
||||
sections.set(sectionName, sectionContent);
|
||||
}
|
||||
return sections;
|
||||
}
|
||||
function parseResponse(response) {
|
||||
if (response.content?.[0].type !== "text")
|
||||
return void 0;
|
||||
const text = response.content[0].text;
|
||||
const sections = parseSections(text);
|
||||
const error = sections.get("Error");
|
||||
const result = sections.get("Result");
|
||||
const code = sections.get("Ran Playwright code");
|
||||
const tabs = sections.get("Open tabs");
|
||||
const page = sections.get("Page");
|
||||
const snapshot = sections.get("Snapshot");
|
||||
const events = sections.get("Events");
|
||||
const modalState = sections.get("Modal state");
|
||||
const codeNoFrame = code?.replace(/^```js\n/, "").replace(/\n```$/, "");
|
||||
const isError = response.isError;
|
||||
const attachments = response.content.length > 1 ? response.content.slice(1) : void 0;
|
||||
return {
|
||||
result,
|
||||
error,
|
||||
code: codeNoFrame,
|
||||
tabs,
|
||||
page,
|
||||
snapshot,
|
||||
events,
|
||||
modalState,
|
||||
isError,
|
||||
attachments,
|
||||
text
|
||||
};
|
||||
}
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
Response,
|
||||
parseResponse,
|
||||
renderTabMarkdown,
|
||||
renderTabsMarkdown,
|
||||
requestDebug
|
||||
});
|
||||
75
backend/node_modules/playwright/lib/mcp/browser/sessionLog.js
generated
vendored
Normal file
75
backend/node_modules/playwright/lib/mcp/browser/sessionLog.js
generated
vendored
Normal file
|
|
@ -0,0 +1,75 @@
|
|||
"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 sessionLog_exports = {};
|
||||
__export(sessionLog_exports, {
|
||||
SessionLog: () => SessionLog
|
||||
});
|
||||
module.exports = __toCommonJS(sessionLog_exports);
|
||||
var import_fs = __toESM(require("fs"));
|
||||
var import_path = __toESM(require("path"));
|
||||
var import_config = require("./config");
|
||||
var import_response = require("./response");
|
||||
class SessionLog {
|
||||
constructor(sessionFolder) {
|
||||
this._sessionFileQueue = Promise.resolve();
|
||||
this._folder = sessionFolder;
|
||||
this._file = import_path.default.join(this._folder, "session.md");
|
||||
}
|
||||
static async create(config, clientInfo) {
|
||||
const sessionFolder = await (0, import_config.outputFile)(config, clientInfo, `session-${Date.now()}`, { origin: "code", title: "Saving session" });
|
||||
await import_fs.default.promises.mkdir(sessionFolder, { recursive: true });
|
||||
console.error(`Session: ${sessionFolder}`);
|
||||
return new SessionLog(sessionFolder);
|
||||
}
|
||||
logResponse(toolName, toolArgs, responseObject) {
|
||||
const parsed = (0, import_response.parseResponse)(responseObject);
|
||||
if (parsed)
|
||||
delete parsed.text;
|
||||
const lines = [""];
|
||||
lines.push(
|
||||
`### Tool call: ${toolName}`,
|
||||
`- Args`,
|
||||
"```json",
|
||||
JSON.stringify(toolArgs, null, 2),
|
||||
"```"
|
||||
);
|
||||
if (parsed) {
|
||||
lines.push(`- Result`);
|
||||
lines.push("```json");
|
||||
lines.push(JSON.stringify(parsed, null, 2));
|
||||
lines.push("```");
|
||||
}
|
||||
lines.push("");
|
||||
this._sessionFileQueue = this._sessionFileQueue.then(() => import_fs.default.promises.appendFile(this._file, lines.join("\n")));
|
||||
}
|
||||
}
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
SessionLog
|
||||
});
|
||||
343
backend/node_modules/playwright/lib/mcp/browser/tab.js
generated
vendored
Normal file
343
backend/node_modules/playwright/lib/mcp/browser/tab.js
generated
vendored
Normal file
|
|
@ -0,0 +1,343 @@
|
|||
"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 tab_exports = {};
|
||||
__export(tab_exports, {
|
||||
Tab: () => Tab,
|
||||
TabEvents: () => TabEvents,
|
||||
renderModalStates: () => renderModalStates,
|
||||
shouldIncludeMessage: () => shouldIncludeMessage
|
||||
});
|
||||
module.exports = __toCommonJS(tab_exports);
|
||||
var import_events = require("events");
|
||||
var import_utils = require("playwright-core/lib/utils");
|
||||
var import_utils2 = require("./tools/utils");
|
||||
var import_log = require("../log");
|
||||
var import_dialogs = require("./tools/dialogs");
|
||||
var import_files = require("./tools/files");
|
||||
var import_transform = require("../../transform/transform");
|
||||
const TabEvents = {
|
||||
modalState: "modalState"
|
||||
};
|
||||
class Tab extends import_events.EventEmitter {
|
||||
constructor(context, page, onPageClose) {
|
||||
super();
|
||||
this._lastHeader = { title: "about:blank", url: "about:blank", current: false };
|
||||
this._consoleMessages = [];
|
||||
this._downloads = [];
|
||||
this._requests = /* @__PURE__ */ new Set();
|
||||
this._modalStates = [];
|
||||
this._needsFullSnapshot = false;
|
||||
this._eventEntries = [];
|
||||
this._recentEventEntries = [];
|
||||
this.context = context;
|
||||
this.page = page;
|
||||
this._onPageClose = onPageClose;
|
||||
page.on("console", (event) => this._handleConsoleMessage(messageToConsoleMessage(event)));
|
||||
page.on("pageerror", (error) => this._handleConsoleMessage(pageErrorToConsoleMessage(error)));
|
||||
page.on("request", (request) => this._handleRequest(request));
|
||||
page.on("close", () => this._onClose());
|
||||
page.on("filechooser", (chooser) => {
|
||||
this.setModalState({
|
||||
type: "fileChooser",
|
||||
description: "File chooser",
|
||||
fileChooser: chooser,
|
||||
clearedBy: import_files.uploadFile.schema.name
|
||||
});
|
||||
});
|
||||
page.on("dialog", (dialog) => this._dialogShown(dialog));
|
||||
page.on("download", (download) => {
|
||||
void this._downloadStarted(download);
|
||||
});
|
||||
page.setDefaultNavigationTimeout(this.context.config.timeouts.navigation);
|
||||
page.setDefaultTimeout(this.context.config.timeouts.action);
|
||||
page[tabSymbol] = this;
|
||||
this._initializedPromise = this._initialize();
|
||||
}
|
||||
static forPage(page) {
|
||||
return page[tabSymbol];
|
||||
}
|
||||
static async collectConsoleMessages(page) {
|
||||
const result = [];
|
||||
const messages = await page.consoleMessages().catch(() => []);
|
||||
for (const message of messages)
|
||||
result.push(messageToConsoleMessage(message));
|
||||
const errors = await page.pageErrors().catch(() => []);
|
||||
for (const error of errors)
|
||||
result.push(pageErrorToConsoleMessage(error));
|
||||
return result;
|
||||
}
|
||||
async _initialize() {
|
||||
for (const message of await Tab.collectConsoleMessages(this.page))
|
||||
this._handleConsoleMessage(message);
|
||||
const requests = await this.page.requests().catch(() => []);
|
||||
for (const request of requests)
|
||||
this._requests.add(request);
|
||||
for (const initPage of this.context.config.browser.initPage || []) {
|
||||
try {
|
||||
const { default: func } = await (0, import_transform.requireOrImport)(initPage);
|
||||
await func({ page: this.page });
|
||||
} catch (e) {
|
||||
(0, import_log.logUnhandledError)(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
modalStates() {
|
||||
return this._modalStates;
|
||||
}
|
||||
setModalState(modalState) {
|
||||
this._modalStates.push(modalState);
|
||||
this.emit(TabEvents.modalState, modalState);
|
||||
}
|
||||
clearModalState(modalState) {
|
||||
this._modalStates = this._modalStates.filter((state) => state !== modalState);
|
||||
}
|
||||
_dialogShown(dialog) {
|
||||
this.setModalState({
|
||||
type: "dialog",
|
||||
description: `"${dialog.type()}" dialog with message "${dialog.message()}"`,
|
||||
dialog,
|
||||
clearedBy: import_dialogs.handleDialog.schema.name
|
||||
});
|
||||
}
|
||||
async _downloadStarted(download) {
|
||||
const entry = {
|
||||
download,
|
||||
finished: false,
|
||||
outputFile: await this.context.outputFile(download.suggestedFilename(), { origin: "web", title: "Saving download" })
|
||||
};
|
||||
this._downloads.push(entry);
|
||||
this._addLogEntry({ type: "download-start", wallTime: Date.now(), download: entry });
|
||||
await download.saveAs(entry.outputFile);
|
||||
entry.finished = true;
|
||||
this._addLogEntry({ type: "download-finish", wallTime: Date.now(), download: entry });
|
||||
}
|
||||
_clearCollectedArtifacts() {
|
||||
this._consoleMessages.length = 0;
|
||||
this._downloads.length = 0;
|
||||
this._requests.clear();
|
||||
this._eventEntries.length = 0;
|
||||
this._recentEventEntries.length = 0;
|
||||
}
|
||||
_handleRequest(request) {
|
||||
this._requests.add(request);
|
||||
this._addLogEntry({ type: "request", wallTime: Date.now(), request });
|
||||
}
|
||||
_handleConsoleMessage(message) {
|
||||
this._consoleMessages.push(message);
|
||||
this._addLogEntry({ type: "console", wallTime: Date.now(), message });
|
||||
}
|
||||
_addLogEntry(entry) {
|
||||
this._eventEntries.push(entry);
|
||||
this._recentEventEntries.push(entry);
|
||||
}
|
||||
_onClose() {
|
||||
this._clearCollectedArtifacts();
|
||||
this._onPageClose(this);
|
||||
}
|
||||
async headerSnapshot() {
|
||||
let title;
|
||||
await this._raceAgainstModalStates(async () => {
|
||||
title = await (0, import_utils2.callOnPageNoTrace)(this.page, (page) => page.title());
|
||||
});
|
||||
if (this._lastHeader.title !== title || this._lastHeader.url !== this.page.url() || this._lastHeader.current !== this.isCurrentTab()) {
|
||||
this._lastHeader = { title: title ?? "", url: this.page.url(), current: this.isCurrentTab() };
|
||||
return { ...this._lastHeader, changed: true };
|
||||
}
|
||||
return { ...this._lastHeader, changed: false };
|
||||
}
|
||||
isCurrentTab() {
|
||||
return this === this.context.currentTab();
|
||||
}
|
||||
async waitForLoadState(state, options) {
|
||||
await this._initializedPromise;
|
||||
await (0, import_utils2.callOnPageNoTrace)(this.page, (page) => page.waitForLoadState(state, options).catch(import_log.logUnhandledError));
|
||||
}
|
||||
async navigate(url) {
|
||||
await this._initializedPromise;
|
||||
this._clearCollectedArtifacts();
|
||||
const { promise: downloadEvent, abort: abortDownloadEvent } = (0, import_utils2.eventWaiter)(this.page, "download", 3e3);
|
||||
try {
|
||||
await this.page.goto(url, { waitUntil: "domcontentloaded" });
|
||||
abortDownloadEvent();
|
||||
} catch (_e) {
|
||||
const e = _e;
|
||||
const mightBeDownload = e.message.includes("net::ERR_ABORTED") || e.message.includes("Download is starting");
|
||||
if (!mightBeDownload)
|
||||
throw e;
|
||||
const download = await downloadEvent;
|
||||
if (!download)
|
||||
throw e;
|
||||
await new Promise((resolve) => setTimeout(resolve, 500));
|
||||
return;
|
||||
}
|
||||
await this.waitForLoadState("load", { timeout: 5e3 });
|
||||
}
|
||||
async consoleMessages(level) {
|
||||
await this._initializedPromise;
|
||||
return this._consoleMessages.filter((message) => shouldIncludeMessage(level, message.type));
|
||||
}
|
||||
async requests() {
|
||||
await this._initializedPromise;
|
||||
return this._requests;
|
||||
}
|
||||
async captureSnapshot() {
|
||||
await this._initializedPromise;
|
||||
let tabSnapshot;
|
||||
const modalStates = await this._raceAgainstModalStates(async () => {
|
||||
const snapshot = await this.page._snapshotForAI({ track: "response" });
|
||||
tabSnapshot = {
|
||||
ariaSnapshot: snapshot.full,
|
||||
ariaSnapshotDiff: this._needsFullSnapshot ? void 0 : snapshot.incremental,
|
||||
modalStates: [],
|
||||
events: []
|
||||
};
|
||||
});
|
||||
if (tabSnapshot) {
|
||||
tabSnapshot.events = this._recentEventEntries;
|
||||
this._recentEventEntries = [];
|
||||
}
|
||||
this._needsFullSnapshot = !tabSnapshot;
|
||||
return tabSnapshot ?? {
|
||||
ariaSnapshot: "",
|
||||
ariaSnapshotDiff: "",
|
||||
modalStates,
|
||||
events: []
|
||||
};
|
||||
}
|
||||
_javaScriptBlocked() {
|
||||
return this._modalStates.some((state) => state.type === "dialog");
|
||||
}
|
||||
async _raceAgainstModalStates(action) {
|
||||
if (this.modalStates().length)
|
||||
return this.modalStates();
|
||||
const promise = new import_utils.ManualPromise();
|
||||
const listener = (modalState) => promise.resolve([modalState]);
|
||||
this.once(TabEvents.modalState, listener);
|
||||
return await Promise.race([
|
||||
action().then(() => {
|
||||
this.off(TabEvents.modalState, listener);
|
||||
return [];
|
||||
}),
|
||||
promise
|
||||
]);
|
||||
}
|
||||
async waitForCompletion(callback) {
|
||||
await this._initializedPromise;
|
||||
await this._raceAgainstModalStates(() => (0, import_utils2.waitForCompletion)(this, callback));
|
||||
}
|
||||
async refLocator(params) {
|
||||
await this._initializedPromise;
|
||||
return (await this.refLocators([params]))[0];
|
||||
}
|
||||
async refLocators(params) {
|
||||
await this._initializedPromise;
|
||||
return Promise.all(params.map(async (param) => {
|
||||
try {
|
||||
let locator = this.page.locator(`aria-ref=${param.ref}`);
|
||||
if (param.element)
|
||||
locator = locator.describe(param.element);
|
||||
const { resolvedSelector } = await locator._resolveSelector();
|
||||
return { locator, resolved: (0, import_utils.asLocator)("javascript", resolvedSelector) };
|
||||
} catch (e) {
|
||||
throw new Error(`Ref ${param.ref} not found in the current page snapshot. Try capturing new snapshot.`);
|
||||
}
|
||||
}));
|
||||
}
|
||||
async waitForTimeout(time) {
|
||||
if (this._javaScriptBlocked()) {
|
||||
await new Promise((f) => setTimeout(f, time));
|
||||
return;
|
||||
}
|
||||
await (0, import_utils2.callOnPageNoTrace)(this.page, (page) => {
|
||||
return page.evaluate(() => new Promise((f) => setTimeout(f, 1e3))).catch(() => {
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
function messageToConsoleMessage(message) {
|
||||
return {
|
||||
type: message.type(),
|
||||
text: message.text(),
|
||||
toString: () => `[${message.type().toUpperCase()}] ${message.text()} @ ${message.location().url}:${message.location().lineNumber}`
|
||||
};
|
||||
}
|
||||
function pageErrorToConsoleMessage(errorOrValue) {
|
||||
if (errorOrValue instanceof Error) {
|
||||
return {
|
||||
type: "error",
|
||||
text: errorOrValue.message,
|
||||
toString: () => errorOrValue.stack || errorOrValue.message
|
||||
};
|
||||
}
|
||||
return {
|
||||
type: "error",
|
||||
text: String(errorOrValue),
|
||||
toString: () => String(errorOrValue)
|
||||
};
|
||||
}
|
||||
function renderModalStates(modalStates) {
|
||||
const result = [];
|
||||
if (modalStates.length === 0)
|
||||
result.push("- There is no modal state present");
|
||||
for (const state of modalStates)
|
||||
result.push(`- [${state.description}]: can be handled by the "${state.clearedBy}" tool`);
|
||||
return result;
|
||||
}
|
||||
const consoleMessageLevels = ["error", "warning", "info", "debug"];
|
||||
function shouldIncludeMessage(thresholdLevel, type) {
|
||||
const messageLevel = consoleLevelForMessageType(type);
|
||||
return consoleMessageLevels.indexOf(messageLevel) <= consoleMessageLevels.indexOf(thresholdLevel);
|
||||
}
|
||||
function consoleLevelForMessageType(type) {
|
||||
switch (type) {
|
||||
case "assert":
|
||||
case "error":
|
||||
return "error";
|
||||
case "warning":
|
||||
return "warning";
|
||||
case "count":
|
||||
case "dir":
|
||||
case "dirxml":
|
||||
case "info":
|
||||
case "log":
|
||||
case "table":
|
||||
case "time":
|
||||
case "timeEnd":
|
||||
return "info";
|
||||
case "clear":
|
||||
case "debug":
|
||||
case "endGroup":
|
||||
case "profile":
|
||||
case "profileEnd":
|
||||
case "startGroup":
|
||||
case "startGroupCollapsed":
|
||||
case "trace":
|
||||
return "debug";
|
||||
default:
|
||||
return "info";
|
||||
}
|
||||
}
|
||||
const tabSymbol = Symbol("tabSymbol");
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
Tab,
|
||||
TabEvents,
|
||||
renderModalStates,
|
||||
shouldIncludeMessage
|
||||
});
|
||||
84
backend/node_modules/playwright/lib/mcp/browser/tools.js
generated
vendored
Normal file
84
backend/node_modules/playwright/lib/mcp/browser/tools.js
generated
vendored
Normal file
|
|
@ -0,0 +1,84 @@
|
|||
"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 tools_exports = {};
|
||||
__export(tools_exports, {
|
||||
browserTools: () => browserTools,
|
||||
filteredTools: () => filteredTools
|
||||
});
|
||||
module.exports = __toCommonJS(tools_exports);
|
||||
var import_common = __toESM(require("./tools/common"));
|
||||
var import_console = __toESM(require("./tools/console"));
|
||||
var import_dialogs = __toESM(require("./tools/dialogs"));
|
||||
var import_evaluate = __toESM(require("./tools/evaluate"));
|
||||
var import_files = __toESM(require("./tools/files"));
|
||||
var import_form = __toESM(require("./tools/form"));
|
||||
var import_install = __toESM(require("./tools/install"));
|
||||
var import_keyboard = __toESM(require("./tools/keyboard"));
|
||||
var import_mouse = __toESM(require("./tools/mouse"));
|
||||
var import_navigate = __toESM(require("./tools/navigate"));
|
||||
var import_network = __toESM(require("./tools/network"));
|
||||
var import_open = __toESM(require("./tools/open"));
|
||||
var import_pdf = __toESM(require("./tools/pdf"));
|
||||
var import_runCode = __toESM(require("./tools/runCode"));
|
||||
var import_snapshot = __toESM(require("./tools/snapshot"));
|
||||
var import_screenshot = __toESM(require("./tools/screenshot"));
|
||||
var import_tabs = __toESM(require("./tools/tabs"));
|
||||
var import_tracing = __toESM(require("./tools/tracing"));
|
||||
var import_wait = __toESM(require("./tools/wait"));
|
||||
var import_verify = __toESM(require("./tools/verify"));
|
||||
const browserTools = [
|
||||
...import_common.default,
|
||||
...import_console.default,
|
||||
...import_dialogs.default,
|
||||
...import_evaluate.default,
|
||||
...import_files.default,
|
||||
...import_form.default,
|
||||
...import_install.default,
|
||||
...import_keyboard.default,
|
||||
...import_mouse.default,
|
||||
...import_navigate.default,
|
||||
...import_network.default,
|
||||
...import_open.default,
|
||||
...import_pdf.default,
|
||||
...import_runCode.default,
|
||||
...import_screenshot.default,
|
||||
...import_snapshot.default,
|
||||
...import_tabs.default,
|
||||
...import_tracing.default,
|
||||
...import_wait.default,
|
||||
...import_verify.default
|
||||
];
|
||||
function filteredTools(config) {
|
||||
return browserTools.filter((tool) => tool.capability.startsWith("core") || config.capabilities?.includes(tool.capability));
|
||||
}
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
browserTools,
|
||||
filteredTools
|
||||
});
|
||||
65
backend/node_modules/playwright/lib/mcp/browser/tools/common.js
generated
vendored
Normal file
65
backend/node_modules/playwright/lib/mcp/browser/tools/common.js
generated
vendored
Normal file
|
|
@ -0,0 +1,65 @@
|
|||
"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 common_exports = {};
|
||||
__export(common_exports, {
|
||||
default: () => common_default
|
||||
});
|
||||
module.exports = __toCommonJS(common_exports);
|
||||
var import_mcpBundle = require("playwright-core/lib/mcpBundle");
|
||||
var import_tool = require("./tool");
|
||||
var import_response = require("../response");
|
||||
const close = (0, import_tool.defineTool)({
|
||||
capability: "core",
|
||||
schema: {
|
||||
name: "browser_close",
|
||||
title: "Close browser",
|
||||
description: "Close the page",
|
||||
inputSchema: import_mcpBundle.z.object({}),
|
||||
type: "action"
|
||||
},
|
||||
handle: async (context, params, response) => {
|
||||
await context.closeBrowserContext();
|
||||
const result = (0, import_response.renderTabsMarkdown)([]);
|
||||
response.addTextResult(result.join("\n"));
|
||||
response.addCode(`await page.close()`);
|
||||
}
|
||||
});
|
||||
const resize = (0, import_tool.defineTabTool)({
|
||||
capability: "core",
|
||||
schema: {
|
||||
name: "browser_resize",
|
||||
title: "Resize browser window",
|
||||
description: "Resize the browser window",
|
||||
inputSchema: import_mcpBundle.z.object({
|
||||
width: import_mcpBundle.z.number().describe("Width of the browser window"),
|
||||
height: import_mcpBundle.z.number().describe("Height of the browser window")
|
||||
}),
|
||||
type: "action"
|
||||
},
|
||||
handle: async (tab, params, response) => {
|
||||
response.addCode(`await page.setViewportSize({ width: ${params.width}, height: ${params.height} });`);
|
||||
await tab.waitForCompletion(async () => {
|
||||
await tab.page.setViewportSize({ width: params.width, height: params.height });
|
||||
});
|
||||
}
|
||||
});
|
||||
var common_default = [
|
||||
close,
|
||||
resize
|
||||
];
|
||||
46
backend/node_modules/playwright/lib/mcp/browser/tools/console.js
generated
vendored
Normal file
46
backend/node_modules/playwright/lib/mcp/browser/tools/console.js
generated
vendored
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
"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 console_exports = {};
|
||||
__export(console_exports, {
|
||||
default: () => console_default
|
||||
});
|
||||
module.exports = __toCommonJS(console_exports);
|
||||
var import_mcpBundle = require("playwright-core/lib/mcpBundle");
|
||||
var import_tool = require("./tool");
|
||||
const console = (0, import_tool.defineTabTool)({
|
||||
capability: "core",
|
||||
schema: {
|
||||
name: "browser_console_messages",
|
||||
title: "Get console messages",
|
||||
description: "Returns all console messages",
|
||||
inputSchema: import_mcpBundle.z.object({
|
||||
level: import_mcpBundle.z.enum(["error", "warning", "info", "debug"]).default("info").describe('Level of the console messages to return. Each level includes the messages of more severe levels. Defaults to "info".'),
|
||||
filename: import_mcpBundle.z.string().optional().describe("Filename to save the console messages to. If not provided, messages are returned as text.")
|
||||
}),
|
||||
type: "readOnly"
|
||||
},
|
||||
handle: async (tab, params, response) => {
|
||||
const messages = await tab.consoleMessages(params.level);
|
||||
const text = messages.map((message) => message.toString()).join("\n");
|
||||
await response.addResult({ text, suggestedFilename: params.filename });
|
||||
}
|
||||
});
|
||||
var console_default = [
|
||||
console
|
||||
];
|
||||
60
backend/node_modules/playwright/lib/mcp/browser/tools/dialogs.js
generated
vendored
Normal file
60
backend/node_modules/playwright/lib/mcp/browser/tools/dialogs.js
generated
vendored
Normal file
|
|
@ -0,0 +1,60 @@
|
|||
"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 dialogs_exports = {};
|
||||
__export(dialogs_exports, {
|
||||
default: () => dialogs_default,
|
||||
handleDialog: () => handleDialog
|
||||
});
|
||||
module.exports = __toCommonJS(dialogs_exports);
|
||||
var import_mcpBundle = require("playwright-core/lib/mcpBundle");
|
||||
var import_tool = require("./tool");
|
||||
const handleDialog = (0, import_tool.defineTabTool)({
|
||||
capability: "core",
|
||||
schema: {
|
||||
name: "browser_handle_dialog",
|
||||
title: "Handle a dialog",
|
||||
description: "Handle a dialog",
|
||||
inputSchema: import_mcpBundle.z.object({
|
||||
accept: import_mcpBundle.z.boolean().describe("Whether to accept the dialog."),
|
||||
promptText: import_mcpBundle.z.string().optional().describe("The text of the prompt in case of a prompt dialog.")
|
||||
}),
|
||||
type: "action"
|
||||
},
|
||||
handle: async (tab, params, response) => {
|
||||
response.setIncludeSnapshot();
|
||||
const dialogState = tab.modalStates().find((state) => state.type === "dialog");
|
||||
if (!dialogState)
|
||||
throw new Error("No dialog visible");
|
||||
tab.clearModalState(dialogState);
|
||||
await tab.waitForCompletion(async () => {
|
||||
if (params.accept)
|
||||
await dialogState.dialog.accept(params.promptText);
|
||||
else
|
||||
await dialogState.dialog.dismiss();
|
||||
});
|
||||
},
|
||||
clearsModalState: "dialog"
|
||||
});
|
||||
var dialogs_default = [
|
||||
handleDialog
|
||||
];
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
handleDialog
|
||||
});
|
||||
61
backend/node_modules/playwright/lib/mcp/browser/tools/evaluate.js
generated
vendored
Normal file
61
backend/node_modules/playwright/lib/mcp/browser/tools/evaluate.js
generated
vendored
Normal file
|
|
@ -0,0 +1,61 @@
|
|||
"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 evaluate_exports = {};
|
||||
__export(evaluate_exports, {
|
||||
default: () => evaluate_default
|
||||
});
|
||||
module.exports = __toCommonJS(evaluate_exports);
|
||||
var import_mcpBundle = require("playwright-core/lib/mcpBundle");
|
||||
var import_utils = require("playwright-core/lib/utils");
|
||||
var import_tool = require("./tool");
|
||||
const evaluateSchema = import_mcpBundle.z.object({
|
||||
function: import_mcpBundle.z.string().describe("() => { /* code */ } or (element) => { /* code */ } when element is provided"),
|
||||
element: import_mcpBundle.z.string().optional().describe("Human-readable element description used to obtain permission to interact with the element"),
|
||||
ref: import_mcpBundle.z.string().optional().describe("Exact target element reference from the page snapshot"),
|
||||
filename: import_mcpBundle.z.string().optional().describe("Filename to save the result to. If not provided, result is returned as JSON string.")
|
||||
});
|
||||
const evaluate = (0, import_tool.defineTabTool)({
|
||||
capability: "core",
|
||||
schema: {
|
||||
name: "browser_evaluate",
|
||||
title: "Evaluate JavaScript",
|
||||
description: "Evaluate JavaScript expression on page or element",
|
||||
inputSchema: evaluateSchema,
|
||||
type: "action"
|
||||
},
|
||||
handle: async (tab, params, response) => {
|
||||
response.setIncludeSnapshot();
|
||||
let locator;
|
||||
if (params.ref && params.element) {
|
||||
locator = await tab.refLocator({ ref: params.ref, element: params.element });
|
||||
response.addCode(`await page.${locator.resolved}.evaluate(${(0, import_utils.escapeWithQuotes)(params.function)});`);
|
||||
} else {
|
||||
response.addCode(`await page.evaluate(${(0, import_utils.escapeWithQuotes)(params.function)});`);
|
||||
}
|
||||
await tab.waitForCompletion(async () => {
|
||||
const receiver = locator?.locator ?? tab.page;
|
||||
const result = await receiver._evaluateFunction(params.function);
|
||||
const text = JSON.stringify(result, null, 2) || "undefined";
|
||||
await response.addResult({ text, suggestedFilename: params.filename });
|
||||
});
|
||||
}
|
||||
});
|
||||
var evaluate_default = [
|
||||
evaluate
|
||||
];
|
||||
58
backend/node_modules/playwright/lib/mcp/browser/tools/files.js
generated
vendored
Normal file
58
backend/node_modules/playwright/lib/mcp/browser/tools/files.js
generated
vendored
Normal 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 files_exports = {};
|
||||
__export(files_exports, {
|
||||
default: () => files_default,
|
||||
uploadFile: () => uploadFile
|
||||
});
|
||||
module.exports = __toCommonJS(files_exports);
|
||||
var import_mcpBundle = require("playwright-core/lib/mcpBundle");
|
||||
var import_tool = require("./tool");
|
||||
const uploadFile = (0, import_tool.defineTabTool)({
|
||||
capability: "core",
|
||||
schema: {
|
||||
name: "browser_file_upload",
|
||||
title: "Upload files",
|
||||
description: "Upload one or multiple files",
|
||||
inputSchema: import_mcpBundle.z.object({
|
||||
paths: import_mcpBundle.z.array(import_mcpBundle.z.string()).optional().describe("The absolute paths to the files to upload. Can be single file or multiple files. If omitted, file chooser is cancelled.")
|
||||
}),
|
||||
type: "action"
|
||||
},
|
||||
handle: async (tab, params, response) => {
|
||||
response.setIncludeSnapshot();
|
||||
const modalState = tab.modalStates().find((state) => state.type === "fileChooser");
|
||||
if (!modalState)
|
||||
throw new Error("No file chooser visible");
|
||||
response.addCode(`await fileChooser.setFiles(${JSON.stringify(params.paths)})`);
|
||||
tab.clearModalState(modalState);
|
||||
await tab.waitForCompletion(async () => {
|
||||
if (params.paths)
|
||||
await modalState.fileChooser.setFiles(params.paths);
|
||||
});
|
||||
},
|
||||
clearsModalState: "fileChooser"
|
||||
});
|
||||
var files_default = [
|
||||
uploadFile
|
||||
];
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
uploadFile
|
||||
});
|
||||
63
backend/node_modules/playwright/lib/mcp/browser/tools/form.js
generated
vendored
Normal file
63
backend/node_modules/playwright/lib/mcp/browser/tools/form.js
generated
vendored
Normal file
|
|
@ -0,0 +1,63 @@
|
|||
"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 form_exports = {};
|
||||
__export(form_exports, {
|
||||
default: () => form_default
|
||||
});
|
||||
module.exports = __toCommonJS(form_exports);
|
||||
var import_mcpBundle = require("playwright-core/lib/mcpBundle");
|
||||
var import_utils = require("playwright-core/lib/utils");
|
||||
var import_tool = require("./tool");
|
||||
const fillForm = (0, import_tool.defineTabTool)({
|
||||
capability: "core",
|
||||
schema: {
|
||||
name: "browser_fill_form",
|
||||
title: "Fill form",
|
||||
description: "Fill multiple form fields",
|
||||
inputSchema: import_mcpBundle.z.object({
|
||||
fields: import_mcpBundle.z.array(import_mcpBundle.z.object({
|
||||
name: import_mcpBundle.z.string().describe("Human-readable field name"),
|
||||
type: import_mcpBundle.z.enum(["textbox", "checkbox", "radio", "combobox", "slider"]).describe("Type of the field"),
|
||||
ref: import_mcpBundle.z.string().describe("Exact target field reference from the page snapshot"),
|
||||
value: import_mcpBundle.z.string().describe("Value to fill in the field. If the field is a checkbox, the value should be `true` or `false`. If the field is a combobox, the value should be the text of the option.")
|
||||
})).describe("Fields to fill in")
|
||||
}),
|
||||
type: "input"
|
||||
},
|
||||
handle: async (tab, params, response) => {
|
||||
for (const field of params.fields) {
|
||||
const { locator, resolved } = await tab.refLocator({ element: field.name, ref: field.ref });
|
||||
const locatorSource = `await page.${resolved}`;
|
||||
if (field.type === "textbox" || field.type === "slider") {
|
||||
const secret = tab.context.lookupSecret(field.value);
|
||||
await locator.fill(secret.value);
|
||||
response.addCode(`${locatorSource}.fill(${secret.code});`);
|
||||
} else if (field.type === "checkbox" || field.type === "radio") {
|
||||
await locator.setChecked(field.value === "true");
|
||||
response.addCode(`${locatorSource}.setChecked(${field.value});`);
|
||||
} else if (field.type === "combobox") {
|
||||
await locator.selectOption({ label: field.value });
|
||||
response.addCode(`${locatorSource}.selectOption(${(0, import_utils.escapeWithQuotes)(field.value)});`);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
var form_default = [
|
||||
fillForm
|
||||
];
|
||||
72
backend/node_modules/playwright/lib/mcp/browser/tools/install.js
generated
vendored
Normal file
72
backend/node_modules/playwright/lib/mcp/browser/tools/install.js
generated
vendored
Normal file
|
|
@ -0,0 +1,72 @@
|
|||
"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 install_exports = {};
|
||||
__export(install_exports, {
|
||||
default: () => install_default
|
||||
});
|
||||
module.exports = __toCommonJS(install_exports);
|
||||
var import_child_process = require("child_process");
|
||||
var import_path = __toESM(require("path"));
|
||||
var import_mcpBundle = require("playwright-core/lib/mcpBundle");
|
||||
var import_tool = require("./tool");
|
||||
var import_response = require("../response");
|
||||
const install = (0, import_tool.defineTool)({
|
||||
capability: "core-install",
|
||||
schema: {
|
||||
name: "browser_install",
|
||||
title: "Install the browser specified in the config",
|
||||
description: "Install the browser specified in the config. Call this if you get an error about the browser not being installed.",
|
||||
inputSchema: import_mcpBundle.z.object({}),
|
||||
type: "action"
|
||||
},
|
||||
handle: async (context, params, response) => {
|
||||
const channel = context.config.browser?.launchOptions?.channel ?? context.config.browser?.browserName ?? "chrome";
|
||||
const cliPath = import_path.default.join(require.resolve("playwright/package.json"), "../cli.js");
|
||||
const child = (0, import_child_process.fork)(cliPath, ["install", channel], {
|
||||
stdio: "pipe"
|
||||
});
|
||||
const output = [];
|
||||
child.stdout?.on("data", (data) => output.push(data.toString()));
|
||||
child.stderr?.on("data", (data) => output.push(data.toString()));
|
||||
await new Promise((resolve, reject) => {
|
||||
child.on("close", (code) => {
|
||||
if (code === 0)
|
||||
resolve();
|
||||
else
|
||||
reject(new Error(`Failed to install browser: ${output.join("")}`));
|
||||
});
|
||||
});
|
||||
const tabHeaders = await Promise.all(context.tabs().map((tab) => tab.headerSnapshot()));
|
||||
const result = (0, import_response.renderTabsMarkdown)(tabHeaders);
|
||||
response.addTextResult(result.join("\n"));
|
||||
}
|
||||
});
|
||||
var install_default = [
|
||||
install
|
||||
];
|
||||
107
backend/node_modules/playwright/lib/mcp/browser/tools/keyboard.js
generated
vendored
Normal file
107
backend/node_modules/playwright/lib/mcp/browser/tools/keyboard.js
generated
vendored
Normal file
|
|
@ -0,0 +1,107 @@
|
|||
"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 keyboard_exports = {};
|
||||
__export(keyboard_exports, {
|
||||
default: () => keyboard_default
|
||||
});
|
||||
module.exports = __toCommonJS(keyboard_exports);
|
||||
var import_mcpBundle = require("playwright-core/lib/mcpBundle");
|
||||
var import_tool = require("./tool");
|
||||
var import_snapshot = require("./snapshot");
|
||||
const pressKey = (0, import_tool.defineTabTool)({
|
||||
capability: "core",
|
||||
schema: {
|
||||
name: "browser_press_key",
|
||||
title: "Press a key",
|
||||
description: "Press a key on the keyboard",
|
||||
inputSchema: import_mcpBundle.z.object({
|
||||
key: import_mcpBundle.z.string().describe("Name of the key to press or a character to generate, such as `ArrowLeft` or `a`")
|
||||
}),
|
||||
type: "input"
|
||||
},
|
||||
handle: async (tab, params, response) => {
|
||||
response.addCode(`// Press ${params.key}`);
|
||||
response.addCode(`await page.keyboard.press('${params.key}');`);
|
||||
await tab.page.keyboard.press(params.key);
|
||||
}
|
||||
});
|
||||
const pressSequentially = (0, import_tool.defineTabTool)({
|
||||
capability: "internal",
|
||||
schema: {
|
||||
name: "browser_press_sequentially",
|
||||
title: "Press sequentially",
|
||||
description: "Press text sequentially on the keyboard",
|
||||
inputSchema: import_mcpBundle.z.object({
|
||||
text: import_mcpBundle.z.string().describe("Text to press sequentially"),
|
||||
submit: import_mcpBundle.z.boolean().optional().describe("Whether to submit entered text (press Enter after)")
|
||||
}),
|
||||
type: "input"
|
||||
},
|
||||
handle: async (tab, params, response) => {
|
||||
response.addCode(`// Press ${params.text}`);
|
||||
response.addCode(`await page.keyboard.type('${params.text}');`);
|
||||
await tab.page.keyboard.type(params.text);
|
||||
if (params.submit) {
|
||||
response.addCode(`await page.keyboard.press('Enter');`);
|
||||
response.setIncludeSnapshot();
|
||||
await tab.waitForCompletion(async () => {
|
||||
await tab.page.keyboard.press("Enter");
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
const typeSchema = import_snapshot.elementSchema.extend({
|
||||
text: import_mcpBundle.z.string().describe("Text to type into the element"),
|
||||
submit: import_mcpBundle.z.boolean().optional().describe("Whether to submit entered text (press Enter after)"),
|
||||
slowly: import_mcpBundle.z.boolean().optional().describe("Whether to type one character at a time. Useful for triggering key handlers in the page. By default entire text is filled in at once.")
|
||||
});
|
||||
const type = (0, import_tool.defineTabTool)({
|
||||
capability: "core",
|
||||
schema: {
|
||||
name: "browser_type",
|
||||
title: "Type text",
|
||||
description: "Type text into editable element",
|
||||
inputSchema: typeSchema,
|
||||
type: "input"
|
||||
},
|
||||
handle: async (tab, params, response) => {
|
||||
const { locator, resolved } = await tab.refLocator(params);
|
||||
const secret = tab.context.lookupSecret(params.text);
|
||||
await tab.waitForCompletion(async () => {
|
||||
if (params.slowly) {
|
||||
response.setIncludeSnapshot();
|
||||
response.addCode(`await page.${resolved}.pressSequentially(${secret.code});`);
|
||||
await locator.pressSequentially(secret.value);
|
||||
} else {
|
||||
response.addCode(`await page.${resolved}.fill(${secret.code});`);
|
||||
await locator.fill(secret.value);
|
||||
}
|
||||
if (params.submit) {
|
||||
response.setIncludeSnapshot();
|
||||
response.addCode(`await page.${resolved}.press('Enter');`);
|
||||
await locator.press("Enter");
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
var keyboard_default = [
|
||||
pressKey,
|
||||
type,
|
||||
pressSequentially
|
||||
];
|
||||
107
backend/node_modules/playwright/lib/mcp/browser/tools/mouse.js
generated
vendored
Normal file
107
backend/node_modules/playwright/lib/mcp/browser/tools/mouse.js
generated
vendored
Normal file
|
|
@ -0,0 +1,107 @@
|
|||
"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 mouse_exports = {};
|
||||
__export(mouse_exports, {
|
||||
default: () => mouse_default
|
||||
});
|
||||
module.exports = __toCommonJS(mouse_exports);
|
||||
var import_mcpBundle = require("playwright-core/lib/mcpBundle");
|
||||
var import_tool = require("./tool");
|
||||
const elementSchema = import_mcpBundle.z.object({
|
||||
element: import_mcpBundle.z.string().describe("Human-readable element description used to obtain permission to interact with the element")
|
||||
});
|
||||
const mouseMove = (0, import_tool.defineTabTool)({
|
||||
capability: "vision",
|
||||
schema: {
|
||||
name: "browser_mouse_move_xy",
|
||||
title: "Move mouse",
|
||||
description: "Move mouse to a given position",
|
||||
inputSchema: elementSchema.extend({
|
||||
x: import_mcpBundle.z.number().describe("X coordinate"),
|
||||
y: import_mcpBundle.z.number().describe("Y coordinate")
|
||||
}),
|
||||
type: "input"
|
||||
},
|
||||
handle: async (tab, params, response) => {
|
||||
response.addCode(`// Move mouse to (${params.x}, ${params.y})`);
|
||||
response.addCode(`await page.mouse.move(${params.x}, ${params.y});`);
|
||||
await tab.waitForCompletion(async () => {
|
||||
await tab.page.mouse.move(params.x, params.y);
|
||||
});
|
||||
}
|
||||
});
|
||||
const mouseClick = (0, import_tool.defineTabTool)({
|
||||
capability: "vision",
|
||||
schema: {
|
||||
name: "browser_mouse_click_xy",
|
||||
title: "Click",
|
||||
description: "Click left mouse button at a given position",
|
||||
inputSchema: elementSchema.extend({
|
||||
x: import_mcpBundle.z.number().describe("X coordinate"),
|
||||
y: import_mcpBundle.z.number().describe("Y coordinate")
|
||||
}),
|
||||
type: "input"
|
||||
},
|
||||
handle: async (tab, params, response) => {
|
||||
response.setIncludeSnapshot();
|
||||
response.addCode(`// Click mouse at coordinates (${params.x}, ${params.y})`);
|
||||
response.addCode(`await page.mouse.move(${params.x}, ${params.y});`);
|
||||
response.addCode(`await page.mouse.down();`);
|
||||
response.addCode(`await page.mouse.up();`);
|
||||
await tab.waitForCompletion(async () => {
|
||||
await tab.page.mouse.move(params.x, params.y);
|
||||
await tab.page.mouse.down();
|
||||
await tab.page.mouse.up();
|
||||
});
|
||||
}
|
||||
});
|
||||
const mouseDrag = (0, import_tool.defineTabTool)({
|
||||
capability: "vision",
|
||||
schema: {
|
||||
name: "browser_mouse_drag_xy",
|
||||
title: "Drag mouse",
|
||||
description: "Drag left mouse button to a given position",
|
||||
inputSchema: elementSchema.extend({
|
||||
startX: import_mcpBundle.z.number().describe("Start X coordinate"),
|
||||
startY: import_mcpBundle.z.number().describe("Start Y coordinate"),
|
||||
endX: import_mcpBundle.z.number().describe("End X coordinate"),
|
||||
endY: import_mcpBundle.z.number().describe("End Y coordinate")
|
||||
}),
|
||||
type: "input"
|
||||
},
|
||||
handle: async (tab, params, response) => {
|
||||
response.setIncludeSnapshot();
|
||||
response.addCode(`// Drag mouse from (${params.startX}, ${params.startY}) to (${params.endX}, ${params.endY})`);
|
||||
response.addCode(`await page.mouse.move(${params.startX}, ${params.startY});`);
|
||||
response.addCode(`await page.mouse.down();`);
|
||||
response.addCode(`await page.mouse.move(${params.endX}, ${params.endY});`);
|
||||
response.addCode(`await page.mouse.up();`);
|
||||
await tab.waitForCompletion(async () => {
|
||||
await tab.page.mouse.move(params.startX, params.startY);
|
||||
await tab.page.mouse.down();
|
||||
await tab.page.mouse.move(params.endX, params.endY);
|
||||
await tab.page.mouse.up();
|
||||
});
|
||||
}
|
||||
});
|
||||
var mouse_default = [
|
||||
mouseMove,
|
||||
mouseClick,
|
||||
mouseDrag
|
||||
];
|
||||
71
backend/node_modules/playwright/lib/mcp/browser/tools/navigate.js
generated
vendored
Normal file
71
backend/node_modules/playwright/lib/mcp/browser/tools/navigate.js
generated
vendored
Normal file
|
|
@ -0,0 +1,71 @@
|
|||
"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 navigate_exports = {};
|
||||
__export(navigate_exports, {
|
||||
default: () => navigate_default
|
||||
});
|
||||
module.exports = __toCommonJS(navigate_exports);
|
||||
var import_mcpBundle = require("playwright-core/lib/mcpBundle");
|
||||
var import_tool = require("./tool");
|
||||
const navigate = (0, import_tool.defineTool)({
|
||||
capability: "core",
|
||||
schema: {
|
||||
name: "browser_navigate",
|
||||
title: "Navigate to a URL",
|
||||
description: "Navigate to a URL",
|
||||
inputSchema: import_mcpBundle.z.object({
|
||||
url: import_mcpBundle.z.string().describe("The URL to navigate to")
|
||||
}),
|
||||
type: "action"
|
||||
},
|
||||
handle: async (context, params, response) => {
|
||||
const tab = await context.ensureTab();
|
||||
let url = params.url;
|
||||
try {
|
||||
new URL(url);
|
||||
} catch (e) {
|
||||
if (url.startsWith("localhost"))
|
||||
url = "http://" + url;
|
||||
else
|
||||
url = "https://" + url;
|
||||
}
|
||||
await tab.navigate(url);
|
||||
response.setIncludeSnapshot();
|
||||
response.addCode(`await page.goto('${params.url}');`);
|
||||
}
|
||||
});
|
||||
const goBack = (0, import_tool.defineTabTool)({
|
||||
capability: "core",
|
||||
schema: {
|
||||
name: "browser_navigate_back",
|
||||
title: "Go back",
|
||||
description: "Go back to the previous page",
|
||||
inputSchema: import_mcpBundle.z.object({}),
|
||||
type: "action"
|
||||
},
|
||||
handle: async (tab, params, response) => {
|
||||
await tab.page.goBack();
|
||||
response.setIncludeSnapshot();
|
||||
response.addCode(`await page.goBack();`);
|
||||
}
|
||||
});
|
||||
var navigate_default = [
|
||||
navigate,
|
||||
goBack
|
||||
];
|
||||
63
backend/node_modules/playwright/lib/mcp/browser/tools/network.js
generated
vendored
Normal file
63
backend/node_modules/playwright/lib/mcp/browser/tools/network.js
generated
vendored
Normal file
|
|
@ -0,0 +1,63 @@
|
|||
"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 network_exports = {};
|
||||
__export(network_exports, {
|
||||
default: () => network_default
|
||||
});
|
||||
module.exports = __toCommonJS(network_exports);
|
||||
var import_mcpBundle = require("playwright-core/lib/mcpBundle");
|
||||
var import_tool = require("./tool");
|
||||
const requests = (0, import_tool.defineTabTool)({
|
||||
capability: "core",
|
||||
schema: {
|
||||
name: "browser_network_requests",
|
||||
title: "List network requests",
|
||||
description: "Returns all network requests since loading the page",
|
||||
inputSchema: import_mcpBundle.z.object({
|
||||
includeStatic: import_mcpBundle.z.boolean().default(false).describe("Whether to include successful static resources like images, fonts, scripts, etc. Defaults to false."),
|
||||
filename: import_mcpBundle.z.string().optional().describe("Filename to save the network requests to. If not provided, requests are returned as text.")
|
||||
}),
|
||||
type: "readOnly"
|
||||
},
|
||||
handle: async (tab, params, response) => {
|
||||
const requests2 = await tab.requests();
|
||||
const text = [];
|
||||
for (const request of requests2) {
|
||||
const rendered = await renderRequest(request, params.includeStatic);
|
||||
if (rendered)
|
||||
text.push(rendered);
|
||||
}
|
||||
await response.addResult({ text: text.join("\n"), suggestedFilename: params.filename });
|
||||
}
|
||||
});
|
||||
async function renderRequest(request, includeStatic) {
|
||||
const response = request._hasResponse ? await request.response() : void 0;
|
||||
const isStaticRequest = ["document", "stylesheet", "image", "media", "font", "script", "manifest"].includes(request.resourceType());
|
||||
const isSuccessfulRequest = !response || response.status() < 400;
|
||||
if (isStaticRequest && isSuccessfulRequest && !includeStatic)
|
||||
return void 0;
|
||||
const result = [];
|
||||
result.push(`[${request.method().toUpperCase()}] ${request.url()}`);
|
||||
if (response)
|
||||
result.push(`=> [${response.status()}] ${response.statusText()}`);
|
||||
return result.join(" ");
|
||||
}
|
||||
var network_default = [
|
||||
requests
|
||||
];
|
||||
57
backend/node_modules/playwright/lib/mcp/browser/tools/open.js
generated
vendored
Normal file
57
backend/node_modules/playwright/lib/mcp/browser/tools/open.js
generated
vendored
Normal file
|
|
@ -0,0 +1,57 @@
|
|||
"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 open_exports = {};
|
||||
__export(open_exports, {
|
||||
default: () => open_default
|
||||
});
|
||||
module.exports = __toCommonJS(open_exports);
|
||||
var import_mcpBundle = require("playwright-core/lib/mcpBundle");
|
||||
var import_tool = require("./tool");
|
||||
const open = (0, import_tool.defineTool)({
|
||||
capability: "internal",
|
||||
schema: {
|
||||
name: "browser_open",
|
||||
title: "Open URL",
|
||||
description: "Open a URL in the browser",
|
||||
inputSchema: import_mcpBundle.z.object({
|
||||
url: import_mcpBundle.z.string().describe("The URL to open"),
|
||||
headed: import_mcpBundle.z.boolean().optional().describe("Run browser in headed mode")
|
||||
}),
|
||||
type: "action"
|
||||
},
|
||||
handle: async (context, params, response) => {
|
||||
const forceHeadless = params.headed ? "headed" : "headless";
|
||||
const tab = await context.ensureTab({ forceHeadless });
|
||||
let url = params.url;
|
||||
try {
|
||||
new URL(url);
|
||||
} catch (e) {
|
||||
if (url.startsWith("localhost"))
|
||||
url = "http://" + url;
|
||||
else
|
||||
url = "https://" + url;
|
||||
}
|
||||
await tab.navigate(url);
|
||||
response.setIncludeSnapshot();
|
||||
response.addCode(`await page.goto('${params.url}');`);
|
||||
}
|
||||
});
|
||||
var open_default = [
|
||||
open
|
||||
];
|
||||
49
backend/node_modules/playwright/lib/mcp/browser/tools/pdf.js
generated
vendored
Normal file
49
backend/node_modules/playwright/lib/mcp/browser/tools/pdf.js
generated
vendored
Normal file
|
|
@ -0,0 +1,49 @@
|
|||
"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 pdf_exports = {};
|
||||
__export(pdf_exports, {
|
||||
default: () => pdf_default
|
||||
});
|
||||
module.exports = __toCommonJS(pdf_exports);
|
||||
var import_mcpBundle = require("playwright-core/lib/mcpBundle");
|
||||
var import_utils = require("playwright-core/lib/utils");
|
||||
var import_tool = require("./tool");
|
||||
var import_utils2 = require("./utils");
|
||||
const pdfSchema = import_mcpBundle.z.object({
|
||||
filename: import_mcpBundle.z.string().optional().describe("File name to save the pdf to. Defaults to `page-{timestamp}.pdf` if not specified. Prefer relative file names to stay within the output directory.")
|
||||
});
|
||||
const pdf = (0, import_tool.defineTabTool)({
|
||||
capability: "pdf",
|
||||
schema: {
|
||||
name: "browser_pdf_save",
|
||||
title: "Save as PDF",
|
||||
description: "Save page as PDF",
|
||||
inputSchema: pdfSchema,
|
||||
type: "readOnly"
|
||||
},
|
||||
handle: async (tab, params, response) => {
|
||||
const data = await tab.page.pdf();
|
||||
const suggestedFilename = params.filename ?? (0, import_utils2.dateAsFileName)("pdf");
|
||||
await response.addResult({ data, title: "Page as pdf", suggestedFilename });
|
||||
response.addCode(`await page.pdf(${(0, import_utils.formatObject)({ path: suggestedFilename })});`);
|
||||
}
|
||||
});
|
||||
var pdf_default = [
|
||||
pdf
|
||||
];
|
||||
78
backend/node_modules/playwright/lib/mcp/browser/tools/runCode.js
generated
vendored
Normal file
78
backend/node_modules/playwright/lib/mcp/browser/tools/runCode.js
generated
vendored
Normal 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 runCode_exports = {};
|
||||
__export(runCode_exports, {
|
||||
default: () => runCode_default
|
||||
});
|
||||
module.exports = __toCommonJS(runCode_exports);
|
||||
var import_vm = __toESM(require("vm"));
|
||||
var import_utils = require("playwright-core/lib/utils");
|
||||
var import_mcpBundle = require("playwright-core/lib/mcpBundle");
|
||||
var import_tool = require("./tool");
|
||||
const codeSchema = import_mcpBundle.z.object({
|
||||
code: import_mcpBundle.z.string().describe(`A JavaScript function containing Playwright code to execute. It will be invoked with a single argument, page, which you can use for any page interaction. For example: \`async (page) => { await page.getByRole('button', { name: 'Submit' }).click(); return await page.title(); }\``),
|
||||
filename: import_mcpBundle.z.string().optional().describe("Filename to save the result to. If not provided, result is returned as JSON string.")
|
||||
});
|
||||
const runCode = (0, import_tool.defineTabTool)({
|
||||
capability: "core",
|
||||
schema: {
|
||||
name: "browser_run_code",
|
||||
title: "Run Playwright code",
|
||||
description: "Run Playwright code snippet",
|
||||
inputSchema: codeSchema,
|
||||
type: "action"
|
||||
},
|
||||
handle: async (tab, params, response) => {
|
||||
response.setIncludeSnapshot();
|
||||
response.addCode(`await (${params.code})(page);`);
|
||||
const __end__ = new import_utils.ManualPromise();
|
||||
const context = {
|
||||
page: tab.page,
|
||||
__end__
|
||||
};
|
||||
import_vm.default.createContext(context);
|
||||
await tab.waitForCompletion(async () => {
|
||||
const snippet = `(async () => {
|
||||
try {
|
||||
const result = await (${params.code})(page);
|
||||
__end__.resolve(JSON.stringify(result));
|
||||
} catch (e) {
|
||||
__end__.reject(e);
|
||||
}
|
||||
})()`;
|
||||
await import_vm.default.runInContext(snippet, context);
|
||||
const result = await __end__;
|
||||
if (typeof result === "string")
|
||||
await response.addResult({ text: result, suggestedFilename: params.filename });
|
||||
});
|
||||
}
|
||||
});
|
||||
var runCode_default = [
|
||||
runCode
|
||||
];
|
||||
93
backend/node_modules/playwright/lib/mcp/browser/tools/screenshot.js
generated
vendored
Normal file
93
backend/node_modules/playwright/lib/mcp/browser/tools/screenshot.js
generated
vendored
Normal file
|
|
@ -0,0 +1,93 @@
|
|||
"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 screenshot_exports = {};
|
||||
__export(screenshot_exports, {
|
||||
default: () => screenshot_default,
|
||||
scaleImageToFitMessage: () => scaleImageToFitMessage
|
||||
});
|
||||
module.exports = __toCommonJS(screenshot_exports);
|
||||
var import_utils = require("playwright-core/lib/utils");
|
||||
var import_utilsBundle = require("playwright-core/lib/utilsBundle");
|
||||
var import_utils2 = require("playwright-core/lib/utils");
|
||||
var import_mcpBundle = require("playwright-core/lib/mcpBundle");
|
||||
var import_tool = require("./tool");
|
||||
var import_utils3 = require("./utils");
|
||||
const screenshotSchema = import_mcpBundle.z.object({
|
||||
type: import_mcpBundle.z.enum(["png", "jpeg"]).default("png").describe("Image format for the screenshot. Default is png."),
|
||||
filename: import_mcpBundle.z.string().optional().describe("File name to save the screenshot to. Defaults to `page-{timestamp}.{png|jpeg}` if not specified. Prefer relative file names to stay within the output directory."),
|
||||
element: import_mcpBundle.z.string().optional().describe("Human-readable element description used to obtain permission to screenshot the element. If not provided, the screenshot will be taken of viewport. If element is provided, ref must be provided too."),
|
||||
ref: import_mcpBundle.z.string().optional().describe("Exact target element reference from the page snapshot. If not provided, the screenshot will be taken of viewport. If ref is provided, element must be provided too."),
|
||||
fullPage: import_mcpBundle.z.boolean().optional().describe("When true, takes a screenshot of the full scrollable page, instead of the currently visible viewport. Cannot be used with element screenshots.")
|
||||
});
|
||||
const screenshot = (0, import_tool.defineTabTool)({
|
||||
capability: "core",
|
||||
schema: {
|
||||
name: "browser_take_screenshot",
|
||||
title: "Take a screenshot",
|
||||
description: `Take a screenshot of the current page. You can't perform actions based on the screenshot, use browser_snapshot for actions.`,
|
||||
inputSchema: screenshotSchema,
|
||||
type: "readOnly"
|
||||
},
|
||||
handle: async (tab, params, response) => {
|
||||
if (!!params.element !== !!params.ref)
|
||||
throw new Error("Both element and ref must be provided or neither.");
|
||||
if (params.fullPage && params.ref)
|
||||
throw new Error("fullPage cannot be used with element screenshots.");
|
||||
const fileType = params.type || "png";
|
||||
const options = {
|
||||
type: fileType,
|
||||
quality: fileType === "png" ? void 0 : 90,
|
||||
scale: "css",
|
||||
...params.fullPage !== void 0 && { fullPage: params.fullPage }
|
||||
};
|
||||
const isElementScreenshot = params.element && params.ref;
|
||||
const screenshotTarget = isElementScreenshot ? params.element : params.fullPage ? "full page" : "viewport";
|
||||
const ref = params.ref ? await tab.refLocator({ element: params.element || "", ref: params.ref }) : null;
|
||||
const data = ref ? await ref.locator.screenshot(options) : await tab.page.screenshot(options);
|
||||
const fileName = params.filename || (0, import_utils3.dateAsFileName)(fileType);
|
||||
response.addCode(`// Screenshot ${screenshotTarget} and save it as ${fileName}`);
|
||||
if (ref)
|
||||
response.addCode(`await page.${ref.resolved}.screenshot(${(0, import_utils2.formatObject)({ ...options, path: fileName })});`);
|
||||
else
|
||||
response.addCode(`await page.screenshot(${(0, import_utils2.formatObject)({ ...options, path: fileName })});`);
|
||||
await response.addResult({ data, title: `Screenshot of ${screenshotTarget}`, suggestedFilename: fileName });
|
||||
response.addImage({
|
||||
contentType: fileType === "png" ? "image/png" : "image/jpeg",
|
||||
data: scaleImageToFitMessage(data, fileType)
|
||||
});
|
||||
}
|
||||
});
|
||||
function scaleImageToFitMessage(buffer, imageType) {
|
||||
const image = imageType === "png" ? import_utilsBundle.PNG.sync.read(buffer) : import_utilsBundle.jpegjs.decode(buffer, { maxMemoryUsageInMB: 512 });
|
||||
const pixels = image.width * image.height;
|
||||
const shrink = Math.min(1568 / image.width, 1568 / image.height, Math.sqrt(1.15 * 1024 * 1024 / pixels));
|
||||
if (shrink > 1)
|
||||
return buffer;
|
||||
const width = image.width * shrink | 0;
|
||||
const height = image.height * shrink | 0;
|
||||
const scaledImage = (0, import_utils.scaleImageToSize)(image, { width, height });
|
||||
return imageType === "png" ? import_utilsBundle.PNG.sync.write(scaledImage) : import_utilsBundle.jpegjs.encode(scaledImage, 80).data;
|
||||
}
|
||||
var screenshot_default = [
|
||||
screenshot
|
||||
];
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
scaleImageToFitMessage
|
||||
});
|
||||
173
backend/node_modules/playwright/lib/mcp/browser/tools/snapshot.js
generated
vendored
Normal file
173
backend/node_modules/playwright/lib/mcp/browser/tools/snapshot.js
generated
vendored
Normal file
|
|
@ -0,0 +1,173 @@
|
|||
"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 snapshot_exports = {};
|
||||
__export(snapshot_exports, {
|
||||
default: () => snapshot_default,
|
||||
elementSchema: () => elementSchema
|
||||
});
|
||||
module.exports = __toCommonJS(snapshot_exports);
|
||||
var import_mcpBundle = require("playwright-core/lib/mcpBundle");
|
||||
var import_utils = require("playwright-core/lib/utils");
|
||||
var import_tool = require("./tool");
|
||||
const snapshot = (0, import_tool.defineTool)({
|
||||
capability: "core",
|
||||
schema: {
|
||||
name: "browser_snapshot",
|
||||
title: "Page snapshot",
|
||||
description: "Capture accessibility snapshot of the current page, this is better than screenshot",
|
||||
inputSchema: import_mcpBundle.z.object({
|
||||
filename: import_mcpBundle.z.string().optional().describe("Save snapshot to markdown file instead of returning it in the response.")
|
||||
}),
|
||||
type: "readOnly"
|
||||
},
|
||||
handle: async (context, params, response) => {
|
||||
await context.ensureTab();
|
||||
response.setIncludeFullSnapshot(params.filename);
|
||||
}
|
||||
});
|
||||
const elementSchema = import_mcpBundle.z.object({
|
||||
element: import_mcpBundle.z.string().optional().describe("Human-readable element description used to obtain permission to interact with the element"),
|
||||
ref: import_mcpBundle.z.string().describe("Exact target element reference from the page snapshot")
|
||||
});
|
||||
const clickSchema = elementSchema.extend({
|
||||
doubleClick: import_mcpBundle.z.boolean().optional().describe("Whether to perform a double click instead of a single click"),
|
||||
button: import_mcpBundle.z.enum(["left", "right", "middle"]).optional().describe("Button to click, defaults to left"),
|
||||
modifiers: import_mcpBundle.z.array(import_mcpBundle.z.enum(["Alt", "Control", "ControlOrMeta", "Meta", "Shift"])).optional().describe("Modifier keys to press")
|
||||
});
|
||||
const click = (0, import_tool.defineTabTool)({
|
||||
capability: "core",
|
||||
schema: {
|
||||
name: "browser_click",
|
||||
title: "Click",
|
||||
description: "Perform click on a web page",
|
||||
inputSchema: clickSchema,
|
||||
type: "input"
|
||||
},
|
||||
handle: async (tab, params, response) => {
|
||||
response.setIncludeSnapshot();
|
||||
const { locator, resolved } = await tab.refLocator(params);
|
||||
const options = {
|
||||
button: params.button,
|
||||
modifiers: params.modifiers
|
||||
};
|
||||
const formatted = (0, import_utils.formatObject)(options, " ", "oneline");
|
||||
const optionsAttr = formatted !== "{}" ? formatted : "";
|
||||
if (params.doubleClick)
|
||||
response.addCode(`await page.${resolved}.dblclick(${optionsAttr});`);
|
||||
else
|
||||
response.addCode(`await page.${resolved}.click(${optionsAttr});`);
|
||||
await tab.waitForCompletion(async () => {
|
||||
if (params.doubleClick)
|
||||
await locator.dblclick(options);
|
||||
else
|
||||
await locator.click(options);
|
||||
});
|
||||
}
|
||||
});
|
||||
const drag = (0, import_tool.defineTabTool)({
|
||||
capability: "core",
|
||||
schema: {
|
||||
name: "browser_drag",
|
||||
title: "Drag mouse",
|
||||
description: "Perform drag and drop between two elements",
|
||||
inputSchema: import_mcpBundle.z.object({
|
||||
startElement: import_mcpBundle.z.string().describe("Human-readable source element description used to obtain the permission to interact with the element"),
|
||||
startRef: import_mcpBundle.z.string().describe("Exact source element reference from the page snapshot"),
|
||||
endElement: import_mcpBundle.z.string().describe("Human-readable target element description used to obtain the permission to interact with the element"),
|
||||
endRef: import_mcpBundle.z.string().describe("Exact target element reference from the page snapshot")
|
||||
}),
|
||||
type: "input"
|
||||
},
|
||||
handle: async (tab, params, response) => {
|
||||
response.setIncludeSnapshot();
|
||||
const [start, end] = await tab.refLocators([
|
||||
{ ref: params.startRef, element: params.startElement },
|
||||
{ ref: params.endRef, element: params.endElement }
|
||||
]);
|
||||
await tab.waitForCompletion(async () => {
|
||||
await start.locator.dragTo(end.locator);
|
||||
});
|
||||
response.addCode(`await page.${start.resolved}.dragTo(page.${end.resolved});`);
|
||||
}
|
||||
});
|
||||
const hover = (0, import_tool.defineTabTool)({
|
||||
capability: "core",
|
||||
schema: {
|
||||
name: "browser_hover",
|
||||
title: "Hover mouse",
|
||||
description: "Hover over element on page",
|
||||
inputSchema: elementSchema,
|
||||
type: "input"
|
||||
},
|
||||
handle: async (tab, params, response) => {
|
||||
response.setIncludeSnapshot();
|
||||
const { locator, resolved } = await tab.refLocator(params);
|
||||
response.addCode(`await page.${resolved}.hover();`);
|
||||
await tab.waitForCompletion(async () => {
|
||||
await locator.hover();
|
||||
});
|
||||
}
|
||||
});
|
||||
const selectOptionSchema = elementSchema.extend({
|
||||
values: import_mcpBundle.z.array(import_mcpBundle.z.string()).describe("Array of values to select in the dropdown. This can be a single value or multiple values.")
|
||||
});
|
||||
const selectOption = (0, import_tool.defineTabTool)({
|
||||
capability: "core",
|
||||
schema: {
|
||||
name: "browser_select_option",
|
||||
title: "Select option",
|
||||
description: "Select an option in a dropdown",
|
||||
inputSchema: selectOptionSchema,
|
||||
type: "input"
|
||||
},
|
||||
handle: async (tab, params, response) => {
|
||||
response.setIncludeSnapshot();
|
||||
const { locator, resolved } = await tab.refLocator(params);
|
||||
response.addCode(`await page.${resolved}.selectOption(${(0, import_utils.formatObject)(params.values)});`);
|
||||
await tab.waitForCompletion(async () => {
|
||||
await locator.selectOption(params.values);
|
||||
});
|
||||
}
|
||||
});
|
||||
const pickLocator = (0, import_tool.defineTabTool)({
|
||||
capability: "testing",
|
||||
schema: {
|
||||
name: "browser_generate_locator",
|
||||
title: "Create locator for element",
|
||||
description: "Generate locator for the given element to use in tests",
|
||||
inputSchema: elementSchema,
|
||||
type: "readOnly"
|
||||
},
|
||||
handle: async (tab, params, response) => {
|
||||
const { resolved } = await tab.refLocator(params);
|
||||
response.addTextResult(resolved);
|
||||
}
|
||||
});
|
||||
var snapshot_default = [
|
||||
snapshot,
|
||||
click,
|
||||
drag,
|
||||
hover,
|
||||
selectOption,
|
||||
pickLocator
|
||||
];
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
elementSchema
|
||||
});
|
||||
67
backend/node_modules/playwright/lib/mcp/browser/tools/tabs.js
generated
vendored
Normal file
67
backend/node_modules/playwright/lib/mcp/browser/tools/tabs.js
generated
vendored
Normal file
|
|
@ -0,0 +1,67 @@
|
|||
"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 tabs_exports = {};
|
||||
__export(tabs_exports, {
|
||||
default: () => tabs_default
|
||||
});
|
||||
module.exports = __toCommonJS(tabs_exports);
|
||||
var import_mcpBundle = require("playwright-core/lib/mcpBundle");
|
||||
var import_tool = require("./tool");
|
||||
var import_response = require("../response");
|
||||
const browserTabs = (0, import_tool.defineTool)({
|
||||
capability: "core-tabs",
|
||||
schema: {
|
||||
name: "browser_tabs",
|
||||
title: "Manage tabs",
|
||||
description: "List, create, close, or select a browser tab.",
|
||||
inputSchema: import_mcpBundle.z.object({
|
||||
action: import_mcpBundle.z.enum(["list", "new", "close", "select"]).describe("Operation to perform"),
|
||||
index: import_mcpBundle.z.number().optional().describe("Tab index, used for close/select. If omitted for close, current tab is closed.")
|
||||
}),
|
||||
type: "action"
|
||||
},
|
||||
handle: async (context, params, response) => {
|
||||
switch (params.action) {
|
||||
case "list": {
|
||||
await context.ensureTab();
|
||||
break;
|
||||
}
|
||||
case "new": {
|
||||
await context.newTab();
|
||||
break;
|
||||
}
|
||||
case "close": {
|
||||
await context.closeTab(params.index);
|
||||
break;
|
||||
}
|
||||
case "select": {
|
||||
if (params.index === void 0)
|
||||
throw new Error("Tab index is required");
|
||||
await context.selectTab(params.index);
|
||||
break;
|
||||
}
|
||||
}
|
||||
const tabHeaders = await Promise.all(context.tabs().map((tab) => tab.headerSnapshot()));
|
||||
const result = (0, import_response.renderTabsMarkdown)(tabHeaders);
|
||||
response.addTextResult(result.join("\n"));
|
||||
}
|
||||
});
|
||||
var tabs_default = [
|
||||
browserTabs
|
||||
];
|
||||
47
backend/node_modules/playwright/lib/mcp/browser/tools/tool.js
generated
vendored
Normal file
47
backend/node_modules/playwright/lib/mcp/browser/tools/tool.js
generated
vendored
Normal file
|
|
@ -0,0 +1,47 @@
|
|||
"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 tool_exports = {};
|
||||
__export(tool_exports, {
|
||||
defineTabTool: () => defineTabTool,
|
||||
defineTool: () => defineTool
|
||||
});
|
||||
module.exports = __toCommonJS(tool_exports);
|
||||
function defineTool(tool) {
|
||||
return tool;
|
||||
}
|
||||
function defineTabTool(tool) {
|
||||
return {
|
||||
...tool,
|
||||
handle: async (context, params, response) => {
|
||||
const tab = await context.ensureTab();
|
||||
const modalStates = tab.modalStates().map((state) => state.type);
|
||||
if (tool.clearsModalState && !modalStates.includes(tool.clearsModalState))
|
||||
response.addError(`Error: The tool "${tool.schema.name}" can only be used when there is related modal state present.`);
|
||||
else if (!tool.clearsModalState && modalStates.length)
|
||||
response.addError(`Error: Tool "${tool.schema.name}" does not handle the modal state.`);
|
||||
else
|
||||
return tool.handle(tab, params, response);
|
||||
}
|
||||
};
|
||||
}
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
defineTabTool,
|
||||
defineTool
|
||||
});
|
||||
74
backend/node_modules/playwright/lib/mcp/browser/tools/tracing.js
generated
vendored
Normal file
74
backend/node_modules/playwright/lib/mcp/browser/tools/tracing.js
generated
vendored
Normal file
|
|
@ -0,0 +1,74 @@
|
|||
"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 tracing_exports = {};
|
||||
__export(tracing_exports, {
|
||||
default: () => tracing_default
|
||||
});
|
||||
module.exports = __toCommonJS(tracing_exports);
|
||||
var import_mcpBundle = require("playwright-core/lib/mcpBundle");
|
||||
var import_tool = require("./tool");
|
||||
const tracingStart = (0, import_tool.defineTool)({
|
||||
capability: "tracing",
|
||||
schema: {
|
||||
name: "browser_start_tracing",
|
||||
title: "Start tracing",
|
||||
description: "Start trace recording",
|
||||
inputSchema: import_mcpBundle.z.object({}),
|
||||
type: "readOnly"
|
||||
},
|
||||
handle: async (context, params, response) => {
|
||||
const browserContext = await context.ensureBrowserContext();
|
||||
const tracesDir = await context.outputFile(`traces`, { origin: "code", title: "Collecting trace" });
|
||||
const name = "trace-" + Date.now();
|
||||
await browserContext.tracing.start({
|
||||
name,
|
||||
screenshots: true,
|
||||
snapshots: true,
|
||||
_live: true
|
||||
});
|
||||
const traceLegend = `- Action log: ${tracesDir}/${name}.trace
|
||||
- Network log: ${tracesDir}/${name}.network
|
||||
- Resources with content by sha1: ${tracesDir}/resources`;
|
||||
response.addTextResult(`Tracing started, saving to ${tracesDir}.
|
||||
${traceLegend}`);
|
||||
browserContext.tracing[traceLegendSymbol] = traceLegend;
|
||||
}
|
||||
});
|
||||
const tracingStop = (0, import_tool.defineTool)({
|
||||
capability: "tracing",
|
||||
schema: {
|
||||
name: "browser_stop_tracing",
|
||||
title: "Stop tracing",
|
||||
description: "Stop trace recording",
|
||||
inputSchema: import_mcpBundle.z.object({}),
|
||||
type: "readOnly"
|
||||
},
|
||||
handle: async (context, params, response) => {
|
||||
const browserContext = await context.ensureBrowserContext();
|
||||
await browserContext.tracing.stop();
|
||||
const traceLegend = browserContext.tracing[traceLegendSymbol];
|
||||
response.addTextResult(`Tracing stopped.
|
||||
${traceLegend}`);
|
||||
}
|
||||
});
|
||||
var tracing_default = [
|
||||
tracingStart,
|
||||
tracingStop
|
||||
];
|
||||
const traceLegendSymbol = Symbol("tracesDir");
|
||||
94
backend/node_modules/playwright/lib/mcp/browser/tools/utils.js
generated
vendored
Normal file
94
backend/node_modules/playwright/lib/mcp/browser/tools/utils.js
generated
vendored
Normal file
|
|
@ -0,0 +1,94 @@
|
|||
"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 utils_exports = {};
|
||||
__export(utils_exports, {
|
||||
callOnPageNoTrace: () => callOnPageNoTrace,
|
||||
dateAsFileName: () => dateAsFileName,
|
||||
eventWaiter: () => eventWaiter,
|
||||
waitForCompletion: () => waitForCompletion
|
||||
});
|
||||
module.exports = __toCommonJS(utils_exports);
|
||||
async function waitForCompletion(tab, callback) {
|
||||
const requests = [];
|
||||
const requestListener = (request) => requests.push(request);
|
||||
const disposeListeners = () => {
|
||||
tab.page.off("request", requestListener);
|
||||
};
|
||||
tab.page.on("request", requestListener);
|
||||
let result;
|
||||
try {
|
||||
result = await callback();
|
||||
await tab.waitForTimeout(500);
|
||||
} finally {
|
||||
disposeListeners();
|
||||
}
|
||||
const requestedNavigation = requests.some((request) => request.isNavigationRequest());
|
||||
if (requestedNavigation) {
|
||||
await tab.page.mainFrame().waitForLoadState("load", { timeout: 1e4 }).catch(() => {
|
||||
});
|
||||
return result;
|
||||
}
|
||||
const promises = [];
|
||||
for (const request of requests) {
|
||||
if (["document", "stylesheet", "script", "xhr", "fetch"].includes(request.resourceType()))
|
||||
promises.push(request.response().then((r) => r?.finished()).catch(() => {
|
||||
}));
|
||||
else
|
||||
promises.push(request.response().catch(() => {
|
||||
}));
|
||||
}
|
||||
const timeout = new Promise((resolve) => setTimeout(resolve, 5e3));
|
||||
await Promise.race([Promise.all(promises), timeout]);
|
||||
if (requests.length)
|
||||
await tab.waitForTimeout(500);
|
||||
return result;
|
||||
}
|
||||
async function callOnPageNoTrace(page, callback) {
|
||||
return await page._wrapApiCall(() => callback(page), { internal: true });
|
||||
}
|
||||
function dateAsFileName(extension) {
|
||||
const date = /* @__PURE__ */ new Date();
|
||||
return `page-${date.toISOString().replace(/[:.]/g, "-")}.${extension}`;
|
||||
}
|
||||
function eventWaiter(page, event, timeout) {
|
||||
const disposables = [];
|
||||
const eventPromise = new Promise((resolve, reject) => {
|
||||
page.on(event, resolve);
|
||||
disposables.push(() => page.off(event, resolve));
|
||||
});
|
||||
let abort;
|
||||
const abortPromise = new Promise((resolve, reject) => {
|
||||
abort = () => resolve(void 0);
|
||||
});
|
||||
const timeoutPromise = new Promise((f) => {
|
||||
const timeoutId = setTimeout(() => f(void 0), timeout);
|
||||
disposables.push(() => clearTimeout(timeoutId));
|
||||
});
|
||||
return {
|
||||
promise: Promise.race([eventPromise, abortPromise, timeoutPromise]).finally(() => disposables.forEach((dispose) => dispose())),
|
||||
abort
|
||||
};
|
||||
}
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
callOnPageNoTrace,
|
||||
dateAsFileName,
|
||||
eventWaiter,
|
||||
waitForCompletion
|
||||
});
|
||||
143
backend/node_modules/playwright/lib/mcp/browser/tools/verify.js
generated
vendored
Normal file
143
backend/node_modules/playwright/lib/mcp/browser/tools/verify.js
generated
vendored
Normal file
|
|
@ -0,0 +1,143 @@
|
|||
"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 verify_exports = {};
|
||||
__export(verify_exports, {
|
||||
default: () => verify_default
|
||||
});
|
||||
module.exports = __toCommonJS(verify_exports);
|
||||
var import_mcpBundle = require("playwright-core/lib/mcpBundle");
|
||||
var import_utils = require("playwright-core/lib/utils");
|
||||
var import_tool = require("./tool");
|
||||
const verifyElement = (0, import_tool.defineTabTool)({
|
||||
capability: "testing",
|
||||
schema: {
|
||||
name: "browser_verify_element_visible",
|
||||
title: "Verify element visible",
|
||||
description: "Verify element is visible on the page",
|
||||
inputSchema: import_mcpBundle.z.object({
|
||||
role: import_mcpBundle.z.string().describe('ROLE of the element. Can be found in the snapshot like this: `- {ROLE} "Accessible Name":`'),
|
||||
accessibleName: import_mcpBundle.z.string().describe('ACCESSIBLE_NAME of the element. Can be found in the snapshot like this: `- role "{ACCESSIBLE_NAME}"`')
|
||||
}),
|
||||
type: "assertion"
|
||||
},
|
||||
handle: async (tab, params, response) => {
|
||||
const locator = tab.page.getByRole(params.role, { name: params.accessibleName });
|
||||
if (await locator.count() === 0) {
|
||||
response.addError(`Element with role "${params.role}" and accessible name "${params.accessibleName}" not found`);
|
||||
return;
|
||||
}
|
||||
response.addCode(`await expect(page.getByRole(${(0, import_utils.escapeWithQuotes)(params.role)}, { name: ${(0, import_utils.escapeWithQuotes)(params.accessibleName)} })).toBeVisible();`);
|
||||
response.addTextResult("Done");
|
||||
}
|
||||
});
|
||||
const verifyText = (0, import_tool.defineTabTool)({
|
||||
capability: "testing",
|
||||
schema: {
|
||||
name: "browser_verify_text_visible",
|
||||
title: "Verify text visible",
|
||||
description: `Verify text is visible on the page. Prefer ${verifyElement.schema.name} if possible.`,
|
||||
inputSchema: import_mcpBundle.z.object({
|
||||
text: import_mcpBundle.z.string().describe('TEXT to verify. Can be found in the snapshot like this: `- role "Accessible Name": {TEXT}` or like this: `- text: {TEXT}`')
|
||||
}),
|
||||
type: "assertion"
|
||||
},
|
||||
handle: async (tab, params, response) => {
|
||||
const locator = tab.page.getByText(params.text).filter({ visible: true });
|
||||
if (await locator.count() === 0) {
|
||||
response.addError("Text not found");
|
||||
return;
|
||||
}
|
||||
response.addCode(`await expect(page.getByText(${(0, import_utils.escapeWithQuotes)(params.text)})).toBeVisible();`);
|
||||
response.addTextResult("Done");
|
||||
}
|
||||
});
|
||||
const verifyList = (0, import_tool.defineTabTool)({
|
||||
capability: "testing",
|
||||
schema: {
|
||||
name: "browser_verify_list_visible",
|
||||
title: "Verify list visible",
|
||||
description: "Verify list is visible on the page",
|
||||
inputSchema: import_mcpBundle.z.object({
|
||||
element: import_mcpBundle.z.string().describe("Human-readable list description"),
|
||||
ref: import_mcpBundle.z.string().describe("Exact target element reference that points to the list"),
|
||||
items: import_mcpBundle.z.array(import_mcpBundle.z.string()).describe("Items to verify")
|
||||
}),
|
||||
type: "assertion"
|
||||
},
|
||||
handle: async (tab, params, response) => {
|
||||
const { locator } = await tab.refLocator({ ref: params.ref, element: params.element });
|
||||
const itemTexts = [];
|
||||
for (const item of params.items) {
|
||||
const itemLocator = locator.getByText(item);
|
||||
if (await itemLocator.count() === 0) {
|
||||
response.addError(`Item "${item}" not found`);
|
||||
return;
|
||||
}
|
||||
itemTexts.push(await itemLocator.textContent());
|
||||
}
|
||||
const ariaSnapshot = `\`
|
||||
- list:
|
||||
${itemTexts.map((t) => ` - listitem: ${(0, import_utils.escapeWithQuotes)(t, '"')}`).join("\n")}
|
||||
\``;
|
||||
response.addCode(`await expect(page.locator('body')).toMatchAriaSnapshot(${ariaSnapshot});`);
|
||||
response.addTextResult("Done");
|
||||
}
|
||||
});
|
||||
const verifyValue = (0, import_tool.defineTabTool)({
|
||||
capability: "testing",
|
||||
schema: {
|
||||
name: "browser_verify_value",
|
||||
title: "Verify value",
|
||||
description: "Verify element value",
|
||||
inputSchema: import_mcpBundle.z.object({
|
||||
type: import_mcpBundle.z.enum(["textbox", "checkbox", "radio", "combobox", "slider"]).describe("Type of the element"),
|
||||
element: import_mcpBundle.z.string().describe("Human-readable element description"),
|
||||
ref: import_mcpBundle.z.string().describe("Exact target element reference that points to the element"),
|
||||
value: import_mcpBundle.z.string().describe('Value to verify. For checkbox, use "true" or "false".')
|
||||
}),
|
||||
type: "assertion"
|
||||
},
|
||||
handle: async (tab, params, response) => {
|
||||
const { locator, resolved } = await tab.refLocator({ ref: params.ref, element: params.element });
|
||||
const locatorSource = `page.${resolved}`;
|
||||
if (params.type === "textbox" || params.type === "slider" || params.type === "combobox") {
|
||||
const value = await locator.inputValue();
|
||||
if (value !== params.value) {
|
||||
response.addError(`Expected value "${params.value}", but got "${value}"`);
|
||||
return;
|
||||
}
|
||||
response.addCode(`await expect(${locatorSource}).toHaveValue(${(0, import_utils.escapeWithQuotes)(params.value)});`);
|
||||
} else if (params.type === "checkbox" || params.type === "radio") {
|
||||
const value = await locator.isChecked();
|
||||
if (value !== (params.value === "true")) {
|
||||
response.addError(`Expected value "${params.value}", but got "${value}"`);
|
||||
return;
|
||||
}
|
||||
const matcher = value ? "toBeChecked" : "not.toBeChecked";
|
||||
response.addCode(`await expect(${locatorSource}).${matcher}();`);
|
||||
}
|
||||
response.addTextResult("Done");
|
||||
}
|
||||
});
|
||||
var verify_default = [
|
||||
verifyElement,
|
||||
verifyText,
|
||||
verifyList,
|
||||
verifyValue
|
||||
];
|
||||
63
backend/node_modules/playwright/lib/mcp/browser/tools/wait.js
generated
vendored
Normal file
63
backend/node_modules/playwright/lib/mcp/browser/tools/wait.js
generated
vendored
Normal file
|
|
@ -0,0 +1,63 @@
|
|||
"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 wait_exports = {};
|
||||
__export(wait_exports, {
|
||||
default: () => wait_default
|
||||
});
|
||||
module.exports = __toCommonJS(wait_exports);
|
||||
var import_mcpBundle = require("playwright-core/lib/mcpBundle");
|
||||
var import_tool = require("./tool");
|
||||
const wait = (0, import_tool.defineTool)({
|
||||
capability: "core",
|
||||
schema: {
|
||||
name: "browser_wait_for",
|
||||
title: "Wait for",
|
||||
description: "Wait for text to appear or disappear or a specified time to pass",
|
||||
inputSchema: import_mcpBundle.z.object({
|
||||
time: import_mcpBundle.z.number().optional().describe("The time to wait in seconds"),
|
||||
text: import_mcpBundle.z.string().optional().describe("The text to wait for"),
|
||||
textGone: import_mcpBundle.z.string().optional().describe("The text to wait for to disappear")
|
||||
}),
|
||||
type: "assertion"
|
||||
},
|
||||
handle: async (context, params, response) => {
|
||||
if (!params.text && !params.textGone && !params.time)
|
||||
throw new Error("Either time, text or textGone must be provided");
|
||||
if (params.time) {
|
||||
response.addCode(`await new Promise(f => setTimeout(f, ${params.time} * 1000));`);
|
||||
await new Promise((f) => setTimeout(f, Math.min(3e4, params.time * 1e3)));
|
||||
}
|
||||
const tab = context.currentTabOrDie();
|
||||
const locator = params.text ? tab.page.getByText(params.text).first() : void 0;
|
||||
const goneLocator = params.textGone ? tab.page.getByText(params.textGone).first() : void 0;
|
||||
if (goneLocator) {
|
||||
response.addCode(`await page.getByText(${JSON.stringify(params.textGone)}).first().waitFor({ state: 'hidden' });`);
|
||||
await goneLocator.waitFor({ state: "hidden" });
|
||||
}
|
||||
if (locator) {
|
||||
response.addCode(`await page.getByText(${JSON.stringify(params.text)}).first().waitFor({ state: 'visible' });`);
|
||||
await locator.waitFor({ state: "visible" });
|
||||
}
|
||||
response.addTextResult(`Waited for ${params.text || params.textGone || params.time}`);
|
||||
response.setIncludeSnapshot();
|
||||
}
|
||||
});
|
||||
var wait_default = [
|
||||
wait
|
||||
];
|
||||
44
backend/node_modules/playwright/lib/mcp/browser/watchdog.js
generated
vendored
Normal file
44
backend/node_modules/playwright/lib/mcp/browser/watchdog.js
generated
vendored
Normal 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 watchdog_exports = {};
|
||||
__export(watchdog_exports, {
|
||||
setupExitWatchdog: () => setupExitWatchdog
|
||||
});
|
||||
module.exports = __toCommonJS(watchdog_exports);
|
||||
var import_browserContextFactory = require("./browserContextFactory");
|
||||
var import_context = require("./context");
|
||||
function setupExitWatchdog() {
|
||||
let isExiting = false;
|
||||
const handleExit = async () => {
|
||||
if (isExiting)
|
||||
return;
|
||||
isExiting = true;
|
||||
setTimeout(() => process.exit(0), 15e3);
|
||||
await import_context.Context.disposeAll();
|
||||
await import_browserContextFactory.SharedContextFactory.dispose();
|
||||
process.exit(0);
|
||||
};
|
||||
process.stdin.on("close", handleExit);
|
||||
process.on("SIGINT", handleExit);
|
||||
process.on("SIGTERM", handleExit);
|
||||
}
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
setupExitWatchdog
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue