@zibby/mcp-browser 0.1.5 → 0.1.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,369 +0,0 @@
1
- "use strict";
2
- const __create = Object.create;
3
- const __defProp = Object.defineProperty;
4
- const __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- const __getOwnPropNames = Object.getOwnPropertyNames;
6
- const __getProtoOf = Object.getPrototypeOf;
7
- const __hasOwnProp = Object.prototype.hasOwnProperty;
8
- const __export = (target, all) => {
9
- for (const name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- const __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (const key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
20
- const __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- const __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
- const config_exports = {};
30
- __export(config_exports, {
31
- commaSeparatedList: () => commaSeparatedList,
32
- configFromCLIOptions: () => configFromCLIOptions,
33
- defaultConfig: () => defaultConfig,
34
- dotenvFileLoader: () => dotenvFileLoader,
35
- headerParser: () => headerParser,
36
- numberParser: () => numberParser,
37
- outputDir: () => outputDir,
38
- outputFile: () => outputFile,
39
- resolutionParser: () => resolutionParser,
40
- resolveCLIConfig: () => resolveCLIConfig,
41
- resolveConfig: () => resolveConfig
42
- });
43
- module.exports = __toCommonJS(config_exports);
44
- const import_fs = __toESM(require("fs"));
45
- const import_os = __toESM(require("os"));
46
- const import_path = __toESM(require("path"));
47
- const import_playwright_core = require("playwright-core");
48
- const import_utilsBundle = require("playwright-core/lib/utilsBundle");
49
- // ZIBBY: Replace internal util with inline implementation
50
- const import_util = { fileExistsAsync: async (path) => import_fs.default.existsSync(path) };
51
- const import_server = require("../sdk/server");
52
- const defaultConfig = {
53
- browser: {
54
- browserName: "chromium",
55
- launchOptions: {
56
- channel: "chrome",
57
- headless: import_os.default.platform() === "linux" && !process.env.DISPLAY,
58
- chromiumSandbox: true
59
- },
60
- contextOptions: {
61
- viewport: null
62
- }
63
- },
64
- server: {},
65
- saveTrace: false,
66
- timeouts: {
67
- action: 5e3,
68
- navigation: 6e4
69
- }
70
- };
71
- async function resolveConfig(config) {
72
- return mergeConfig(defaultConfig, config);
73
- }
74
- async function resolveCLIConfig(cliOptions) {
75
- const configInFile = await loadConfig(cliOptions.config);
76
- const envOverrides = configFromEnv();
77
- const cliOverrides = configFromCLIOptions(cliOptions);
78
- let result = defaultConfig;
79
- result = mergeConfig(result, configInFile);
80
- result = mergeConfig(result, envOverrides);
81
- result = mergeConfig(result, cliOverrides);
82
- await validateConfig(result);
83
- return result;
84
- }
85
- async function validateConfig(config) {
86
- if (config.browser.initScript) {
87
- for (const script of config.browser.initScript) {
88
- if (!await (0, import_util.fileExistsAsync)(script))
89
- throw new Error(`Init script file does not exist: ${script}`);
90
- }
91
- }
92
- if (config.sharedBrowserContext && config.saveVideo)
93
- throw new Error("saveVideo is not supported when sharedBrowserContext is true");
94
- }
95
- function configFromCLIOptions(cliOptions) {
96
- let browserName;
97
- let channel;
98
- switch (cliOptions.browser) {
99
- case "chrome":
100
- case "chrome-beta":
101
- case "chrome-canary":
102
- case "chrome-dev":
103
- case "chromium":
104
- case "msedge":
105
- case "msedge-beta":
106
- case "msedge-canary":
107
- case "msedge-dev":
108
- browserName = "chromium";
109
- channel = cliOptions.browser;
110
- break;
111
- case "firefox":
112
- browserName = "firefox";
113
- break;
114
- case "webkit":
115
- browserName = "webkit";
116
- break;
117
- }
118
- const launchOptions = {
119
- channel,
120
- executablePath: cliOptions.executablePath,
121
- headless: cliOptions.headless
122
- };
123
- if (cliOptions.sandbox === false)
124
- launchOptions.chromiumSandbox = false;
125
- if (cliOptions.proxyServer) {
126
- launchOptions.proxy = {
127
- server: cliOptions.proxyServer
128
- };
129
- if (cliOptions.proxyBypass)
130
- launchOptions.proxy.bypass = cliOptions.proxyBypass;
131
- }
132
- if (cliOptions.device && cliOptions.cdpEndpoint)
133
- throw new Error("Device emulation is not supported with cdpEndpoint.");
134
- const contextOptions = cliOptions.device ? import_playwright_core.devices[cliOptions.device] : {};
135
- if (cliOptions.storageState)
136
- contextOptions.storageState = cliOptions.storageState;
137
- if (cliOptions.userAgent)
138
- contextOptions.userAgent = cliOptions.userAgent;
139
- if (cliOptions.viewportSize)
140
- contextOptions.viewport = cliOptions.viewportSize;
141
- if (cliOptions.ignoreHttpsErrors)
142
- contextOptions.ignoreHTTPSErrors = true;
143
- if (cliOptions.blockServiceWorkers)
144
- contextOptions.serviceWorkers = "block";
145
- if (cliOptions.grantPermissions)
146
- contextOptions.permissions = cliOptions.grantPermissions;
147
- if (cliOptions.saveVideo) {
148
- contextOptions.recordVideo = {
149
- // Videos are moved to output directory on saveAs.
150
- dir: tmpDir(),
151
- size: cliOptions.saveVideo
152
- };
153
- }
154
- const result = {
155
- browser: {
156
- browserName,
157
- isolated: cliOptions.isolated,
158
- userDataDir: cliOptions.userDataDir,
159
- launchOptions,
160
- contextOptions,
161
- cdpEndpoint: cliOptions.cdpEndpoint,
162
- cdpHeaders: cliOptions.cdpHeader,
163
- initPage: cliOptions.initPage,
164
- initScript: cliOptions.initScript
165
- },
166
- server: {
167
- port: cliOptions.port,
168
- host: cliOptions.host,
169
- allowedHosts: cliOptions.allowedHosts
170
- },
171
- capabilities: cliOptions.caps,
172
- saveSession: cliOptions.saveSession,
173
- saveTrace: cliOptions.saveTrace,
174
- saveVideo: cliOptions.saveVideo,
175
- secrets: cliOptions.secrets,
176
- sharedBrowserContext: cliOptions.sharedBrowserContext,
177
- outputDir: cliOptions.outputDir,
178
- imageResponses: cliOptions.imageResponses,
179
- testIdAttribute: cliOptions.testIdAttribute,
180
- timeouts: {
181
- action: cliOptions.timeoutAction,
182
- navigation: cliOptions.timeoutNavigation
183
- }
184
- };
185
- return result;
186
- }
187
- function configFromEnv() {
188
- const options = {};
189
- options.allowedHosts = commaSeparatedList(process.env.PLAYWRIGHT_MCP_ALLOWED_HOSTNAMES);
190
- options.blockServiceWorkers = envToBoolean(process.env.PLAYWRIGHT_MCP_BLOCK_SERVICE_WORKERS);
191
- options.browser = envToString(process.env.PLAYWRIGHT_MCP_BROWSER);
192
- options.caps = commaSeparatedList(process.env.PLAYWRIGHT_MCP_CAPS);
193
- options.cdpEndpoint = envToString(process.env.PLAYWRIGHT_MCP_CDP_ENDPOINT);
194
- options.cdpHeader = headerParser(process.env.PLAYWRIGHT_MCP_CDP_HEADERS, {});
195
- options.config = envToString(process.env.PLAYWRIGHT_MCP_CONFIG);
196
- options.device = envToString(process.env.PLAYWRIGHT_MCP_DEVICE);
197
- options.executablePath = envToString(process.env.PLAYWRIGHT_MCP_EXECUTABLE_PATH);
198
- options.grantPermissions = commaSeparatedList(process.env.PLAYWRIGHT_MCP_GRANT_PERMISSIONS);
199
- options.headless = envToBoolean(process.env.PLAYWRIGHT_MCP_HEADLESS);
200
- options.host = envToString(process.env.PLAYWRIGHT_MCP_HOST);
201
- options.ignoreHttpsErrors = envToBoolean(process.env.PLAYWRIGHT_MCP_IGNORE_HTTPS_ERRORS);
202
- const initPage = envToString(process.env.PLAYWRIGHT_MCP_INIT_PAGE);
203
- if (initPage)
204
- options.initPage = [initPage];
205
- const initScript = envToString(process.env.PLAYWRIGHT_MCP_INIT_SCRIPT);
206
- if (initScript)
207
- options.initScript = [initScript];
208
- options.isolated = envToBoolean(process.env.PLAYWRIGHT_MCP_ISOLATED);
209
- if (process.env.PLAYWRIGHT_MCP_IMAGE_RESPONSES === "omit")
210
- options.imageResponses = "omit";
211
- options.sandbox = envToBoolean(process.env.PLAYWRIGHT_MCP_SANDBOX);
212
- options.outputDir = envToString(process.env.PLAYWRIGHT_MCP_OUTPUT_DIR);
213
- options.port = numberParser(process.env.PLAYWRIGHT_MCP_PORT);
214
- options.proxyBypass = envToString(process.env.PLAYWRIGHT_MCP_PROXY_BYPASS);
215
- options.proxyServer = envToString(process.env.PLAYWRIGHT_MCP_PROXY_SERVER);
216
- options.saveTrace = envToBoolean(process.env.PLAYWRIGHT_MCP_SAVE_TRACE);
217
- options.saveVideo = resolutionParser("--save-video", process.env.PLAYWRIGHT_MCP_SAVE_VIDEO);
218
- options.secrets = dotenvFileLoader(process.env.PLAYWRIGHT_MCP_SECRETS_FILE);
219
- options.storageState = envToString(process.env.PLAYWRIGHT_MCP_STORAGE_STATE);
220
- options.testIdAttribute = envToString(process.env.PLAYWRIGHT_MCP_TEST_ID_ATTRIBUTE);
221
- options.timeoutAction = numberParser(process.env.PLAYWRIGHT_MCP_TIMEOUT_ACTION);
222
- options.timeoutNavigation = numberParser(process.env.PLAYWRIGHT_MCP_TIMEOUT_NAVIGATION);
223
- options.userAgent = envToString(process.env.PLAYWRIGHT_MCP_USER_AGENT);
224
- options.userDataDir = envToString(process.env.PLAYWRIGHT_MCP_USER_DATA_DIR);
225
- options.viewportSize = resolutionParser("--viewport-size", process.env.PLAYWRIGHT_MCP_VIEWPORT_SIZE);
226
- return configFromCLIOptions(options);
227
- }
228
- async function loadConfig(configFile) {
229
- if (!configFile)
230
- return {};
231
- try {
232
- return JSON.parse(await import_fs.default.promises.readFile(configFile, "utf8"));
233
- } catch (error) {
234
- throw new Error(`Failed to load config file: ${configFile}, ${error}`);
235
- }
236
- }
237
- function tmpDir() {
238
- return import_path.default.join(process.env.PW_TMPDIR_FOR_TEST ?? import_os.default.tmpdir(), "playwright-mcp-output");
239
- }
240
- function outputDir(config, clientInfo) {
241
- const rootPath = (0, import_server.firstRootPath)(clientInfo);
242
- return config.outputDir ?? (rootPath ? import_path.default.join(rootPath, ".playwright-mcp") : void 0) ?? import_path.default.join(tmpDir(), String(clientInfo.timestamp));
243
- }
244
- async function outputFile(config, clientInfo, fileName, options) {
245
- const file = await resolveFile(config, clientInfo, fileName, options);
246
- (0, import_utilsBundle.debug)("pw:mcp:file")(options.reason, file);
247
- return file;
248
- }
249
- async function resolveFile(config, clientInfo, fileName, options) {
250
- const dir = outputDir(config, clientInfo);
251
- if (options.origin === "code")
252
- return import_path.default.resolve(dir, fileName);
253
- if (options.origin === "llm") {
254
- fileName = fileName.split("\\").join("/");
255
- const resolvedFile = import_path.default.resolve(dir, fileName);
256
- if (!resolvedFile.startsWith(import_path.default.resolve(dir) + import_path.default.sep))
257
- throw new Error(`Resolved file path ${resolvedFile} is outside of the output directory ${dir}. Use relative file names to stay within the output directory.`);
258
- return resolvedFile;
259
- }
260
- return import_path.default.join(dir, sanitizeForFilePath(fileName));
261
- }
262
- function pickDefined(obj) {
263
- return Object.fromEntries(
264
- Object.entries(obj ?? {}).filter(([_, v]) => v !== void 0)
265
- );
266
- }
267
- function mergeConfig(base, overrides) {
268
- const browser = {
269
- ...pickDefined(base.browser),
270
- ...pickDefined(overrides.browser),
271
- browserName: overrides.browser?.browserName ?? base.browser?.browserName ?? "chromium",
272
- isolated: overrides.browser?.isolated ?? base.browser?.isolated ?? false,
273
- launchOptions: {
274
- ...pickDefined(base.browser?.launchOptions),
275
- ...pickDefined(overrides.browser?.launchOptions),
276
- ...{ assistantMode: true }
277
- },
278
- contextOptions: {
279
- ...pickDefined(base.browser?.contextOptions),
280
- ...pickDefined(overrides.browser?.contextOptions)
281
- }
282
- };
283
- if (browser.browserName !== "chromium" && browser.launchOptions)
284
- delete browser.launchOptions.channel;
285
- return {
286
- ...pickDefined(base),
287
- ...pickDefined(overrides),
288
- browser,
289
- server: {
290
- ...pickDefined(base.server),
291
- ...pickDefined(overrides.server)
292
- },
293
- timeouts: {
294
- ...pickDefined(base.timeouts),
295
- ...pickDefined(overrides.timeouts)
296
- }
297
- };
298
- }
299
- function commaSeparatedList(value) {
300
- if (!value)
301
- return void 0;
302
- return value.split(",").map((v) => v.trim());
303
- }
304
- function dotenvFileLoader(value) {
305
- if (!value)
306
- return void 0;
307
- return import_utilsBundle.dotenv.parse(import_fs.default.readFileSync(value, "utf8"));
308
- }
309
- function numberParser(value) {
310
- if (!value)
311
- return void 0;
312
- return +value;
313
- }
314
- function resolutionParser(name, value) {
315
- if (!value)
316
- return void 0;
317
- if (value.includes("x")) {
318
- const [width, height] = value.split("x").map((v) => +v);
319
- if (isNaN(width) || isNaN(height) || width <= 0 || height <= 0)
320
- throw new Error(`Invalid resolution format: use ${name}="800x600"`);
321
- return { width, height };
322
- }
323
- if (value.includes(",")) {
324
- const [width, height] = value.split(",").map((v) => +v);
325
- if (isNaN(width) || isNaN(height) || width <= 0 || height <= 0)
326
- throw new Error(`Invalid resolution format: use ${name}="800x600"`);
327
- return { width, height };
328
- }
329
- throw new Error(`Invalid resolution format: use ${name}="800x600"`);
330
- }
331
- function headerParser(arg, previous) {
332
- if (!arg)
333
- return previous || {};
334
- const result = previous || {};
335
- const [name, value] = arg.split(":").map((v) => v.trim());
336
- result[name] = value;
337
- return result;
338
- }
339
- function envToBoolean(value) {
340
- if (value === "true" || value === "1")
341
- return true;
342
- if (value === "false" || value === "0")
343
- return false;
344
- return void 0;
345
- }
346
- function envToString(value) {
347
- return value ? value.trim() : void 0;
348
- }
349
- function sanitizeForFilePath(s) {
350
- const sanitize = (s2) => s2.replace(/[\x00-\x2C\x2E-\x2F\x3A-\x40\x5B-\x60\x7B-\x7F]+/g, "-");
351
- const separator = s.lastIndexOf(".");
352
- if (separator === -1)
353
- return sanitize(s);
354
- return sanitize(s.substring(0, separator)) + "." + sanitize(s.substring(separator + 1));
355
- }
356
- // Annotate the CommonJS export names for ESM import in node:
357
- 0 && (module.exports = {
358
- commaSeparatedList,
359
- configFromCLIOptions,
360
- defaultConfig,
361
- dotenvFileLoader,
362
- headerParser,
363
- numberParser,
364
- outputDir,
365
- outputFile,
366
- resolutionParser,
367
- resolveCLIConfig,
368
- resolveConfig
369
- });
@@ -1,274 +0,0 @@
1
- "use strict";
2
- const __create = Object.create;
3
- const __defProp = Object.defineProperty;
4
- const __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- const __getOwnPropNames = Object.getOwnPropertyNames;
6
- const __getProtoOf = Object.getPrototypeOf;
7
- const __hasOwnProp = Object.prototype.hasOwnProperty;
8
- const __export = (target, all) => {
9
- for (const name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- const __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (const key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
20
- const __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- const __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
- const context_exports = {};
30
- __export(context_exports, {
31
- Context: () => Context,
32
- InputRecorder: () => InputRecorder
33
- });
34
- module.exports = __toCommonJS(context_exports);
35
- const import_fs = __toESM(require("fs"));
36
- const import_path = __toESM(require("path"));
37
- const import_utilsBundle = require("playwright-core/lib/utilsBundle");
38
- const import_playwright_core = require("playwright-core");
39
- const import_log = require("../log");
40
- const import_tab = require("./tab");
41
- const import_config = require("./config");
42
- const codegen = __toESM(require("./codegen"));
43
- const import_utils = require("./tools/utils");
44
- const testDebug = (0, import_utilsBundle.debug)("pw:mcp:test");
45
- class Context {
46
- constructor(options) {
47
- this._tabs = [];
48
- this._abortController = new AbortController();
49
- this.config = options.config;
50
- this.sessionLog = options.sessionLog;
51
- this.options = options;
52
- this._browserContextFactory = options.browserContextFactory;
53
- this._clientInfo = options.clientInfo;
54
- testDebug("create context");
55
- Context._allContexts.add(this);
56
- }
57
- static {
58
- this._allContexts = /* @__PURE__ */ new Set();
59
- }
60
- static async disposeAll() {
61
- await Promise.all([...Context._allContexts].map((context) => context.dispose()));
62
- }
63
- tabs() {
64
- return this._tabs;
65
- }
66
- currentTab() {
67
- return this._currentTab;
68
- }
69
- currentTabOrDie() {
70
- if (!this._currentTab)
71
- throw new Error('No open pages available. Use the "browser_navigate" tool to navigate to a page first.');
72
- return this._currentTab;
73
- }
74
- async newTab() {
75
- const { browserContext } = await this._ensureBrowserContext();
76
- const page = await browserContext.newPage();
77
- this._currentTab = this._tabs.find((t) => t.page === page);
78
- await this._currentTab.initializedPromise;
79
- return this._currentTab;
80
- }
81
- async selectTab(index) {
82
- const tab = this._tabs[index];
83
- if (!tab)
84
- throw new Error(`Tab ${index} not found`);
85
- await tab.page.bringToFront();
86
- this._currentTab = tab;
87
- return tab;
88
- }
89
- async ensureTab() {
90
- const { browserContext } = await this._ensureBrowserContext();
91
- if (!this._currentTab)
92
- await browserContext.newPage();
93
- return this._currentTab;
94
- }
95
- async closeTab(index) {
96
- const tab = index === void 0 ? this._currentTab : this._tabs[index];
97
- if (!tab)
98
- throw new Error(`Tab ${index} not found`);
99
- const url = tab.page.url();
100
- await tab.page.close();
101
- return url;
102
- }
103
- async outputFile(fileName, options) {
104
- return (0, import_config.outputFile)(this.config, this._clientInfo, fileName, options);
105
- }
106
- _onPageCreated(page) {
107
- const tab = new import_tab.Tab(this, page, (tab2) => this._onPageClosed(tab2));
108
- this._tabs.push(tab);
109
- if (!this._currentTab)
110
- this._currentTab = tab;
111
- }
112
- _onPageClosed(tab) {
113
- const index = this._tabs.indexOf(tab);
114
- if (index === -1)
115
- return;
116
- this._tabs.splice(index, 1);
117
- if (this._currentTab === tab)
118
- this._currentTab = this._tabs[Math.min(index, this._tabs.length - 1)];
119
- if (!this._tabs.length)
120
- void this.closeBrowserContext();
121
- }
122
- async closeBrowserContext() {
123
- if (!this._closeBrowserContextPromise)
124
- this._closeBrowserContextPromise = this._closeBrowserContextImpl().catch(import_log.logUnhandledError);
125
- await this._closeBrowserContextPromise;
126
- this._closeBrowserContextPromise = void 0;
127
- }
128
- isRunningTool() {
129
- return this._runningToolName !== void 0;
130
- }
131
- setRunningTool(name) {
132
- this._runningToolName = name;
133
- }
134
- async _closeBrowserContextImpl() {
135
- if (!this._browserContextPromise)
136
- return;
137
- testDebug("close context");
138
- const promise = this._browserContextPromise;
139
- this._browserContextPromise = void 0;
140
- await promise.then(async ({ browserContext, close }) => {
141
- if (this.config.saveTrace)
142
- await browserContext.tracing.stop();
143
- const videos = this.config.saveVideo ? browserContext.pages().map((page) => page.video()).filter((video) => !!video) : [];
144
- await close(async () => {
145
- for (const video of videos) {
146
- const name = await this.outputFile((0, import_utils.dateAsFileName)("webm"), { origin: "code", reason: "Saving video" });
147
- await import_fs.default.promises.mkdir(import_path.default.dirname(name), { recursive: true });
148
- const p = await video.path();
149
- if (import_fs.default.existsSync(p)) {
150
- try {
151
- await import_fs.default.promises.rename(p, name);
152
- } catch (e) {
153
- if (e.code !== "EXDEV")
154
- (0, import_log.logUnhandledError)(e);
155
- try {
156
- await import_fs.default.promises.copyFile(p, name);
157
- await import_fs.default.promises.unlink(p);
158
- } catch (e2) {
159
- (0, import_log.logUnhandledError)(e2);
160
- }
161
- }
162
- }
163
- }
164
- });
165
- });
166
- }
167
- async dispose() {
168
- this._abortController.abort("MCP context disposed");
169
- await this.closeBrowserContext();
170
- Context._allContexts.delete(this);
171
- }
172
- async ensureBrowserContext() {
173
- const { browserContext } = await this._ensureBrowserContext();
174
- return browserContext;
175
- }
176
- _ensureBrowserContext() {
177
- if (!this._browserContextPromise) {
178
- this._browserContextPromise = this._setupBrowserContext();
179
- this._browserContextPromise.catch(() => {
180
- this._browserContextPromise = void 0;
181
- });
182
- }
183
- return this._browserContextPromise;
184
- }
185
- async _setupBrowserContext() {
186
- if (this._closeBrowserContextPromise)
187
- throw new Error("Another browser context is being closed.");
188
- if (this.config.testIdAttribute)
189
- import_playwright_core.selectors.setTestIdAttribute(this.config.testIdAttribute);
190
- const result = await this._browserContextFactory.createContext(this._clientInfo, this._abortController.signal, this._runningToolName);
191
- const { browserContext } = result;
192
-
193
- // ZIBBY: Inject stable ID script into every page
194
- const stableIdScriptPath = import_path.default.join(__dirname, '..', '..', 'src', 'stable-id-inject.js');
195
- if (import_fs.default.existsSync(stableIdScriptPath)) {
196
- await browserContext.addInitScript({ path: stableIdScriptPath });
197
- }
198
-
199
- if (this.sessionLog)
200
- await InputRecorder.create(this, browserContext);
201
- for (const page of browserContext.pages())
202
- this._onPageCreated(page);
203
- browserContext.on("page", (page) => this._onPageCreated(page));
204
- if (this.config.saveTrace) {
205
- await browserContext.tracing.start({
206
- name: "trace-" + Date.now(),
207
- screenshots: true,
208
- snapshots: true,
209
- _live: true
210
- });
211
- }
212
- return result;
213
- }
214
- lookupSecret(secretName) {
215
- if (!this.config.secrets?.[secretName])
216
- return { value: secretName, code: codegen.quote(secretName) };
217
- return {
218
- value: this.config.secrets[secretName],
219
- code: `process.env['${secretName}']`
220
- };
221
- }
222
- }
223
- class InputRecorder {
224
- constructor(context, browserContext) {
225
- this._context = context;
226
- this._browserContext = browserContext;
227
- }
228
- static async create(context, browserContext) {
229
- const recorder = new InputRecorder(context, browserContext);
230
- await recorder._initialize();
231
- return recorder;
232
- }
233
- async _initialize() {
234
- const sessionLog = this._context.sessionLog;
235
- await this._browserContext._enableRecorder({
236
- mode: "recording",
237
- recorderMode: "api"
238
- }, {
239
- actionAdded: (page, data, code) => {
240
- if (this._context.isRunningTool())
241
- return;
242
- const tab = import_tab.Tab.forPage(page);
243
- if (tab)
244
- sessionLog.logUserAction(data.action, tab, code, false);
245
- },
246
- actionUpdated: (page, data, code) => {
247
- if (this._context.isRunningTool())
248
- return;
249
- const tab = import_tab.Tab.forPage(page);
250
- if (tab)
251
- sessionLog.logUserAction(data.action, tab, code, true);
252
- },
253
- signalAdded: (page, data) => {
254
- if (this._context.isRunningTool())
255
- return;
256
- if (data.signal.name !== "navigation")
257
- return;
258
- const tab = import_tab.Tab.forPage(page);
259
- const navigateAction = {
260
- name: "navigate",
261
- url: data.signal.url,
262
- signals: []
263
- };
264
- if (tab)
265
- sessionLog.logUserAction(navigateAction, tab, `await page.goto('${data.signal.url}');`, false);
266
- }
267
- });
268
- }
269
- }
270
- // Annotate the CommonJS export names for ESM import in node:
271
- 0 && (module.exports = {
272
- Context,
273
- InputRecorder
274
- });