@applitools/mcp 0.10.4 → 0.10.6

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.
package/dist/index.js CHANGED
@@ -8,8 +8,8 @@ var promises = require('node:fs/promises');
8
8
  var path = require('node:path');
9
9
  var logger$1 = require('@applitools/logger');
10
10
  var coreBase = require('@applitools/core-base');
11
- var fs = require('node:fs');
12
11
  var dotenv = require('dotenv');
12
+ var fs = require('node:fs');
13
13
  var os = require('node:os');
14
14
  var crypto = require('node:crypto');
15
15
  var req = require('@applitools/req');
@@ -38,8 +38,8 @@ function _interopNamespaceDefault(e) {
38
38
  }
39
39
 
40
40
  var path__namespace = /*#__PURE__*/_interopNamespaceDefault(path);
41
- var fs__namespace = /*#__PURE__*/_interopNamespaceDefault(fs);
42
41
  var dotenv__namespace = /*#__PURE__*/_interopNamespaceDefault(dotenv);
42
+ var fs__namespace = /*#__PURE__*/_interopNamespaceDefault(fs);
43
43
  var os__namespace = /*#__PURE__*/_interopNamespaceDefault(os);
44
44
  var crypto__namespace = /*#__PURE__*/_interopNamespaceDefault(crypto);
45
45
  var zlib__namespace = /*#__PURE__*/_interopNamespaceDefault(zlib);
@@ -66,444 +66,141 @@ const RESOURCE_METADATA = {
66
66
  },
67
67
  };
68
68
 
69
- function loadEnvFile(workingDirectory) {
70
- const envPath = path__namespace.join(workingDirectory, '.env');
71
- if (!fs__namespace.existsSync(envPath)) {
72
- return {};
73
- }
74
- try {
75
- const content = fs__namespace.readFileSync(envPath, 'utf-8');
76
- const lines = content.split('\n');
77
- let apiKey;
78
- let serverUrl;
79
- for (const line of lines) {
80
- const trimmed = line.trim();
81
- // Skip empty lines and comments
82
- if (!trimmed || trimmed.startsWith('#')) {
83
- continue;
84
- }
85
- // Parse KEY=VALUE
86
- const match = trimmed.match(/^([^=]+)=(.*)$/);
87
- if (!match)
88
- continue;
89
- const key = match[1].trim();
90
- let value = match[2].trim();
91
- // Remove quotes if present
92
- if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) {
93
- value = value.slice(1, -1);
94
- }
95
- if (key === 'APPLITOOLS_API_KEY' && value) {
96
- apiKey = value;
97
- }
98
- else if (key === 'APPLITOOLS_SERVER_URL' && value) {
99
- serverUrl = value;
100
- }
101
- }
102
- if (apiKey) {
103
- return { apiKey, serverUrl, foundIn: '.env' };
104
- }
105
- }
106
- catch {
107
- // Silently ignore errors reading .env
108
- }
109
- return {};
110
- }
111
69
  /**
112
- * Helper to resolve environment variable references in config files
113
- * Checks if the content references an env var, then resolves from process.env or .env file
70
+ * Wraps already-resolved key strings. A getter throws a clear error if its key wasn't supplied —
71
+ * e.g. a write key deliberately withheld when building a provider for a read-only call — rather
72
+ * than returning `undefined` and letting a missing credential fail confusingly further down.
114
73
  */
115
- function resolveEnvVarFromContent(content, envVarName, workingDirectory) {
116
- // Check if content references the environment variable (with or without process.env prefix)
117
- const patterns = [
118
- new RegExp(`process\\.env\\.${envVarName}`, 'i'),
119
- new RegExp(`${envVarName}(?!['"])`, 'i'), // Bare reference (not in quotes)
120
- ];
121
- const hasReference = patterns.some(pattern => pattern.test(content));
122
- if (!hasReference) {
123
- return undefined;
74
+ class StaticApiKeyProvider {
75
+ keys;
76
+ constructor(keys) {
77
+ this.keys = keys;
124
78
  }
125
- // Try to resolve the value: first from process.env, then from .env file
126
- const envValue = process.env[envVarName];
127
- if (envValue) {
128
- return envValue;
79
+ getReadKey() {
80
+ return this.require('readKey', 'read');
129
81
  }
130
- // Fallback to .env file
131
- const envResult = loadEnvFile(workingDirectory);
132
- if (envVarName === 'APPLITOOLS_API_KEY') {
133
- return envResult.apiKey;
82
+ getWriteKey() {
83
+ return this.require('writeKey', 'write');
134
84
  }
135
- else if (envVarName === 'APPLITOOLS_SERVER_URL') {
136
- return envResult.serverUrl;
85
+ getRunKey() {
86
+ return this.require('runKey', 'run');
137
87
  }
138
- return undefined;
139
- }
140
- function loadConfigFile(configPath, fileName, workingDirectory) {
141
- if (!fs__namespace.existsSync(configPath)) {
142
- return {};
88
+ require(field, label) {
89
+ const key = this.keys[field];
90
+ if (key === undefined)
91
+ throw new Error(`No ${label} API key is available for this call.`);
92
+ return key;
143
93
  }
144
- try {
145
- const content = fs__namespace.readFileSync(configPath, 'utf-8');
146
- // Search for apiKey and serverUrl in the file content
147
- let apiKey;
148
- let serverUrl;
149
- // Pattern 1: apiKey: 'value' or apiKey: "value" (hardcoded values)
150
- const apiKeyMatch = content.match(/apiKey\s*:\s*['"]([^'"]+)['"]/i);
151
- if (apiKeyMatch) {
152
- apiKey = apiKeyMatch[1];
153
- }
154
- // Pattern 2: serverUrl: 'value' or serverUrl: "value" (hardcoded values)
155
- const serverUrlMatch = content.match(/serverUrl\s*:\s*['"]([^'"]+)['"]/i);
156
- if (serverUrlMatch) {
157
- serverUrl = serverUrlMatch[1];
158
- }
159
- // Pattern 3: Resolve environment variable references in config file
160
- if (!apiKey) {
161
- apiKey = resolveEnvVarFromContent(content, 'APPLITOOLS_API_KEY', workingDirectory);
94
+ }
95
+
96
+ const defaultLoadEnvDeps = {
97
+ existsSync: fs__namespace.existsSync,
98
+ configDotenv: ({ path }) => {
99
+ try {
100
+ return { parsed: dotenv__namespace.parse(fs__namespace.readFileSync(path)) };
162
101
  }
163
- if (!serverUrl) {
164
- serverUrl = resolveEnvVarFromContent(content, 'APPLITOOLS_SERVER_URL', workingDirectory);
102
+ catch {
103
+ return {};
165
104
  }
166
- if (apiKey) {
167
- return { apiKey, serverUrl, foundIn: fileName };
105
+ },
106
+ };
107
+ /** The variables `loadEnvFromCwd` reads from a `.env`: the keys and the server URL the Eyes tools use. */
108
+ const WORKSPACE_ENV_NAMES = [
109
+ 'APPLITOOLS_API_KEY',
110
+ 'APPLITOOLS_READ_KEY',
111
+ 'APPLITOOLS_WRITE_KEY',
112
+ 'APPLITOOLS_SERVER_URL',
113
+ ];
114
+ /** The nearest `.env` up from `startDir` that defines any of `WORKSPACE_ENV_NAMES`; never writes `process.env`. */
115
+ function loadEnvFromCwd(startDir = process.cwd(), deps = defaultLoadEnvDeps) {
116
+ let dir = startDir;
117
+ while (true) {
118
+ const envPath = path__namespace.join(dir, '.env');
119
+ if (deps.existsSync(envPath)) {
120
+ const result = deps.configDotenv({ path: envPath });
121
+ const parsed = Object.fromEntries(WORKSPACE_ENV_NAMES.flatMap(name => (result?.parsed?.[name] ? [[name, result.parsed[name]]] : [])));
122
+ if (Object.keys(parsed).length)
123
+ return { path: envPath, parsed };
168
124
  }
125
+ const parent = path__namespace.dirname(dir);
126
+ if (parent === dir)
127
+ return undefined;
128
+ dir = parent;
169
129
  }
170
- catch {
171
- // Silently ignore errors reading config file
172
- }
173
- return {};
174
130
  }
175
- function findApiKey(workingDirectory = process.cwd()) {
176
- // Define config file patterns to check (in priority order)
177
- const configFiles = [
178
- // Applitools config files
179
- { name: 'applitools.config.js', path: path__namespace.join(workingDirectory, 'applitools.config.js') },
180
- { name: 'applitools.config.cjs', path: path__namespace.join(workingDirectory, 'applitools.config.cjs') },
181
- { name: 'applitools.config.mjs', path: path__namespace.join(workingDirectory, 'applitools.config.mjs') },
182
- { name: 'applitools.config.ts', path: path__namespace.join(workingDirectory, 'applitools.config.ts') },
183
- // Playwright config files
184
- { name: 'playwright.config.js', path: path__namespace.join(workingDirectory, 'playwright.config.js') },
185
- { name: 'playwright.config.cjs', path: path__namespace.join(workingDirectory, 'playwright.config.cjs') },
186
- { name: 'playwright.config.mjs', path: path__namespace.join(workingDirectory, 'playwright.config.mjs') },
187
- { name: 'playwright.config.ts', path: path__namespace.join(workingDirectory, 'playwright.config.ts') },
188
- ];
189
- // 1. Check each config file in order (config files have priority over .env)
190
- for (const config of configFiles) {
191
- const result = loadConfigFile(config.path, config.name, workingDirectory);
192
- if (result.apiKey) {
193
- return result;
131
+
132
+ const RETRYABLE_CODES = new Set(['EBUSY', 'EPERM', 'EACCES', 'EAGAIN']);
133
+ const RETRY_ATTEMPTS = 5;
134
+ const RETRY_BASE_DELAY_MS = 20;
135
+ /**
136
+ * A synchronous blocking sleep (`Atomics.wait` against a throwaway shared buffer) — matches
137
+ * the rest of this codebase's synchronous fs style (`fs.readFileSync`/`writeFileSync`
138
+ * throughout `commands.ts`), rather than forcing every phase-tracker call to be async merely
139
+ * to await a short backoff delay.
140
+ */
141
+ function busyWaitSleep(ms) {
142
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
143
+ }
144
+ const defaultPhaseTrackerDeps = {
145
+ readFile: p => (fs__namespace.existsSync(p) ? fs__namespace.readFileSync(p, 'utf8') : null),
146
+ writeFile: (p, contents) => fs__namespace.writeFileSync(p, contents),
147
+ appendFile: (p, contents) => fs__namespace.appendFileSync(p, contents),
148
+ deleteFile: p => fs__namespace.rmSync(p, { force: true }),
149
+ mkdir: dir => fs__namespace.mkdirSync(dir, { recursive: true }),
150
+ sleep: busyWaitSleep,
151
+ stateDir: path__namespace.join(os__namespace.tmpdir(), 'eyes-resolve'),
152
+ };
153
+ /**
154
+ * Retries `fn` on a transient file-lock error (a momentarily-locked file must never crash a
155
+ * workflow call — see `lib.md`), with a short exponential backoff between attempts. Any other
156
+ * error (including a non-`Error` throw with no `.code`) propagates immediately, unretried.
157
+ */
158
+ function withRetry(fn, deps) {
159
+ for (let attempt = 0;; attempt++) {
160
+ try {
161
+ return fn();
162
+ }
163
+ catch (error) {
164
+ const code = error?.code;
165
+ if (attempt >= RETRY_ATTEMPTS - 1 || !code || !RETRYABLE_CODES.has(code))
166
+ throw error;
167
+ deps.sleep(RETRY_BASE_DELAY_MS * 2 ** attempt);
194
168
  }
195
169
  }
196
- // 2. Check .env file as fallback
197
- const envResult = loadEnvFile(workingDirectory);
198
- if (envResult.apiKey) {
199
- return envResult;
200
- }
201
- // 3. Check environment variables as final fallback
202
- const envApiKey = process.env.APPLITOOLS_API_KEY;
203
- const envServerUrl = process.env.APPLITOOLS_SERVER_URL;
204
- if (envApiKey) {
205
- return {
206
- apiKey: envApiKey,
207
- serverUrl: envServerUrl,
208
- foundIn: 'environment variable',
209
- };
210
- }
211
- // Not found
212
- return {};
213
170
  }
214
-
215
- let currentClientInfo = undefined;
216
- let currentCredentials = undefined;
217
- let ide = undefined;
218
- function setClientInfo(clientInfo) {
219
- currentClientInfo = clientInfo;
171
+ function hashId(id) {
172
+ return crypto__namespace.createHash('sha256').update(id).digest('hex');
220
173
  }
221
- function getClientInfo() {
222
- return currentClientInfo;
174
+ // path.posix.join/dirname (not path.join/dirname) so the result is deterministic across
175
+ // platforms — Node's fs APIs accept forward slashes on Windows too (same convention as
176
+ // `api/fs-cache.ts`'s `cacheFilePath`).
177
+ function recordPath(deps, kind, id) {
178
+ return path__namespace.posix.join(deps.stateDir, kind, `${hashId(id)}.json`);
223
179
  }
224
- function setCredentials(credentials) {
225
- currentCredentials = credentials;
180
+ function readJson(deps, filePath) {
181
+ const contents = withRetry(() => deps.readFile(filePath), deps);
182
+ return contents === null ? undefined : JSON.parse(contents);
226
183
  }
227
- function getCredentials() {
228
- return currentCredentials;
184
+ function writeJson(deps, filePath, value) {
185
+ withRetry(() => deps.mkdir(path__namespace.posix.dirname(filePath)), deps);
186
+ withRetry(() => deps.writeFile(filePath, JSON.stringify(value)), deps);
229
187
  }
230
- function setIDE(ideName) {
231
- ide = ideName;
188
+ /** The recorded completion for `id`, or `undefined` if `<level>_end` was never (successfully) called for it. */
189
+ function getCompletion(id, deps = defaultPhaseTrackerDeps) {
190
+ return readJson(deps, recordPath(deps, 'completions', id));
232
191
  }
233
- function getIDE() {
234
- return ide;
192
+ function isCompleted(id, deps = defaultPhaseTrackerDeps) {
193
+ return getCompletion(id, deps) !== undefined;
235
194
  }
236
- function parseIDE(env, argv) {
237
- var _a;
238
- return env['ide'] || ((_a = argv.find(arg => arg.startsWith('--ide='))) === null || _a === void 0 ? void 0 : _a.split('=')[1]) || 'unknown';
239
- }
240
- /** Evaluated once at process start; off unless `EXPERIMENTAL_ENV` is `1`/`true` (any case). */
241
- function parseExperimental(env) {
242
- var _a;
243
- return ['1', 'true'].includes(((_a = env[EXPERIMENTAL_ENV]) !== null && _a !== void 0 ? _a : '').toLowerCase());
244
- }
245
-
246
- /** Load credentials from server context, config files, or environment variables */
247
- function loadCredentials(workingDirectory) {
248
- const storedCredentials = getCredentials();
249
- if ((storedCredentials === null || storedCredentials === void 0 ? void 0 : storedCredentials.apiKey) && (storedCredentials === null || storedCredentials === void 0 ? void 0 : storedCredentials.serverUrl)) {
250
- return {
251
- apiKey: storedCredentials.apiKey,
252
- serverUrl: storedCredentials.serverUrl,
253
- source: 'server-context',
254
- };
255
- }
256
- const workingDir = workingDirectory || process.cwd();
257
- const configResult = findApiKey(workingDir);
258
- const apiKey = configResult.apiKey;
259
- const serverUrl = configResult.serverUrl || DEFAULT_SERVER_URL;
260
- const source = configResult.foundIn;
261
- return { apiKey, serverUrl, source };
262
- }
263
- /** Load and store credentials in server context */
264
- function loadAndStoreCredentials(workingDirectory) {
265
- const result = loadCredentials(workingDirectory);
266
- if (result.apiKey && result.serverUrl) {
267
- setCredentials({
268
- apiKey: result.apiKey,
269
- serverUrl: result.serverUrl,
270
- });
271
- return true;
272
- }
273
- return false;
274
- }
275
- /** Get credentials for external logging */
276
- function getCredentialsForLogging() {
277
- const result = loadCredentials();
278
- return {
279
- apiKey: result.apiKey,
280
- serverUrl: result.serverUrl || DEFAULT_SERVER_URL,
281
- };
282
- }
283
-
284
- const handler = (() => {
285
- if (process.env.APPLITOOLS_LOG_FILE) {
286
- return logger$1.makeFileHandler({ filename: process.env.APPLITOOLS_LOG_FILE });
287
- }
288
- else if (process.env.APPLITOOLS_LOG_DIR) {
289
- return logger$1.makeRollingFileHandler({ dirname: process.env.APPLITOOLS_LOG_DIR });
290
- }
291
- // Default to stderr to avoid interfering with MCP stdio protocol
292
- return {
293
- // eslint-disable-next-line no-console
294
- log: (message) => console.error(message),
295
- // eslint-disable-next-line no-console
296
- warn: (message) => console.warn(message),
297
- // eslint-disable-next-line no-console
298
- error: (message) => console.error(message),
299
- };
300
- })();
301
- // Only perform expensive serialisation when a log sink is explicitly configured.
302
- const isVerboseLogging = !!(process.env.APPLITOOLS_LOG_FILE ||
303
- process.env.APPLITOOLS_LOG_DIR ||
304
- process.env.APPLITOOLS_SHOW_LOGS);
305
- const logger = logger$1.makeLogger({ level: 'all', handler });
306
- const externalLogger = coreBase.makeCore({
307
- agentId: 'mcp-tool-handler',
308
- maskLog: false,
309
- logger,
310
- offlineLocationPath: undefined,
311
- });
312
- function log$2(level, ...args) {
313
- logger[level](level, ...args);
314
- }
315
- async function externalLog(eventName, data, level = 'Notice') {
316
- // Get credentials using centralized loader
317
- const { apiKey, serverUrl: eyesServerUrl } = getCredentialsForLogging();
318
- if (!apiKey || apiKey === '') {
319
- logger.warn(`Cannot log external event ${eventName} - no API key configured`);
320
- return;
321
- }
322
- try {
323
- await externalLogger.logEvent({
324
- settings: {
325
- apiKey,
326
- eyesServerUrl,
327
- level,
328
- event: {
329
- type: eventName,
330
- data: data || {},
331
- },
332
- },
333
- logger,
334
- });
335
- }
336
- catch (error) {
337
- logger.error(`Failed to log external event ${eventName}:`, error);
338
- }
339
- }
340
-
341
- /**
342
- * Documentation Resource
343
- *
344
- * Exposes the comprehensive README documentation for the Applitools MCP server
345
- */
346
- /**
347
- * Read documentation resource content
348
- */
349
- async function readDocumentationResource(uri) {
350
- // Validate URI first (don't log validation errors)
351
- if (uri !== RESOURCE_URIS.DOCUMENTATION_README) {
352
- throw new Error(`Unknown resource URI: ${uri}`);
353
- }
354
- try {
355
- // Determine the correct path based on whether we're running from source or dist
356
- // In production: dist/resources/documentation/index.js -> dist/docs/README.md
357
- // In tests: src/resources/documentation/index.ts -> docs/README.md
358
- let docsPath;
359
- if (/[\\/]dist(?:[\\/]|$)/.test(__dirname)) {
360
- // Running from compiled dist (standalone or VS Code extension)
361
- // Expect docs folder to be sibling of the script
362
- docsPath = path.join(__dirname, 'docs/README.md');
363
- }
364
- else {
365
- // Running from source (tests)
366
- docsPath = path.join(__dirname, '../../../docs/README.md');
367
- }
368
- const content = await promises.readFile(docsPath, 'utf-8');
369
- return {
370
- contents: [
371
- {
372
- uri,
373
- text: content,
374
- mimeType: 'text/markdown',
375
- },
376
- ],
377
- };
378
- }
379
- catch (error) {
380
- // Only log unexpected errors (file system errors, not validation errors)
381
- log$2('error', '[Resources] Failed to read documentation:', error);
382
- throw new Error(`Failed to read documentation: ${error instanceof Error ? error.message : String(error)}`);
383
- }
384
- }
385
-
386
- /**
387
- * Wraps already-resolved key strings. A getter throws a clear error if its key wasn't supplied —
388
- * e.g. a write key deliberately withheld when building a provider for a read-only call — rather
389
- * than returning `undefined` and letting a missing credential fail confusingly further down.
390
- */
391
- class StaticApiKeyProvider {
392
- keys;
393
- constructor(keys) {
394
- this.keys = keys;
395
- }
396
- getReadKey() {
397
- return this.require('readKey', 'read');
398
- }
399
- getWriteKey() {
400
- return this.require('writeKey', 'write');
401
- }
402
- getRunKey() {
403
- return this.require('runKey', 'run');
404
- }
405
- require(field, label) {
406
- const key = this.keys[field];
407
- if (key === undefined)
408
- throw new Error(`No ${label} API key is available for this call.`);
409
- return key;
410
- }
411
- }
412
-
413
- const defaultLoadEnvDeps = {
414
- existsSync: fs__namespace.existsSync,
415
- configDotenv: dotenv__namespace.config,
416
- };
417
- function loadEnvFromCwd(startDir = process.cwd(), deps = defaultLoadEnvDeps) {
418
- let dir = startDir;
419
- while (true) {
420
- const envPath = path__namespace.join(dir, '.env');
421
- if (deps.existsSync(envPath)) {
422
- const preset = new Set(Object.keys(process.env));
423
- const result = deps.configDotenv({ path: envPath });
424
- const parsed = result?.parsed ?? {};
425
- const applied = Object.keys(parsed).filter(name => !preset.has(name));
426
- return { path: envPath, applied, parsed };
427
- }
428
- const parent = path__namespace.dirname(dir);
429
- if (parent === dir)
430
- return undefined;
431
- dir = parent;
432
- }
433
- }
434
-
435
- const RETRYABLE_CODES = new Set(['EBUSY', 'EPERM', 'EACCES', 'EAGAIN']);
436
- const RETRY_ATTEMPTS = 5;
437
- const RETRY_BASE_DELAY_MS = 20;
438
- /**
439
- * A synchronous blocking sleep (`Atomics.wait` against a throwaway shared buffer) — matches
440
- * the rest of this codebase's synchronous fs style (`fs.readFileSync`/`writeFileSync`
441
- * throughout `commands.ts`), rather than forcing every phase-tracker call to be async merely
442
- * to await a short backoff delay.
443
- */
444
- function busyWaitSleep(ms) {
445
- Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
446
- }
447
- const defaultPhaseTrackerDeps = {
448
- readFile: p => (fs__namespace.existsSync(p) ? fs__namespace.readFileSync(p, 'utf8') : null),
449
- writeFile: (p, contents) => fs__namespace.writeFileSync(p, contents),
450
- appendFile: (p, contents) => fs__namespace.appendFileSync(p, contents),
451
- deleteFile: p => fs__namespace.rmSync(p, { force: true }),
452
- mkdir: dir => fs__namespace.mkdirSync(dir, { recursive: true }),
453
- sleep: busyWaitSleep,
454
- stateDir: path__namespace.join(os__namespace.tmpdir(), 'eyes-resolve'),
455
- };
456
- /**
457
- * Retries `fn` on a transient file-lock error (a momentarily-locked file must never crash a
458
- * workflow call — see `lib.md`), with a short exponential backoff between attempts. Any other
459
- * error (including a non-`Error` throw with no `.code`) propagates immediately, unretried.
460
- */
461
- function withRetry(fn, deps) {
462
- for (let attempt = 0;; attempt++) {
463
- try {
464
- return fn();
465
- }
466
- catch (error) {
467
- const code = error?.code;
468
- if (attempt >= RETRY_ATTEMPTS - 1 || !code || !RETRYABLE_CODES.has(code))
469
- throw error;
470
- deps.sleep(RETRY_BASE_DELAY_MS * 2 ** attempt);
471
- }
472
- }
473
- }
474
- function hashId(id) {
475
- return crypto__namespace.createHash('sha256').update(id).digest('hex');
476
- }
477
- // path.posix.join/dirname (not path.join/dirname) so the result is deterministic across
478
- // platforms — Node's fs APIs accept forward slashes on Windows too (same convention as
479
- // `api/fs-cache.ts`'s `cacheFilePath`).
480
- function recordPath(deps, kind, id) {
481
- return path__namespace.posix.join(deps.stateDir, kind, `${hashId(id)}.json`);
482
- }
483
- function readJson(deps, filePath) {
484
- const contents = withRetry(() => deps.readFile(filePath), deps);
485
- return contents === null ? undefined : JSON.parse(contents);
486
- }
487
- function writeJson(deps, filePath, value) {
488
- withRetry(() => deps.mkdir(path__namespace.posix.dirname(filePath)), deps);
489
- withRetry(() => deps.writeFile(filePath, JSON.stringify(value)), deps);
490
- }
491
- /** The recorded completion for `id`, or `undefined` if `<level>_end` was never (successfully) called for it. */
492
- function getCompletion(id, deps = defaultPhaseTrackerDeps) {
493
- return readJson(deps, recordPath(deps, 'completions', id));
494
- }
495
- function isCompleted(id, deps = defaultPhaseTrackerDeps) {
496
- return getCompletion(id, deps) !== undefined;
497
- }
498
- /**
499
- * Persists `payload` as `id`'s completion, stamped with the current time — overwriting
500
- * whatever was recorded for `id` before, so revising a summary (or refreshing a stale
501
- * completion) is just calling this again.
502
- */
503
- function recordCompletion(id, payload, deps = defaultPhaseTrackerDeps) {
504
- const completion = { payload, completedAt: new Date().toISOString() };
505
- writeJson(deps, recordPath(deps, 'completions', id), completion);
506
- return completion;
195
+ /**
196
+ * Persists `payload` as `id`'s completion, stamped with the current time — overwriting
197
+ * whatever was recorded for `id` before, so revising a summary (or refreshing a stale
198
+ * completion) is just calling this again.
199
+ */
200
+ function recordCompletion(id, payload, deps = defaultPhaseTrackerDeps) {
201
+ const completion = { payload, completedAt: new Date().toISOString() };
202
+ writeJson(deps, recordPath(deps, 'completions', id), completion);
203
+ return completion;
507
204
  }
508
205
  /** `parentId`'s full accumulated child-findings record, read as-is with no live-data filtering. `{}` if no child has ever reported into it. */
509
206
  function getChildFindings(parentId, deps = defaultPhaseTrackerDeps) {
@@ -661,7 +358,7 @@ function getLogFilePath(scopeId, deps = defaultPhaseTrackerDeps) {
661
358
  * lock-retry backoff (`withRetry`) as every other record this module writes, so a caller never
662
359
  * has to poll for the file to become available itself; a momentarily-busy append just retries.
663
360
  */
664
- function log$1(scopeId, label, fields = {}, deps = defaultPhaseTrackerDeps) {
361
+ function log$2(scopeId, label, fields = {}, deps = defaultPhaseTrackerDeps) {
665
362
  const entry = { at: new Date().toISOString(), label, ...fields };
666
363
  withRetry(() => deps.mkdir(debugLogDir(deps)), deps);
667
364
  withRetry(() => deps.appendFile(getLogFilePath(scopeId, deps), `${JSON.stringify(entry)}\n`), deps);
@@ -3299,7 +2996,37 @@ function parseBatchUrl(url) {
3299
2996
  return { ...parsed, sessionId: null };
3300
2997
  }
3301
2998
 
3302
- // Same convention as core-base's reqEyes: `expected` is enforced by an afterResponse hook, so
2999
+ /** The only domains an API key is ever sent to: a request host must be one of them or a subdomain of one. */
3000
+ const SAFE_DOMAINS = ['applitools.com'];
3001
+ // The first rule `url` breaks, worded for the user and naming at most the hostname; undefined when it may receive a key.
3002
+ function refusalReason(url) {
3003
+ let parsed;
3004
+ try {
3005
+ parsed = new URL(url);
3006
+ }
3007
+ catch {
3008
+ return 'the URL could not be parsed';
3009
+ }
3010
+ const { hostname, protocol, username, password } = parsed;
3011
+ if (!SAFE_DOMAINS.some(domain => hostname === domain || hostname.endsWith(`.${domain}`))) {
3012
+ return `${hostname || 'the URL'} is not an Applitools host`;
3013
+ }
3014
+ if (protocol !== 'https:')
3015
+ return `${hostname} is addressed over ${protocol.slice(0, -1)}, and keys are sent over https only`;
3016
+ if (username || password)
3017
+ return `the URL for ${hostname} contains a user name or password, which keys are never sent with`;
3018
+ return undefined;
3019
+ }
3020
+ function isTrustedEyesUrl(url) {
3021
+ return refusalReason(url) === undefined;
3022
+ }
3023
+ function assertTrustedEyesUrl(url) {
3024
+ const reason = refusalReason(url);
3025
+ if (reason)
3026
+ throw new Error(`${reason}, so the request was not sent`);
3027
+ }
3028
+
3029
+ // Same convention as core-base's reqEyes: `expected` is enforced by an afterResponse hook, so
3303
3030
  // call sites branch only on the statuses that carry meaning for them.
3304
3031
  function handleUnexpectedResponse() {
3305
3032
  return {
@@ -3338,9 +3065,38 @@ function isolateRetryPerRequest() {
3338
3065
  },
3339
3066
  };
3340
3067
  }
3068
+ // Kept last on every request: req appends per-call hooks after the instance's, and any earlier
3069
+ // beforeRequest may still return a request with a different URL.
3070
+ function guardDestination() {
3071
+ const guard = {
3072
+ afterOptionsMerged({ options }) {
3073
+ const hooks = [].concat(options.hooks ?? []);
3074
+ return { ...options, hooks: [...hooks.filter(hook => hook !== guard), guard] };
3075
+ },
3076
+ beforeRequest({ request }) {
3077
+ assertTrustedEyesUrl(request.url);
3078
+ // node-fetch forwards custom headers, the key's included, across a cross-origin redirect.
3079
+ return { request, redirect: 'error' };
3080
+ },
3081
+ };
3082
+ return guard;
3083
+ }
3084
+ /** Paths whose endpoint accepts the key only as the `apiKey` query parameter; every other request carries it as a header only. */
3085
+ const QUERY_AUTH_PATHS = [];
3086
+ /** The task-status endpoint answers without a key, so a request to it carries none. */
3087
+ const KEYLESS_PATH = /^\/api\/tasks\/[^/]+\/status$/;
3088
+ // Older api modules bake `apiKey=` into the URLs they pass in, so the parameter is settled here per path.
3089
+ function withQueryAuth(input, serverUrl, apiKey) {
3090
+ const url = new URL(String(input), serverUrl.endsWith('/') ? serverUrl : `${serverUrl}/`);
3091
+ if (QUERY_AUTH_PATHS.some(path => path.test(url.pathname)))
3092
+ url.searchParams.set('apiKey', apiKey);
3093
+ else
3094
+ url.searchParams.delete('apiKey');
3095
+ return url;
3096
+ }
3341
3097
  /**
3342
3098
  * Builds a configured `req` — core-base's `makeReqEyes` concept adapted to this package: the
3343
- * instance owns the server URL, the `apiKey` query parameter, the transient-retry policy, and the
3099
+ * instance owns the server URL, the API key, the transient-retry policy, and the
3344
3100
  * `expected`-status convention above, so api functions take the configured req plus business
3345
3101
  * parameters and never thread baseUrl/apiKey/transport themselves. Flat options on purpose: an api
3346
3102
  * function's own deps spread straight in — `makeReqResults({serverUrl, apiKey, ...deps})`.
@@ -3355,9 +3111,11 @@ function isolateRetryPerRequest() {
3355
3111
  * calls through a single instance and pins both properties.
3356
3112
  */
3357
3113
  function makeReqResults({ serverUrl, apiKey, fetch, logger }) {
3358
- return req.makeReq({
3114
+ const req$1 = req.makeReq({
3359
3115
  baseUrl: serverUrl,
3360
- query: { apiKey },
3116
+ headers: { 'X-Eyes-Api-Key': apiKey },
3117
+ // req's HTTP/2 path rebuilds the request without its `redirect` mode.
3118
+ httpVersion: 1,
3361
3119
  retry: {
3362
3120
  limit: 5,
3363
3121
  timeout: [200, 400, 800, 1600, 3200],
@@ -3370,10 +3128,19 @@ function makeReqResults({ serverUrl, apiKey, fetch, logger }) {
3370
3128
  // needs its own timeout to not hang forever.
3371
3129
  requestTimeout: 30000,
3372
3130
  connectionTimeout: 300000,
3373
- hooks: [isolateRetryPerRequest(), handleUnexpectedResponse()],
3131
+ hooks: [isolateRetryPerRequest(), handleUnexpectedResponse(), guardDestination()],
3374
3132
  fetch,
3375
3133
  logger,
3376
3134
  });
3135
+ return (input, options) => {
3136
+ if (typeof input !== 'string' && !(input instanceof URL))
3137
+ return req$1(input, options);
3138
+ const url = withQueryAuth(input, serverUrl, apiKey);
3139
+ if (!KEYLESS_PATH.test(url.pathname))
3140
+ return req$1(url, options);
3141
+ // An empty value overrides the instance's key header, and req drops empty-valued headers.
3142
+ return req$1(url, { ...options, headers: { ...options?.headers, 'X-Eyes-Api-Key': '' } });
3143
+ };
3377
3144
  }
3378
3145
 
3379
3146
  /**
@@ -3987,140 +3754,483 @@ async function compareStep(body, options, fetchImpl = reqTransport) {
3987
3754
  const response = await postJson(url, body, fetchImpl);
3988
3755
  return getJsonResult(response, apiKey, fetchImpl, undefined, url);
3989
3756
  }
3990
-
3991
- /**
3992
- * Given a reference step and a candidate list of other steps, returns which of `steps` actually
3993
- * have the same diff as `reference` — the real target steps an accept/reject decision should
3994
- * propagate to, as opposed to every step a scenario-name match happened to include. `image1`/
3995
- * `image2` here are plain baseline/checkpoint image id strings, not full `ImageRecord` objects
3996
- * (unlike `compareStep`'s own request shape) — each entry (including `reference`) carries its
3997
- * own step's `matchSettings`, never another step's.
3998
- *
3999
- * Confirmed live: an async job (202 + Location), same as every other endpoint in this file.
4000
- * **The result is `number[]` — zero-based indices into the request's own `steps` array, e.g.
4001
- * `[0, 1]` meaning `steps[0]` and `steps[1]` both matched — never step objects, and never
4002
- * `{sessionId, stepIndex}` identifiers.** A caller must resolve each index back against its own
4003
- * original `steps`/candidate array; the response carries nothing else to identify a match by.
4004
- * When nothing in `steps` matches `reference`, the job's own result is `204 No Content` — an
4005
- * empty body, which `getJsonResult` parses as `undefined` — normalized here to `[]` so callers
4006
- * can always assume an array.
4007
- */
4008
- async function findSameDiffSteps(body, options, fetchImpl = reqTransport) {
4009
- const { baseUrl, accountId, keys } = options;
4010
- const apiKey = keys.getReadKey();
4011
- const url = `${baseUrl}/api/sessions/steps/samediffas?accountId=${accountId}&apiKey=${encodeURIComponent(apiKey)}`;
4012
- const response = await postJson(url, body, fetchImpl);
4013
- return (await getJsonResult(response, apiKey, fetchImpl, undefined, url)) ?? [];
3757
+
3758
+ /**
3759
+ * Given a reference step and a candidate list of other steps, returns which of `steps` actually
3760
+ * have the same diff as `reference` — the real target steps an accept/reject decision should
3761
+ * propagate to, as opposed to every step a scenario-name match happened to include. `image1`/
3762
+ * `image2` here are plain baseline/checkpoint image id strings, not full `ImageRecord` objects
3763
+ * (unlike `compareStep`'s own request shape) — each entry (including `reference`) carries its
3764
+ * own step's `matchSettings`, never another step's.
3765
+ *
3766
+ * Confirmed live: an async job (202 + Location), same as every other endpoint in this file.
3767
+ * **The result is `number[]` — zero-based indices into the request's own `steps` array, e.g.
3768
+ * `[0, 1]` meaning `steps[0]` and `steps[1]` both matched — never step objects, and never
3769
+ * `{sessionId, stepIndex}` identifiers.** A caller must resolve each index back against its own
3770
+ * original `steps`/candidate array; the response carries nothing else to identify a match by.
3771
+ * When nothing in `steps` matches `reference`, the job's own result is `204 No Content` — an
3772
+ * empty body, which `getJsonResult` parses as `undefined` — normalized here to `[]` so callers
3773
+ * can always assume an array.
3774
+ */
3775
+ async function findSameDiffSteps(body, options, fetchImpl = reqTransport) {
3776
+ const { baseUrl, accountId, keys } = options;
3777
+ const apiKey = keys.getReadKey();
3778
+ const url = `${baseUrl}/api/sessions/steps/samediffas?accountId=${accountId}&apiKey=${encodeURIComponent(apiKey)}`;
3779
+ const response = await postJson(url, body, fetchImpl);
3780
+ return (await getJsonResult(response, apiKey, fetchImpl, undefined, url)) ?? [];
3781
+ }
3782
+
3783
+ // findNodeBySelector/findNodeByRect return a nested {domSelector, rect} shape (DomNode);
3784
+ // the Region shape needed elsewhere is flat (domSelector alongside left/top/width/height).
3785
+ function toRegion$1(resolved) {
3786
+ return { domSelector: resolved.domSelector, ...resolved.rect };
3787
+ }
3788
+ /**
3789
+ * Maps every `anchored` pair's `domSelector` to the other side via one batched
3790
+ * get-compatible-selectors call, resolving each mapped selector's accurate rect locally
3791
+ * against that side's DOM (the API only returns the mapped selector, never a rect). Falls
3792
+ * back to treating every selector as unmapped if the batch call itself fails for some reason
3793
+ * other than a bad input selector (`sessions`'s own `checkRegions` already filters those out).
3794
+ * Mutates each pair's missing side in place. Returns whether anything was attempted (i.e.
3795
+ * `anchored` was non-empty and both sides have an image to map between).
3796
+ *
3797
+ * Lives here, not in `atoms/sessions` (where the rest of the region-healing pipeline this composes
3798
+ * into — `checkRegions`/`clearStaleSelectors`/`healNonAnchoredRegionsBySourceRect` — lives):
3799
+ * this is the one step of that pipeline that actually calls the network (`getCompatibleSelectors`),
3800
+ * and `atoms` must never depend on `api`/`common` (so it can't reference `ApiKeyProvider` or make
3801
+ * network calls) — the orchestration belongs in `common`, which depends on both instead.
3802
+ */
3803
+ async function mapAnchoredRegionsBySelector(rawSession, stepIndex, anchored, deps) {
3804
+ if (anchored.length === 0)
3805
+ return false;
3806
+ const sourceSide = resolveDomIdSide('unchanged', rawSession, stepIndex);
3807
+ const missingSide = sourceSide === 'baseline' ? 'checkpoint' : 'baseline';
3808
+ const imageSource = imageForSide(rawSession, stepIndex, sourceSide);
3809
+ const imageMissing = imageForSide(rawSession, stepIndex, missingSide);
3810
+ if (!imageSource || !imageMissing)
3811
+ return false;
3812
+ const domMissing = await deps.fetchDomForSide(rawSession, stepIndex, missingSide, deps.baseUrl).catch(() => null);
3813
+ // `anchored` pairs are guaranteed a truthy domSelector by checkRegions's own definition of "anchored".
3814
+ const selectors = anchored.map(p => (p.baseline ?? p.checkpoint).domSelector);
3815
+ let mapped;
3816
+ try {
3817
+ mapped = await deps.getCompatibleSelectors({ baseUrl: deps.baseUrl, accountId: deps.accountId, keys: deps.keys }, imageSource, imageMissing, selectors);
3818
+ }
3819
+ catch {
3820
+ mapped = selectors.map(() => null); // the batch itself failed — treat every one as unmapped rather than throwing
3821
+ }
3822
+ anchored.forEach((pair, i) => {
3823
+ const newSelector = mapped[i];
3824
+ const resolved = newSelector && domMissing ? findNodeBySelector(domMissing, newSelector) : null;
3825
+ pair[missingSide] = resolved
3826
+ ? toRegion$1(resolved)
3827
+ : { ...(pair.baseline ?? pair.checkpoint), domSelector: newSelector ?? '' };
3828
+ });
3829
+ return true;
3830
+ }
3831
+
3832
+ const defaultFetchRawDiffsDeps = {
3833
+ fetchStepDiff,
3834
+ compareStep,
3835
+ readFile: defaultFsCacheDeps.readFile,
3836
+ writeFile: defaultFsCacheDeps.writeFile,
3837
+ };
3838
+ /**
3839
+ * The two-way visual diff for one step — `image1` in the baseline image's own coordinate
3840
+ * space, `image2` in the checkpoint's, exactly mirroring both the plain `GET .../diff`
3841
+ * endpoint's and `compareStep`'s own response shape. When the step's resolution state is
3842
+ * unchanged from the original test run (`appOutputResolution[stepIndex].isChanged` is not
3843
+ * `true`), the cheap `GET .../diff` endpoint is used as-is — nothing about the step's
3844
+ * effective match settings differs from what the test already ran with. Otherwise, the step's
3845
+ * current effective regions are folded into a fresh `compareStep` request so the returned diff
3846
+ * reflects any region added since the test ran — that (more expensive) result is cached on
3847
+ * disk, keyed by a hash of the full request body, so repeated calls against the same resolved
3848
+ * state don't repeatedly hit the endpoint.
3849
+ *
3850
+ * Takes an already-fetched `rawSession` rather than fetching its own — `batchId`/`sessionId`
3851
+ * are read straight off it (`rawSession.batchId`/`rawSession.id`), so a caller that already has
3852
+ * the raw session in hand (e.g. for its own domId lookups) never pays for a second fetch just
3853
+ * to hand this function a `url` it would otherwise re-resolve into the same session itself.
3854
+ *
3855
+ * `matchSettings` comes straight from `getEffectiveMatchSettings` — the raw session's own
3856
+ * scalars/regions, shaped directly into the request format, with no baseline/checkpoint
3857
+ * pairing and no healing: that shaping only exists for diagnostic region output (which needs
3858
+ * both sides shown, healing in whichever one the raw session doesn't encode), never for a
3859
+ * compare request. Re-deriving "accepted ⇒ checkpoint, else baseline" here would duplicate
3860
+ * logic the raw session's own `annotations` field already resolves — and healing in the other
3861
+ * side would cost an extra network round trip per region for nothing a compare request needs.
3862
+ */
3863
+ async function fetchRawDiffs(rawSession, stepIndex, baseUrl, accountId, keys, deps = defaultFetchRawDiffsDeps) {
3864
+ const batchId = rawSession?.batchId;
3865
+ const sessionId = rawSession?.id;
3866
+ if (rawSession?.appOutputResolution?.[stepIndex]?.isChanged !== true) {
3867
+ return deps.fetchStepDiff({ baseUrl, batchId, sessionId, stepIndex, accountId, keys });
3868
+ }
3869
+ const requestBody = {
3870
+ matchSettings: getEffectiveMatchSettings(rawSession, stepIndex),
3871
+ image1: imageForSide(rawSession, stepIndex, 'baseline'),
3872
+ image2: imageForSide(rawSession, stepIndex, 'checkpoint'),
3873
+ sessionId: rawSession.id,
3874
+ batchId: rawSession.batchId,
3875
+ runningSessionId: rawSession.runningSessionId,
3876
+ stepIndex,
3877
+ };
3878
+ // SHA-256 (not SHA-1): this is only a content-addressed cache key, but the hashed body carries
3879
+ // session identifiers, so a collision-prone digest is neither needed nor acceptable here.
3880
+ const requestHash = crypto__namespace.createHash('sha256').update(JSON.stringify(requestBody)).digest('hex').slice(0, 16);
3881
+ const cachePath = cacheFilePath(defaultFsCacheDeps, 'eyes-compare', requestHash);
3882
+ const cached = deps.readFile(cachePath);
3883
+ if (cached !== null) {
3884
+ const parsed = JSON.parse(cached);
3885
+ return { image1: parsed.image1 ?? [], image2: parsed.image2 ?? [] };
3886
+ }
3887
+ const result = await deps.compareStep(requestBody, { baseUrl, accountId, keys });
3888
+ const rects = { image1: result.image1 ?? [], image2: result.image2 ?? [] };
3889
+ deps.writeFile(cachePath, JSON.stringify(rects));
3890
+ return rects;
3891
+ }
3892
+
3893
+ function loadEnvFile(workingDirectory) {
3894
+ const envPath = path__namespace.join(workingDirectory, '.env');
3895
+ if (!fs__namespace.existsSync(envPath)) {
3896
+ return {};
3897
+ }
3898
+ try {
3899
+ const content = fs__namespace.readFileSync(envPath, 'utf-8');
3900
+ const lines = content.split('\n');
3901
+ let apiKey;
3902
+ let serverUrl;
3903
+ for (const line of lines) {
3904
+ const trimmed = line.trim();
3905
+ // Skip empty lines and comments
3906
+ if (!trimmed || trimmed.startsWith('#')) {
3907
+ continue;
3908
+ }
3909
+ // Parse KEY=VALUE
3910
+ const match = trimmed.match(/^([^=]+)=(.*)$/);
3911
+ if (!match)
3912
+ continue;
3913
+ const key = match[1].trim();
3914
+ let value = match[2].trim();
3915
+ // Remove quotes if present
3916
+ if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) {
3917
+ value = value.slice(1, -1);
3918
+ }
3919
+ if (key === 'APPLITOOLS_API_KEY' && value) {
3920
+ apiKey = value;
3921
+ }
3922
+ else if (key === 'APPLITOOLS_SERVER_URL' && value) {
3923
+ serverUrl = value;
3924
+ }
3925
+ }
3926
+ if (apiKey) {
3927
+ return { apiKey, serverUrl, foundIn: '.env', keyFrom: 'env_file' };
3928
+ }
3929
+ }
3930
+ catch {
3931
+ // Silently ignore errors reading .env
3932
+ }
3933
+ return {};
3934
+ }
3935
+ /**
3936
+ * Helper to resolve environment variable references in config files
3937
+ * Checks if the content references an env var, then resolves from process.env or .env file
3938
+ */
3939
+ function resolveEnvVarFromContent(content, envVarName, workingDirectory) {
3940
+ // Check if content references the environment variable (with or without process.env prefix)
3941
+ const patterns = [
3942
+ new RegExp(`process\\.env\\.${envVarName}`, 'i'),
3943
+ new RegExp(`${envVarName}(?!['"])`, 'i'), // Bare reference (not in quotes)
3944
+ ];
3945
+ const hasReference = patterns.some(pattern => pattern.test(content));
3946
+ if (!hasReference) {
3947
+ return undefined;
3948
+ }
3949
+ // Try to resolve the value: first from process.env, then from .env file
3950
+ const envValue = process.env[envVarName];
3951
+ if (envValue) {
3952
+ return envValue;
3953
+ }
3954
+ // Fallback to .env file
3955
+ const envResult = loadEnvFile(workingDirectory);
3956
+ if (envVarName === 'APPLITOOLS_API_KEY') {
3957
+ return envResult.apiKey;
3958
+ }
3959
+ else if (envVarName === 'APPLITOOLS_SERVER_URL') {
3960
+ return envResult.serverUrl;
3961
+ }
3962
+ return undefined;
3963
+ }
3964
+ function loadConfigFile(configPath, fileName, workingDirectory) {
3965
+ if (!fs__namespace.existsSync(configPath)) {
3966
+ return {};
3967
+ }
3968
+ try {
3969
+ const content = fs__namespace.readFileSync(configPath, 'utf-8');
3970
+ // Search for apiKey and serverUrl in the file content
3971
+ let apiKey;
3972
+ let serverUrl;
3973
+ let keyFrom = 'config';
3974
+ // Pattern 1: apiKey: 'value' or apiKey: "value" (hardcoded values)
3975
+ const apiKeyMatch = content.match(/apiKey\s*:\s*['"]([^'"]+)['"]/i);
3976
+ if (apiKeyMatch) {
3977
+ apiKey = apiKeyMatch[1];
3978
+ }
3979
+ // Pattern 2: serverUrl: 'value' or serverUrl: "value" (hardcoded values)
3980
+ const serverUrlMatch = content.match(/serverUrl\s*:\s*['"]([^'"]+)['"]/i);
3981
+ if (serverUrlMatch) {
3982
+ serverUrl = serverUrlMatch[1];
3983
+ }
3984
+ // Pattern 3: Resolve environment variable references in config file
3985
+ if (!apiKey) {
3986
+ apiKey = resolveEnvVarFromContent(content, 'APPLITOOLS_API_KEY', workingDirectory);
3987
+ // The same check resolveEnvVarFromContent makes before falling back to this directory's .env.
3988
+ keyFrom = process.env.APPLITOOLS_API_KEY ? 'environment' : 'env_file';
3989
+ }
3990
+ if (!serverUrl) {
3991
+ serverUrl = resolveEnvVarFromContent(content, 'APPLITOOLS_SERVER_URL', workingDirectory);
3992
+ }
3993
+ if (apiKey) {
3994
+ return { apiKey, serverUrl, foundIn: fileName, keyFrom };
3995
+ }
3996
+ }
3997
+ catch {
3998
+ // Silently ignore errors reading config file
3999
+ }
4000
+ return {};
4001
+ }
4002
+ function findApiKey(workingDirectory = process.cwd()) {
4003
+ // Define config file patterns to check (in priority order)
4004
+ const configFiles = [
4005
+ // Applitools config files
4006
+ { name: 'applitools.config.js', path: path__namespace.join(workingDirectory, 'applitools.config.js') },
4007
+ { name: 'applitools.config.cjs', path: path__namespace.join(workingDirectory, 'applitools.config.cjs') },
4008
+ { name: 'applitools.config.mjs', path: path__namespace.join(workingDirectory, 'applitools.config.mjs') },
4009
+ { name: 'applitools.config.ts', path: path__namespace.join(workingDirectory, 'applitools.config.ts') },
4010
+ // Playwright config files
4011
+ { name: 'playwright.config.js', path: path__namespace.join(workingDirectory, 'playwright.config.js') },
4012
+ { name: 'playwright.config.cjs', path: path__namespace.join(workingDirectory, 'playwright.config.cjs') },
4013
+ { name: 'playwright.config.mjs', path: path__namespace.join(workingDirectory, 'playwright.config.mjs') },
4014
+ { name: 'playwright.config.ts', path: path__namespace.join(workingDirectory, 'playwright.config.ts') },
4015
+ ];
4016
+ // 1. Check each config file in order (config files have priority over .env)
4017
+ for (const config of configFiles) {
4018
+ const result = loadConfigFile(config.path, config.name, workingDirectory);
4019
+ if (result.apiKey) {
4020
+ return result;
4021
+ }
4022
+ }
4023
+ // 2. Check .env file as fallback
4024
+ const envResult = loadEnvFile(workingDirectory);
4025
+ if (envResult.apiKey) {
4026
+ return envResult;
4027
+ }
4028
+ // 3. Check environment variables as final fallback
4029
+ const envApiKey = process.env.APPLITOOLS_API_KEY;
4030
+ const envServerUrl = process.env.APPLITOOLS_SERVER_URL;
4031
+ if (envApiKey) {
4032
+ return {
4033
+ apiKey: envApiKey,
4034
+ serverUrl: envServerUrl,
4035
+ foundIn: 'environment variable',
4036
+ keyFrom: 'environment',
4037
+ };
4038
+ }
4039
+ // Not found
4040
+ return {};
4041
+ }
4042
+
4043
+ // Saved the first time a .env overrides a workspace name, so the launch value comes back once no
4044
+ // chosen .env defines it. Kept here so credential loading can read it without importing env-loader.
4045
+ const workspaceLaunchValues = new Map();
4046
+ /** Whether a workspace name's current value is the chosen `.env`'s override, the launch value, or absent. */
4047
+ function workspaceValueSource(name) {
4048
+ if (!process.env[name])
4049
+ return 'unset';
4050
+ return workspaceLaunchValues.has(name) ? 'env_file' : 'process_env';
4051
+ }
4052
+ let currentClientInfo = undefined;
4053
+ let currentCredentials = undefined;
4054
+ let ide = undefined;
4055
+ function setClientInfo(clientInfo) {
4056
+ currentClientInfo = clientInfo;
4057
+ }
4058
+ function getClientInfo() {
4059
+ return currentClientInfo;
4060
+ }
4061
+ function setCredentials(credentials) {
4062
+ currentCredentials = credentials;
4063
+ }
4064
+ function getCredentials() {
4065
+ return currentCredentials;
4066
+ }
4067
+ function setIDE(ideName) {
4068
+ ide = ideName;
4069
+ }
4070
+ function getIDE() {
4071
+ return ide;
4072
+ }
4073
+ function parseIDE(env, argv) {
4074
+ var _a;
4075
+ return env['ide'] || ((_a = argv.find(arg => arg.startsWith('--ide='))) === null || _a === void 0 ? void 0 : _a.split('=')[1]) || 'unknown';
4076
+ }
4077
+ /** Evaluated once at process start; off unless `EXPERIMENTAL_ENV` is `1`/`true` (any case). */
4078
+ function parseExperimental(env) {
4079
+ var _a;
4080
+ return ['1', 'true'].includes(((_a = env[EXPERIMENTAL_ENV]) !== null && _a !== void 0 ? _a : '').toLowerCase());
4081
+ }
4082
+
4083
+ /** Load credentials from server context, config files, or environment variables */
4084
+ function loadCredentials(workingDirectory) {
4085
+ const storedCredentials = getCredentials();
4086
+ if ((storedCredentials === null || storedCredentials === void 0 ? void 0 : storedCredentials.apiKey) && (storedCredentials === null || storedCredentials === void 0 ? void 0 : storedCredentials.serverUrl)) {
4087
+ return {
4088
+ apiKey: storedCredentials.apiKey,
4089
+ serverUrl: storedCredentials.serverUrl,
4090
+ source: 'server-context',
4091
+ keySource: storedCredentials.keySource,
4092
+ };
4093
+ }
4094
+ const workingDir = workingDirectory || process.cwd();
4095
+ const configResult = findApiKey(workingDir);
4096
+ const apiKey = configResult.apiKey;
4097
+ const serverUrl = configResult.serverUrl || process.env.APPLITOOLS_SERVER_URL || DEFAULT_SERVER_URL;
4098
+ const source = configResult.foundIn;
4099
+ return { apiKey, serverUrl, source, keySource: apiKey ? keySourceOf(configResult) : undefined };
4100
+ }
4101
+ function keySourceOf({ keyFrom, foundIn }) {
4102
+ if (keyFrom === 'environment')
4103
+ return workspaceValueSource('APPLITOOLS_API_KEY');
4104
+ if (keyFrom === 'env_file')
4105
+ return 'env_file';
4106
+ return (foundIn === null || foundIn === void 0 ? void 0 : foundIn.startsWith('playwright.config')) ? 'playwright_config' : 'applitools_config';
4107
+ }
4108
+ /** Load and store credentials in server context */
4109
+ function loadAndStoreCredentials(workingDirectory) {
4110
+ const result = loadCredentials(workingDirectory);
4111
+ if (result.apiKey && result.serverUrl) {
4112
+ setCredentials({
4113
+ apiKey: result.apiKey,
4114
+ serverUrl: result.serverUrl,
4115
+ keySource: result.keySource,
4116
+ });
4117
+ return true;
4118
+ }
4119
+ return false;
4120
+ }
4121
+ /** Get credentials for external logging */
4122
+ function getCredentialsForLogging() {
4123
+ const result = loadCredentials();
4124
+ return {
4125
+ apiKey: result.apiKey,
4126
+ serverUrl: result.serverUrl || DEFAULT_SERVER_URL,
4127
+ };
4014
4128
  }
4015
4129
 
4016
- // findNodeBySelector/findNodeByRect return a nested {domSelector, rect} shape (DomNode);
4017
- // the Region shape needed elsewhere is flat (domSelector alongside left/top/width/height).
4018
- function toRegion$1(resolved) {
4019
- return { domSelector: resolved.domSelector, ...resolved.rect };
4130
+ const handler = (() => {
4131
+ if (process.env.APPLITOOLS_LOG_FILE) {
4132
+ return logger$1.makeFileHandler({ filename: process.env.APPLITOOLS_LOG_FILE });
4133
+ }
4134
+ else if (process.env.APPLITOOLS_LOG_DIR) {
4135
+ return logger$1.makeRollingFileHandler({ dirname: process.env.APPLITOOLS_LOG_DIR });
4136
+ }
4137
+ // Default to stderr to avoid interfering with MCP stdio protocol
4138
+ return {
4139
+ // eslint-disable-next-line no-console
4140
+ log: (message) => console.error(message),
4141
+ // eslint-disable-next-line no-console
4142
+ warn: (message) => console.warn(message),
4143
+ // eslint-disable-next-line no-console
4144
+ error: (message) => console.error(message),
4145
+ };
4146
+ })();
4147
+ // Only perform expensive serialisation when a log sink is explicitly configured.
4148
+ const isVerboseLogging = !!(process.env.APPLITOOLS_LOG_FILE ||
4149
+ process.env.APPLITOOLS_LOG_DIR ||
4150
+ process.env.APPLITOOLS_SHOW_LOGS);
4151
+ const logger = logger$1.makeLogger({ level: 'all', handler });
4152
+ const externalLogger = coreBase.makeCore({
4153
+ agentId: 'mcp-tool-handler',
4154
+ maskLog: false,
4155
+ logger,
4156
+ offlineLocationPath: undefined,
4157
+ });
4158
+ function log$1(level, ...args) {
4159
+ logger[level](level, ...args);
4020
4160
  }
4021
- /**
4022
- * Maps every `anchored` pair's `domSelector` to the other side via one batched
4023
- * get-compatible-selectors call, resolving each mapped selector's accurate rect locally
4024
- * against that side's DOM (the API only returns the mapped selector, never a rect). Falls
4025
- * back to treating every selector as unmapped if the batch call itself fails for some reason
4026
- * other than a bad input selector (`sessions`'s own `checkRegions` already filters those out).
4027
- * Mutates each pair's missing side in place. Returns whether anything was attempted (i.e.
4028
- * `anchored` was non-empty and both sides have an image to map between).
4029
- *
4030
- * Lives here, not in `atoms/sessions` (where the rest of the region-healing pipeline this composes
4031
- * into — `checkRegions`/`clearStaleSelectors`/`healNonAnchoredRegionsBySourceRect` — lives):
4032
- * this is the one step of that pipeline that actually calls the network (`getCompatibleSelectors`),
4033
- * and `atoms` must never depend on `api`/`common` (so it can't reference `ApiKeyProvider` or make
4034
- * network calls) — the orchestration belongs in `common`, which depends on both instead.
4035
- */
4036
- async function mapAnchoredRegionsBySelector(rawSession, stepIndex, anchored, deps) {
4037
- if (anchored.length === 0)
4038
- return false;
4039
- const sourceSide = resolveDomIdSide('unchanged', rawSession, stepIndex);
4040
- const missingSide = sourceSide === 'baseline' ? 'checkpoint' : 'baseline';
4041
- const imageSource = imageForSide(rawSession, stepIndex, sourceSide);
4042
- const imageMissing = imageForSide(rawSession, stepIndex, missingSide);
4043
- if (!imageSource || !imageMissing)
4044
- return false;
4045
- const domMissing = await deps.fetchDomForSide(rawSession, stepIndex, missingSide, deps.baseUrl).catch(() => null);
4046
- // `anchored` pairs are guaranteed a truthy domSelector by checkRegions's own definition of "anchored".
4047
- const selectors = anchored.map(p => (p.baseline ?? p.checkpoint).domSelector);
4048
- let mapped;
4161
+ async function externalLog(eventName, data, level = 'Notice') {
4162
+ // Get credentials using centralized loader
4163
+ const { apiKey, serverUrl: eyesServerUrl } = getCredentialsForLogging();
4164
+ if (!apiKey || apiKey === '') {
4165
+ logger.warn(`Cannot log external event ${eventName} - no API key configured`);
4166
+ return;
4167
+ }
4168
+ if (!isTrustedEyesUrl(eyesServerUrl)) {
4169
+ logger.warn(`Cannot log external event ${eventName} - the configured server is not an Applitools host`);
4170
+ return;
4171
+ }
4049
4172
  try {
4050
- mapped = await deps.getCompatibleSelectors({ baseUrl: deps.baseUrl, accountId: deps.accountId, keys: deps.keys }, imageSource, imageMissing, selectors);
4173
+ await externalLogger.logEvent({
4174
+ settings: {
4175
+ apiKey,
4176
+ eyesServerUrl,
4177
+ level,
4178
+ event: {
4179
+ type: eventName,
4180
+ data: data || {},
4181
+ },
4182
+ },
4183
+ logger,
4184
+ });
4051
4185
  }
4052
- catch {
4053
- mapped = selectors.map(() => null); // the batch itself failed — treat every one as unmapped rather than throwing
4186
+ catch (error) {
4187
+ logger.error(`Failed to log external event ${eventName}:`, error);
4054
4188
  }
4055
- anchored.forEach((pair, i) => {
4056
- const newSelector = mapped[i];
4057
- const resolved = newSelector && domMissing ? findNodeBySelector(domMissing, newSelector) : null;
4058
- pair[missingSide] = resolved
4059
- ? toRegion$1(resolved)
4060
- : { ...(pair.baseline ?? pair.checkpoint), domSelector: newSelector ?? '' };
4061
- });
4062
- return true;
4063
4189
  }
4064
4190
 
4065
- const defaultFetchRawDiffsDeps = {
4066
- fetchStepDiff,
4067
- compareStep,
4068
- readFile: defaultFsCacheDeps.readFile,
4069
- writeFile: defaultFsCacheDeps.writeFile,
4070
- };
4071
4191
  /**
4072
- * The two-way visual diff for one step — `image1` in the baseline image's own coordinate
4073
- * space, `image2` in the checkpoint's, exactly mirroring both the plain `GET .../diff`
4074
- * endpoint's and `compareStep`'s own response shape. When the step's resolution state is
4075
- * unchanged from the original test run (`appOutputResolution[stepIndex].isChanged` is not
4076
- * `true`), the cheap `GET .../diff` endpoint is used as-is — nothing about the step's
4077
- * effective match settings differs from what the test already ran with. Otherwise, the step's
4078
- * current effective regions are folded into a fresh `compareStep` request so the returned diff
4079
- * reflects any region added since the test ran — that (more expensive) result is cached on
4080
- * disk, keyed by a hash of the full request body, so repeated calls against the same resolved
4081
- * state don't repeatedly hit the endpoint.
4082
- *
4083
- * Takes an already-fetched `rawSession` rather than fetching its own — `batchId`/`sessionId`
4084
- * are read straight off it (`rawSession.batchId`/`rawSession.id`), so a caller that already has
4085
- * the raw session in hand (e.g. for its own domId lookups) never pays for a second fetch just
4086
- * to hand this function a `url` it would otherwise re-resolve into the same session itself.
4192
+ * Documentation Resource
4087
4193
  *
4088
- * `matchSettings` comes straight from `getEffectiveMatchSettings` — the raw session's own
4089
- * scalars/regions, shaped directly into the request format, with no baseline/checkpoint
4090
- * pairing and no healing: that shaping only exists for diagnostic region output (which needs
4091
- * both sides shown, healing in whichever one the raw session doesn't encode), never for a
4092
- * compare request. Re-deriving "accepted ⇒ checkpoint, else baseline" here would duplicate
4093
- * logic the raw session's own `annotations` field already resolves — and healing in the other
4094
- * side would cost an extra network round trip per region for nothing a compare request needs.
4194
+ * Exposes the comprehensive README documentation for the Applitools MCP server
4095
4195
  */
4096
- async function fetchRawDiffs(rawSession, stepIndex, baseUrl, accountId, keys, deps = defaultFetchRawDiffsDeps) {
4097
- const batchId = rawSession?.batchId;
4098
- const sessionId = rawSession?.id;
4099
- if (rawSession?.appOutputResolution?.[stepIndex]?.isChanged !== true) {
4100
- return deps.fetchStepDiff({ baseUrl, batchId, sessionId, stepIndex, accountId, keys });
4196
+ /**
4197
+ * Read documentation resource content
4198
+ */
4199
+ async function readDocumentationResource(uri) {
4200
+ // Validate URI first (don't log validation errors)
4201
+ if (uri !== RESOURCE_URIS.DOCUMENTATION_README) {
4202
+ throw new Error(`Unknown resource URI: ${uri}`);
4101
4203
  }
4102
- const requestBody = {
4103
- matchSettings: getEffectiveMatchSettings(rawSession, stepIndex),
4104
- image1: imageForSide(rawSession, stepIndex, 'baseline'),
4105
- image2: imageForSide(rawSession, stepIndex, 'checkpoint'),
4106
- sessionId: rawSession.id,
4107
- batchId: rawSession.batchId,
4108
- runningSessionId: rawSession.runningSessionId,
4109
- stepIndex,
4110
- };
4111
- // SHA-256 (not SHA-1): this is only a content-addressed cache key, but the hashed body carries
4112
- // session identifiers, so a collision-prone digest is neither needed nor acceptable here.
4113
- const requestHash = crypto__namespace.createHash('sha256').update(JSON.stringify(requestBody)).digest('hex').slice(0, 16);
4114
- const cachePath = cacheFilePath(defaultFsCacheDeps, 'eyes-compare', requestHash);
4115
- const cached = deps.readFile(cachePath);
4116
- if (cached !== null) {
4117
- const parsed = JSON.parse(cached);
4118
- return { image1: parsed.image1 ?? [], image2: parsed.image2 ?? [] };
4204
+ try {
4205
+ // Determine the correct path based on whether we're running from source or dist
4206
+ // In production: dist/resources/documentation/index.js -> dist/docs/README.md
4207
+ // In tests: src/resources/documentation/index.ts -> docs/README.md
4208
+ let docsPath;
4209
+ if (/[\\/]dist(?:[\\/]|$)/.test(__dirname)) {
4210
+ // Running from compiled dist (standalone or VS Code extension)
4211
+ // Expect docs folder to be sibling of the script
4212
+ docsPath = path.join(__dirname, 'docs/README.md');
4213
+ }
4214
+ else {
4215
+ // Running from source (tests)
4216
+ docsPath = path.join(__dirname, '../../../docs/README.md');
4217
+ }
4218
+ const content = await promises.readFile(docsPath, 'utf-8');
4219
+ return {
4220
+ contents: [
4221
+ {
4222
+ uri,
4223
+ text: content,
4224
+ mimeType: 'text/markdown',
4225
+ },
4226
+ ],
4227
+ };
4228
+ }
4229
+ catch (error) {
4230
+ // Only log unexpected errors (file system errors, not validation errors)
4231
+ log$1('error', '[Resources] Failed to read documentation:', error);
4232
+ throw new Error(`Failed to read documentation: ${error instanceof Error ? error.message : String(error)}`);
4119
4233
  }
4120
- const result = await deps.compareStep(requestBody, { baseUrl, accountId, keys });
4121
- const rects = { image1: result.image1 ?? [], image2: result.image2 ?? [] };
4122
- deps.writeFile(cachePath, JSON.stringify(rects));
4123
- return rects;
4124
4234
  }
4125
4235
 
4126
4236
  const sessionMetadata = {
@@ -4144,33 +4254,36 @@ function getLastValidatedServerUrl() {
4144
4254
  return sessionMetadata.lastValidatedServerUrl;
4145
4255
  }
4146
4256
 
4147
- const API_KEY_VARS = ['APPLITOOLS_READ_KEY', 'APPLITOOLS_WRITE_KEY'];
4148
4257
  const loadEnvOnce = utils__namespace.general.cachify((startDir, source) => {
4149
4258
  const loaded = loadEnvFromCwd(startDir);
4150
4259
  if (loaded) {
4151
- const applied = loaded.applied.length ? `set ${loaded.applied.join(', ')}` : 'no new variables applied';
4152
- log$2('info', `[MCP Server] .env loaded from ${loaded.path} (${applied}; walked up from ${startDir}, triggered by ${source})`);
4260
+ log$1('info', `[MCP Server] .env loaded from ${loaded.path} (defines ${Object.keys(loaded.parsed).join(', ')}; walked up from ${startDir}, triggered by ${source})`);
4153
4261
  }
4154
4262
  else {
4155
- log$2('debug', `[MCP Server] no .env found walking up from ${startDir} (triggered by ${source})`);
4263
+ log$1('debug', `[MCP Server] no .env found walking up from ${startDir} (triggered by ${source})`);
4156
4264
  }
4157
4265
  return loaded;
4158
4266
  }, ([startDir]) => startDir, 30000);
4159
4267
  function syncWorkspaceKeys(workspaceRoot, source) {
4160
4268
  const loaded = loadEnvOnce(workspaceRoot, source);
4161
- if (!loaded)
4162
- return;
4163
- for (const name of API_KEY_VARS) {
4164
- const value = loaded.parsed[name];
4165
- if (process.env[name] === value)
4166
- continue;
4167
- if (value) {
4269
+ for (const name of WORKSPACE_ENV_NAMES) {
4270
+ const value = loaded === null || loaded === void 0 ? void 0 : loaded.parsed[name];
4271
+ if (loaded && value) {
4272
+ if (!workspaceLaunchValues.has(name))
4273
+ workspaceLaunchValues.set(name, process.env[name]);
4274
+ if (process.env[name] === value)
4275
+ continue;
4168
4276
  process.env[name] = value;
4169
- log$2('info', `[MCP Server] ${name} set from ${loaded.path} (triggered by ${source})`);
4277
+ log$1('info', `[MCP Server] ${name} set from ${loaded.path} (triggered by ${source})`);
4170
4278
  }
4171
- else if (name in process.env) {
4172
- delete process.env[name];
4173
- log$2('info', `[MCP Server] ${name} removed — not in ${loaded.path} (triggered by ${source})`);
4279
+ else if (workspaceLaunchValues.has(name)) {
4280
+ const launchValue = workspaceLaunchValues.get(name);
4281
+ workspaceLaunchValues.delete(name);
4282
+ if (launchValue === undefined)
4283
+ delete process.env[name];
4284
+ else
4285
+ process.env[name] = launchValue;
4286
+ log$1('info', `[MCP Server] ${name} restored to its launch value (triggered by ${source})`);
4174
4287
  }
4175
4288
  }
4176
4289
  }
@@ -4496,11 +4609,20 @@ function countGateRejection() {
4496
4609
  function gateRejectionCount() {
4497
4610
  return gateRejections;
4498
4611
  }
4612
+ /** Where each key setting in use came from, as fixed enum values only — never a path, file name or key. */
4613
+ function keySources() {
4614
+ var _a;
4615
+ return {
4616
+ api_key_source: (_a = loadCredentials().keySource) !== null && _a !== void 0 ? _a : 'unset',
4617
+ read_key_source: workspaceValueSource('APPLITOOLS_READ_KEY'),
4618
+ write_key_source: workspaceValueSource('APPLITOOLS_WRITE_KEY'),
4619
+ };
4620
+ }
4499
4621
 
4500
4622
  var name = "@applitools/mcp";
4501
4623
  var mcpName = "io.github.applitools/applitools";
4502
- var mcpRegistryVersion = "1.0.16";
4503
- var version = "0.10.4";
4624
+ var mcpRegistryVersion = "1.0.18";
4625
+ var version = "0.10.6";
4504
4626
  var description = "Applitools MCP server for AI coding assistants";
4505
4627
  var main = "./dist/index.js";
4506
4628
  var bin = "./dist/index.js";
@@ -4732,7 +4854,7 @@ function jsonParams(essential, inputs) {
4732
4854
  if (biggest === undefined)
4733
4855
  return json;
4734
4856
  fields.delete(biggest);
4735
- log$2('warn', `[MCP] json_params over ${JSON_PARAMS_BUDGET} chars — dropped input "${biggest}"`);
4857
+ log$1('warn', `[MCP] json_params over ${JSON_PARAMS_BUDGET} chars — dropped input "${biggest}"`);
4736
4858
  json = serialize();
4737
4859
  }
4738
4860
  return json;
@@ -4740,13 +4862,17 @@ function jsonParams(essential, inputs) {
4740
4862
  const createToolHandler = (toolDef, logic) => {
4741
4863
  return async (params) => {
4742
4864
  const clientInfo = getClientInfo();
4743
- log$2('info', `[MCP] 🟢 Tool Accessed: ${toolDef.name}`);
4744
- log$2('info', `[MCP] 📥 Client: ${(clientInfo === null || clientInfo === void 0 ? void 0 : clientInfo.name) || 'unknown'} v${(clientInfo === null || clientInfo === void 0 ? void 0 : clientInfo.version) || 'unknown'}`);
4865
+ log$1('info', `[MCP] 🟢 Tool Accessed: ${toolDef.name}`);
4866
+ log$1('info', `[MCP] 📥 Client: ${(clientInfo === null || clientInfo === void 0 ? void 0 : clientInfo.name) || 'unknown'} v${(clientInfo === null || clientInfo === void 0 ? void 0 : clientInfo.version) || 'unknown'}`);
4867
+ if (typeof (params === null || params === void 0 ? void 0 : params.apiKey) === 'string')
4868
+ logger.mask(params.apiKey);
4745
4869
  if (isVerboseLogging)
4746
- log$2('info', `[MCP] 📥 Params:`, JSON.stringify(params, null, 2));
4870
+ log$1('info', `[MCP] 📥 Params:`, JSON.stringify(params, null, 2));
4747
4871
  const safeParams = params !== null && params !== void 0 ? params : {};
4748
4872
  const workspaceRoot = safeParams.workspaceRoot || getWorkspaceRoot() || process.cwd();
4749
4873
  syncWorkspaceKeys(workspaceRoot, toolDef.name);
4874
+ // Read before any await, while the process-wide key slot still holds this call's keys.
4875
+ const sources = keySources();
4750
4876
  const { selected: frameworkSelected, detected: detectedFrameworks } = getAutomationFramework(workspaceRoot, safeParams.activeFile);
4751
4877
  const { name: automationFramework, version: automationFrameworkVersion } = frameworkSelected;
4752
4878
  const { selected: sdkLanguage, detected: detectedLanguages } = getSdkLanguage(workspaceRoot);
@@ -4758,7 +4884,7 @@ const createToolHandler = (toolDef, logic) => {
4758
4884
  sdkLanguage,
4759
4885
  };
4760
4886
  const { batchId, sessionId } = extractScopeIds(safeParams);
4761
- const telemetry = {};
4887
+ const telemetry = { ...sources };
4762
4888
  const callInputs = reportedInputs(safeParams);
4763
4889
  const outcomeJsonParams = () => jsonParams({ ...telemetry, gate_rejections: gateRejectionCount() }, callInputs);
4764
4890
  externalLog('mcp_tool_invoked', {
@@ -4770,8 +4896,9 @@ const createToolHandler = (toolDef, logic) => {
4770
4896
  transport_mode: TRANSPORT_MODE,
4771
4897
  batch_id: batchId,
4772
4898
  session_id: sessionId,
4773
- params: JSON.stringify(params, null, 2).slice(0, 1024),
4774
- json_params: jsonParams({}, callInputs),
4899
+ // The backend attributes every event to the authenticating key's account, so no key goes out here.
4900
+ params: JSON.stringify({ ...params, apiKey: undefined }, null, 2).slice(0, 1024),
4901
+ json_params: jsonParams(sources, callInputs),
4775
4902
  automation_framework: automationFramework,
4776
4903
  automation_framework_version: automationFrameworkVersion,
4777
4904
  sdk_language: sdkLanguage,
@@ -4782,7 +4909,7 @@ const createToolHandler = (toolDef, logic) => {
4782
4909
  const validatedParams = toolDef.input.parse(enrichedParams || {});
4783
4910
  const result = await withToolTelemetry(telemetry, () => logic(validatedParams));
4784
4911
  if (isVerboseLogging)
4785
- log$2('info', `[MCP] 📤 Result:`, serializeResultForLog(result));
4912
+ log$1('info', `[MCP] 📤 Result:`, serializeResultForLog(result));
4786
4913
  const structuredContentWithoutMessage = { ...result.structuredContent };
4787
4914
  if (structuredContentWithoutMessage && 'message' in structuredContentWithoutMessage) {
4788
4915
  delete structuredContentWithoutMessage.message;
@@ -4893,6 +5020,12 @@ const DEFAULT_RETRY_CONFIG = [
4893
5020
  timeout: [2000, 4000, 8000, 16000, 32000],
4894
5021
  },
4895
5022
  ];
5023
+ // node-fetch forwards the key header across a cross-origin redirect, and req's HTTP/2 path
5024
+ // rebuilds the request without its `redirect` mode.
5025
+ const NO_REDIRECTS = {
5026
+ hooks: { beforeRequest: ({ request }) => ({ request, redirect: 'error' }) },
5027
+ httpVersion: 1,
5028
+ };
4896
5029
  /**
4897
5030
  * API Client for Eyes server using @applitools/req for automatic retry handling
4898
5031
  */
@@ -4927,6 +5060,7 @@ class ApiClient {
4927
5060
  },
4928
5061
  requestTimeout: this.timeout,
4929
5062
  retry: this.retryConfig,
5063
+ ...NO_REDIRECTS,
4930
5064
  });
4931
5065
  if (response.status === 401) {
4932
5066
  throw new InvalidApiKeyError(this.apiKey);
@@ -4949,9 +5083,10 @@ class ApiClient {
4949
5083
  },
4950
5084
  requestTimeout: this.timeout,
4951
5085
  retry: this.retryConfig,
5086
+ ...NO_REDIRECTS,
4952
5087
  });
4953
- // Handle authentication errors
4954
- if (response.status === 401) {
5088
+ // Handle authentication errors; a 403 refuses the key too, which account-id-resolver remembers
5089
+ if (response.status === 401 || response.status === 403) {
4955
5090
  throw new InvalidApiKeyError(this.apiKey);
4956
5091
  }
4957
5092
  if (!response.ok) {
@@ -4978,16 +5113,16 @@ class ApiClient {
4978
5113
  const reqOptions = {
4979
5114
  method: 'POST',
4980
5115
  headers: {
5116
+ 'X-Eyes-Api-Key': this.apiKey,
4981
5117
  'Content-Type': 'application/json',
4982
5118
  Accept: 'application/json',
4983
5119
  },
4984
5120
  body,
4985
5121
  requestTimeout: this.timeout,
4986
5122
  retry: this.retryConfig,
5123
+ ...NO_REDIRECTS,
4987
5124
  };
4988
- // Add API key to query for POST requests (Eyes API pattern)
4989
- const url = `${this.baseUrl}/${endpoint}${endpoint.includes('?') ? '&' : '?'}apiKey=${this.apiKey}`;
4990
- const response = await req.req(url, reqOptions);
5125
+ const response = await req.req(`${this.baseUrl}/${endpoint}`, reqOptions);
4991
5126
  // Handle authentication errors
4992
5127
  if (response.status === 401) {
4993
5128
  throw new InvalidApiKeyError(this.apiKey);
@@ -5050,14 +5185,15 @@ const VERIFY_RETRY_CONFIG = [
5050
5185
  */
5051
5186
  async function verifyApiKeyWithServer(params) {
5052
5187
  const { apiKey, serverUrl } = params;
5188
+ assertTrustedEyesUrl(serverUrl);
5053
5189
  const client = new ApiClient({
5054
5190
  baseUrl: serverUrl,
5055
5191
  apiKey: apiKey,
5056
5192
  timeout: 2000,
5057
5193
  retryConfig: VERIFY_RETRY_CONFIG,
5058
5194
  });
5059
- const response = await client.get(`api/auth/access?accessKey=${apiKey}`);
5060
- log$2('debug', `API key verification response: ${JSON.stringify(response)}`);
5195
+ const response = await client.get('api/auth/access');
5196
+ log$1('debug', `API key verification response: ${JSON.stringify(response)}`);
5061
5197
  if (response.accountId === '') {
5062
5198
  throw new Error('Invalid API key');
5063
5199
  }
@@ -5083,22 +5219,32 @@ const VerifyApiKeyInputSchema = zod.z.object({
5083
5219
  .optional()
5084
5220
  .describe('If true, save the validated API key and server URL as the default configuration in cache'),
5085
5221
  });
5222
+ // A key that fails validation is the one telemetry case where a key is reported, masked so that
5223
+ // a short value is never shown; its source replaces the pinned key's so both fields describe it.
5224
+ function reportUnvalidatedKey(apiKey, keySource) {
5225
+ recordToolTelemetry({
5226
+ api_key_source: keySource,
5227
+ api_key_masked: apiKey.length <= 7 ? '***' : `${apiKey.slice(0, 3)}***${apiKey.slice(-3)}`,
5228
+ });
5229
+ }
5086
5230
  /** Verify API key handler function */
5087
5231
  async function verifyApiKey(input = {}) {
5088
5232
  // Determine working directory
5089
5233
  const workingDirectory = input.workingDirectory || input.workspaceRoot || process.cwd();
5090
- log$2('debug', `Verifying Eyes API key in working directory: ${workingDirectory}`);
5091
- log$2('debug', `Input parameters: ${JSON.stringify(input)}`);
5234
+ log$1('debug', `Verifying Eyes API key in working directory: ${workingDirectory}`);
5235
+ log$1('debug', `Input parameters: ${JSON.stringify(input)}`);
5092
5236
  // Get API key - priority: input parameter > credential loader (server-context > config files > env vars)
5093
5237
  let apiKey = input.apiKey;
5094
5238
  let serverUrl = input.serverUrl;
5095
5239
  let foundIn;
5240
+ let keySource = input.apiKey ? 'tool_argument' : undefined;
5096
5241
  // Load credentials if not provided as input
5097
5242
  if (!apiKey || !serverUrl) {
5098
5243
  const credentialResult = loadCredentials(workingDirectory);
5099
5244
  apiKey = apiKey || credentialResult.apiKey;
5100
5245
  serverUrl = serverUrl || credentialResult.serverUrl; // loadCredentials always provides serverUrl (with default)
5101
5246
  foundIn = credentialResult.source;
5247
+ keySource !== null && keySource !== void 0 ? keySource : (keySource = credentialResult.keySource);
5102
5248
  }
5103
5249
  // Validate API key presence
5104
5250
  if (!apiKey || apiKey.trim() === '') {
@@ -5113,17 +5259,30 @@ async function verifyApiKey(input = {}) {
5113
5259
  new URL(finalServerUrl);
5114
5260
  }
5115
5261
  catch {
5262
+ reportUnvalidatedKey(apiKey, keySource);
5116
5263
  return {
5117
5264
  message: wrapText('Eyes authentication failed. Invalid server URL format. Please verify that your server URL is correct.', 'suffix'),
5118
5265
  };
5119
5266
  }
5267
+ try {
5268
+ assertTrustedEyesUrl(finalServerUrl);
5269
+ }
5270
+ catch (error) {
5271
+ reportUnvalidatedKey(apiKey, keySource);
5272
+ return {
5273
+ message: wrapText(`Eyes authentication failed: ${error.message}. ` +
5274
+ 'Correct the server URL where it is set: the serverUrl argument, APPLITOOLS_SERVER_URL or the project config file.', 'suffix'),
5275
+ };
5276
+ }
5120
5277
  // Call Eyes API to verify the key
5121
5278
  try {
5122
5279
  await verifyApiKeyWithServer({ apiKey, serverUrl: finalServerUrl });
5123
5280
  // Mark as validated in session memory
5124
5281
  markApiKeyAsValidated(apiKey, finalServerUrl);
5125
5282
  // Store credentials in server context for external logging
5126
- setCredentials({ apiKey, serverUrl: finalServerUrl });
5283
+ setCredentials({ apiKey, serverUrl: finalServerUrl, keySource });
5284
+ // This call's events were seeded before the key was pinned; report the pinned key's source instead.
5285
+ recordToolTelemetry({ api_key_source: keySource });
5127
5286
  const successMessage = foundIn
5128
5287
  ? `Eyes authentication successful! API key found in ${foundIn}`
5129
5288
  : 'Eyes authentication successful!';
@@ -5133,6 +5292,7 @@ async function verifyApiKey(input = {}) {
5133
5292
  }
5134
5293
  catch {
5135
5294
  // Return invalid for any error (401, network, etc.)
5295
+ reportUnvalidatedKey(apiKey, keySource);
5136
5296
  return {
5137
5297
  message: wrapText('Eyes authentication failed. Please verify that your API Key or server URL is correct. Visit our documentation to learn how to retrieve these values: https://applitools.com/docs/eyes/playwright#set-your-applitools-api-key', 'suffix'),
5138
5298
  };
@@ -5272,7 +5432,8 @@ const PlaywrightJsSetupProjectClientInputSchema = createClientInputSchema(Playwr
5272
5432
  async function eyesSetupProject(input = {}) {
5273
5433
  const { workspaceRoot, warning } = validateCommonInput(input);
5274
5434
  let apiKey = getLastValidatedApiKey() || findApiKey(workspaceRoot).apiKey;
5275
- let eyesServerUrl = getLastValidatedServerUrl() || findApiKey(workspaceRoot).serverUrl;
5435
+ const foundServerUrl = getLastValidatedServerUrl() || findApiKey(workspaceRoot).serverUrl;
5436
+ let eyesServerUrl = foundServerUrl && isTrustedEyesUrl(foundServerUrl) ? foundServerUrl : undefined;
5276
5437
  const requiredApiKeyMessage = !apiKey
5277
5438
  ? 'IMPORTANT: An Applitools API key is required to run visual tests. Please provide your API key using the --apiKey argument when running npx eyes-setup, or set it in your environment variables or Playwright config file.'
5278
5439
  : '';
@@ -5858,20 +6019,30 @@ function instrumentedRegistrar(server) {
5858
6019
  const defaultResolverDeps = {
5859
6020
  verify: verifyApiKeyWithServer,
5860
6021
  };
5861
- // No expiry: an accountId is a fixed property of the account behind the key, so a resolved entry
5862
- // can never go stale. Holds the in-flight promise so a burst of URL builds shares one verification.
6022
+ // A resolved entry never expires: an accountId is a fixed property of the account behind the key.
6023
+ // Holds the in-flight promise so a burst of URL builds shares one verification.
5863
6024
  const accountIds = new Map();
6025
+ // A refusal can be temporary (a proxy's 403, permissions granted later), so it is retried after this long.
6026
+ const REFUSAL_TTL_MS = 5 * 60 * 1000;
6027
+ const refusalExpiry = new Map();
5864
6028
  function realAccountId(apiKey, serverUrl, deps) {
6029
+ var _a, _b;
5865
6030
  // serverUrl joins the key because one API key against two servers is two accounts.
5866
6031
  const key = `${serverUrl}::${apiKey}`;
6032
+ const now = (_a = deps.now) !== null && _a !== void 0 ? _a : (() => performance.now());
5867
6033
  const known = accountIds.get(key);
5868
- if (known)
6034
+ if (known && ((_b = refusalExpiry.get(key)) !== null && _b !== void 0 ? _b : Infinity) > now())
5869
6035
  return known;
5870
6036
  const promise = deps.verify({ apiKey, serverUrl }).then(result => result.accountId);
5871
6037
  accountIds.set(key, promise);
5872
- // Failures are not remembered — a transient error must not poison the id for the whole process.
5873
- promise.catch(() => {
5874
- if (accountIds.get(key) === promise)
6038
+ refusalExpiry.delete(key);
6039
+ // A refused key is not sent again until the refusal expires; any other failure is retried next call.
6040
+ promise.catch(error => {
6041
+ if (accountIds.get(key) !== promise)
6042
+ return;
6043
+ if (error instanceof InvalidApiKeyError)
6044
+ refusalExpiry.set(key, now() + REFUSAL_TTL_MS);
6045
+ else
5875
6046
  accountIds.delete(key);
5876
6047
  });
5877
6048
  return promise;
@@ -5884,6 +6055,10 @@ function realAccountId(apiKey, serverUrl, deps) {
5884
6055
  * failure also returns the input unchanged.
5885
6056
  */
5886
6057
  async function getFullAccountId(accountId, apiKey, serverUrl = DEFAULT_SERVER_URL, deps = defaultResolverDeps) {
6058
+ // Padded base64 always has a length divisible by 4 and stripped padding never leaves one, so an id
6059
+ // of such a length is already complete and a lookup could not change it.
6060
+ if (accountId && accountId.length % 4 === 0)
6061
+ return accountId;
5887
6062
  try {
5888
6063
  const real = await realAccountId(apiKey, serverUrl, deps);
5889
6064
  if (accountId === undefined)
@@ -6743,6 +6918,7 @@ function textResult(text) {
6743
6918
  * variable name and the wording of the note that follows.
6744
6919
  */
6745
6920
  function resolveApiKey(spec, urlForAccountHint) {
6921
+ assertTrustedEyesUrl(urlForAccountHint);
6746
6922
  const apiKey = process.env[spec.envVar];
6747
6923
  if (apiKey)
6748
6924
  return apiKey;
@@ -7921,7 +8097,7 @@ function registerEyesResolveTools(server, deps = defaultCommandsDeps) {
7921
8097
  * consolidates into that investigation's own single debug log rather than scattering per level.
7922
8098
  */
7923
8099
  function log(scopeId, label, fields = {}, deps) {
7924
- log$1(rootScopeId(scopeId), label, fields, deps);
8100
+ log$2(rootScopeId(scopeId), label, fields, deps);
7925
8101
  }
7926
8102
  /** The exact path `log` above appends `scopeId`'s investigation's entries to — see `log`'s own doc comment for the root-normalization it applies first. */
7927
8103
  function debugLogPath(scopeId, deps) {
@@ -11410,7 +11586,7 @@ function registeredToolNames(experimental) {
11410
11586
  }
11411
11587
 
11412
11588
  async function startServer() {
11413
- loadEnvOnce(process.cwd(), 'server startup');
11589
+ syncWorkspaceKeys(process.cwd(), 'server startup');
11414
11590
  const experimental = parseExperimental(process.env);
11415
11591
  const server = new mcp_js.McpServer({
11416
11592
  name: 'applitools-mcp',
@@ -11447,7 +11623,7 @@ async function startServer() {
11447
11623
  const clientInfo = server.server.getClientVersion();
11448
11624
  setClientInfo(clientInfo);
11449
11625
  setIDE(parseIDE(process.env, process.argv));
11450
- log$2('info', '[MCP Server] Client connected:', {
11626
+ log$1('info', '[MCP Server] Client connected:', {
11451
11627
  name: (clientInfo === null || clientInfo === void 0 ? void 0 : clientInfo.name) || 'unknown',
11452
11628
  version: (clientInfo === null || clientInfo === void 0 ? void 0 : clientInfo.version) || 'unknown',
11453
11629
  description: clientInfo === null || clientInfo === void 0 ? void 0 : clientInfo.description,
@@ -11468,9 +11644,9 @@ async function startServer() {
11468
11644
  .then(({ roots }) => {
11469
11645
  const root = roots.find(r => r.uri.startsWith('file://'));
11470
11646
  if (root)
11471
- loadEnvOnce(node_url.fileURLToPath(root.uri), 'client roots');
11647
+ syncWorkspaceKeys(node_url.fileURLToPath(root.uri), 'client roots');
11472
11648
  })
11473
- .catch(error => log$2('debug', '[MCP Server] roots/list failed:', error));
11649
+ .catch(error => log$1('debug', '[MCP Server] roots/list failed:', error));
11474
11650
  }
11475
11651
  };
11476
11652
  registerAllTools(server, experimental);
@@ -11484,28 +11660,28 @@ async function startServer() {
11484
11660
  return result;
11485
11661
  }
11486
11662
  catch (error) {
11487
- log$2('error', '[MCP Server] Resource documentation read failed:', error);
11663
+ log$1('error', '[MCP Server] Resource documentation read failed:', error);
11488
11664
  throw error;
11489
11665
  }
11490
11666
  });
11491
- log$2('info', '[MCP Server] Registered resources: documentation');
11667
+ log$1('info', '[MCP Server] Registered resources: documentation');
11492
11668
  const credentialsLoaded = loadAndStoreCredentials();
11493
11669
  if (credentialsLoaded) {
11494
- log$2('info', '[MCP Server] Credentials loaded from config/environment for stdio mode');
11670
+ log$1('info', '[MCP Server] Credentials loaded from config/environment for stdio mode');
11495
11671
  }
11496
11672
  const transport = new stdio_js.StdioServerTransport();
11497
11673
  await server.connect(transport);
11498
- log$2('info', '[MCP Server] Applitools MCP Server started successfully (Stdio Mode)');
11499
- log$2('info', `[MCP Server] Experimental tools ${experimental ? 'enabled' : 'disabled'}`);
11500
- log$2('info', `[MCP Server] Available tools: ${registeredToolNames(experimental).join(', ')}`);
11501
- log$2('info', `[MCP Server] Available resources: documentation (${RESOURCE_URIS.DOCUMENTATION_README})`);
11674
+ log$1('info', '[MCP Server] Applitools MCP Server started successfully (Stdio Mode)');
11675
+ log$1('info', `[MCP Server] Experimental tools ${experimental ? 'enabled' : 'disabled'}`);
11676
+ log$1('info', `[MCP Server] Available tools: ${registeredToolNames(experimental).join(', ')}`);
11677
+ log$1('info', `[MCP Server] Available resources: documentation (${RESOURCE_URIS.DOCUMENTATION_README})`);
11502
11678
  }
11503
11679
  process.on('SIGINT', () => {
11504
- log$2('info', '[MCP Server] Received SIGINT, shutting down gracefully...');
11680
+ log$1('info', '[MCP Server] Received SIGINT, shutting down gracefully...');
11505
11681
  process.exit(0);
11506
11682
  });
11507
11683
  process.on('SIGTERM', () => {
11508
- log$2('info', '[MCP Server] Received SIGTERM, shutting down gracefully...');
11684
+ log$1('info', '[MCP Server] Received SIGTERM, shutting down gracefully...');
11509
11685
  process.exit(0);
11510
11686
  });
11511
11687
  const REJECTION_LOG_THROTTLE_MS = 1000;
@@ -11528,17 +11704,17 @@ function makeThrottledRejectionHandler(logFn, throttleMs = REJECTION_LOG_THROTTL
11528
11704
  }
11529
11705
  };
11530
11706
  }
11531
- process.on('unhandledRejection', makeThrottledRejectionHandler((...args) => log$2('error', ...args)));
11707
+ process.on('unhandledRejection', makeThrottledRejectionHandler((...args) => log$1('error', ...args)));
11532
11708
  process.on('uncaughtException', error => {
11533
11709
  if (error.code === 'EPIPE') {
11534
11710
  process.stderr.write('[MCP Server] Client disconnected (EPIPE), shutting down gracefully...\n');
11535
11711
  process.exit(0);
11536
11712
  }
11537
- log$2('error', '[MCP Server] Uncaught Exception:', error);
11713
+ log$1('error', '[MCP Server] Uncaught Exception:', error);
11538
11714
  });
11539
11715
 
11540
11716
  startServer().catch(error => {
11541
- log$2('error', '[MCP Server] Failed to start Applitools Eyes MCP server:', error);
11717
+ log$1('error', '[MCP Server] Failed to start Applitools Eyes MCP server:', error);
11542
11718
  process.exit(1);
11543
11719
  });
11544
11720
  //# sourceMappingURL=index.js.map