@percy/nightwatch 2.2.1-beta.0 → 2.2.1-beta.1

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.
@@ -46,8 +46,10 @@ module.exports = class PercySnapshotCommand {
46
46
  // Readiness gate — runs before serialize when CLI supports it.
47
47
  const readinessDiagnostics = await waitForReady(this.api, options, utils, log);
48
48
 
49
- // Serialize and capture the DOM
50
- let { domSnapshot, url } = await captureDOM(this.api, options, utils, log, domScript);
49
+ // Thread domScript + log through ctx so concurrent percySnapshot calls
50
+ // (parallel workers in the same Node process) don't race on shared
51
+ // module-level state.
52
+ let { domSnapshot, url } = await captureDOM(this.api, options, utils, domScript, log);
51
53
 
52
54
  // Attach readiness diagnostics so the CLI can log timing and pass/fail
53
55
  if (readinessDiagnostics && domSnapshot && typeof domSnapshot === 'object' && !Array.isArray(domSnapshot)) {
package/lib/snapshot.js CHANGED
@@ -1,6 +1,31 @@
1
+ // Canonical iframe-capture helpers, single source of truth (percy/cli #2319).
2
+ // Aliased to the local _FRAME_ names this module already uses.
3
+ const {
4
+ DEFAULT_MAX_IFRAME_DEPTH: DEFAULT_MAX_FRAME_DEPTH,
5
+ isUnsupportedIframeSrc,
6
+ clampIframeDepth: clampFrameDepth,
7
+ normalizeIgnoreSelectors
8
+ } = require('@percy/sdk-utils');
9
+
1
10
  const CS_MAX_SCREENSHOT_LIMIT = 25000;
2
11
  const SCROLL_DEFAULT_SLEEP_TIME = 0.45; // 450ms
3
12
 
13
+ // Kept for backward compatibility with callers that previously pinned a
14
+ // module-scope domScript + log. The new code threads both through ctx /
15
+ // function arguments so two concurrent percySnapshot calls cannot race on
16
+ // shared module state. This function is a no-op.
17
+ function setSnapshotContext(/* script, logger */) {
18
+ // Intentionally empty — context now flows through ctx.
19
+ }
20
+
21
+ function getOrigin(url) {
22
+ try {
23
+ return new URL(url).origin;
24
+ } catch {
25
+ return null;
26
+ }
27
+ }
28
+
4
29
  function ignoreCanvasSerializationErrors(options = {}, utils) {
5
30
  return options?.ignoreCanvasSerializationErrors ??
6
31
  utils?.percy?.config?.snapshot?.ignoreCanvasSerializationErrors ??
@@ -102,7 +127,262 @@ function getCookies(browser) {
102
127
  }).catch(() => []);
103
128
  }
104
129
 
105
- async function captureSerializedDOM(browser, options = {}, utils) {
130
+ function resolveMaxFrameDepth(options = {}, utils) {
131
+ return clampFrameDepth(
132
+ options.maxIframeDepth ??
133
+ utils?.percy?.config?.snapshot?.maxIframeDepth ??
134
+ DEFAULT_MAX_FRAME_DEPTH
135
+ );
136
+ }
137
+
138
+ function resolveIgnoreSelectors(options = {}, utils) {
139
+ return normalizeIgnoreSelectors(
140
+ options.ignoreIframeSelectors ??
141
+ utils?.percy?.config?.snapshot?.ignoreIframeSelectors ??
142
+ []
143
+ );
144
+ }
145
+
146
+ // In-browser script that walks document.querySelectorAll('iframe') and
147
+ // returns metadata for each. Defined as a function reference so the two
148
+ // call sites (top-level enumeration in captureCorsIframes and per-frame
149
+ // recursion in processFrameTree) share one body.
150
+ function enumerateIframesScript(selectors) {
151
+ let iframes = document.querySelectorAll('iframe');
152
+ let result = [];
153
+ for (let i = 0; i < iframes.length; i++) {
154
+ let frame = iframes[i];
155
+ let matchesIgnore = false;
156
+ if (selectors && selectors.length) {
157
+ for (let j = 0; j < selectors.length; j++) {
158
+ try { if (frame.matches(selectors[j])) { matchesIgnore = true; break; } } catch (e) { /* invalid selector — ignore */ }
159
+ }
160
+ }
161
+ result.push({
162
+ src: frame.src || '',
163
+ srcdoc: frame.getAttribute('srcdoc'),
164
+ percyElementId: frame.getAttribute('data-percy-element-id'),
165
+ dataPercyIgnore: frame.hasAttribute('data-percy-ignore'),
166
+ matchesIgnoreSelector: matchesIgnore,
167
+ index: i
168
+ });
169
+ }
170
+ return result;
171
+ }
172
+
173
+ function shouldSkipIframe(iframe, currentOrigin, log) {
174
+ if (iframe.dataPercyIgnore) {
175
+ log?.debug?.(`Skipping iframe marked with data-percy-ignore: ${iframe.src || '(no src)'}`);
176
+ return true;
177
+ }
178
+ if (iframe.matchesIgnoreSelector) {
179
+ log?.debug?.(`Skipping iframe matching ignoreIframeSelectors: ${iframe.src || '(no src)'}`);
180
+ return true;
181
+ }
182
+ if (!iframe.src || isUnsupportedIframeSrc(iframe.src)) {
183
+ if (iframe.src) log?.debug?.(`Skipping unsupported iframe src: ${iframe.src}`);
184
+ return true;
185
+ }
186
+ if (iframe.srcdoc) {
187
+ log?.debug?.(`Skipping srcdoc iframe at index ${iframe.index}`);
188
+ return true;
189
+ }
190
+ let frameOrigin = getOrigin(iframe.src);
191
+ if (!frameOrigin) {
192
+ log?.debug?.(`Skipping iframe with invalid URL: ${iframe.src}`);
193
+ return true;
194
+ }
195
+ if (frameOrigin === currentOrigin) {
196
+ log?.debug?.(`Skipping same-origin iframe: ${iframe.src}`);
197
+ return true;
198
+ }
199
+ if (!iframe.percyElementId) {
200
+ log?.debug?.(`Skipping cross-origin iframe without data-percy-element-id: ${iframe.src}`);
201
+ return true;
202
+ }
203
+ return false;
204
+ }
205
+
206
+ // Switch into the given iframe element from the current frame context, capture
207
+ // its DOM, then recurse into any cross-origin iframes nested inside it. Restores
208
+ // the parent context on exit. Bounded by maxFrameDepth to prevent runaway
209
+ // recursion when pages link to each other in cycles. `ancestorUrls` tracks the
210
+ // chain of frame URLs above this one — if the current frame's URL appears in
211
+ // the chain, we treat it as a cycle and stop descending (still capturing the
212
+ // current frame once).
213
+ async function processFrameTree(browser, iframe, depth, ancestorUrls, ctx) {
214
+ const { maxFrameDepth, ignoreSelectors, serializeOptions, domScript, log } = ctx;
215
+ if (depth > maxFrameDepth) {
216
+ log?.debug?.(`Reached max iframe nesting depth (${maxFrameDepth}); stopping at ${iframe.src}`);
217
+ return [];
218
+ }
219
+ if (ancestorUrls && ancestorUrls.has(iframe.src)) {
220
+ log?.debug?.(`Skipping cyclic iframe (${iframe.src} appears in ancestor chain)`);
221
+ return [];
222
+ }
223
+
224
+ const collected = [];
225
+ let switchedIn = false;
226
+ let capturedError = null;
227
+
228
+ try {
229
+ log?.debug?.(`Processing cross-origin iframe (depth ${depth}): ${iframe.src}`);
230
+
231
+ // Switch to the iframe by its data-percy-element-id attribute instead of numeric
232
+ // index, which avoids drift if the DOM changes between enumeration and switch.
233
+ // CSS.escape() neutralises any quote/backslash characters that could otherwise
234
+ // break out of the attribute selector — defence in depth, since the id is
235
+ // SDK-generated.
236
+ let iframeElement = await executeScript(browser, function(percyId) {
237
+ /* eslint-disable-next-line no-undef */
238
+ const cssApi = (typeof CSS !== 'undefined') ? CSS : null;
239
+ const safeId = (cssApi && cssApi.escape) ? cssApi.escape(percyId) : String(percyId).replace(/["\\]/g, '\\$&');
240
+ return document.querySelector('iframe[data-percy-element-id="' + safeId + '"]');
241
+ }, [iframe.percyElementId]);
242
+
243
+ if (!iframeElement) {
244
+ log?.warn?.(`Could not find iframe element with data-percy-element-id: ${iframe.percyElementId}`);
245
+ return [];
246
+ }
247
+
248
+ await promisifyBrowserCommand(browser, 'frame', iframeElement);
249
+ switchedIn = true;
250
+
251
+ // Inject PercyDOM into the frame
252
+ if (domScript) {
253
+ await executeScript(browser, domScript);
254
+ log?.debug?.(`Injected PercyDOM into frame: ${iframe.src}`);
255
+ }
256
+
257
+ // Serialize the frame's DOM; enableJavaScript is intentionally forced to true
258
+ // to prevent the standard iframe serialization logic from running, since we
259
+ // handle cross-origin iframe serialization manually here
260
+ let frameResult = await executeScript(browser, function(opts) {
261
+ return {
262
+ /* eslint-disable-next-line no-undef */
263
+ snapshot: PercyDOM.serialize(opts),
264
+ frameUrl: document.URL
265
+ };
266
+ }, [{ ...serializeOptions, enableJavaScript: true }]);
267
+
268
+ if (!frameResult || !frameResult.snapshot) {
269
+ log?.warn?.(`Serialization returned empty result for frame: ${iframe.src}`);
270
+ return [];
271
+ }
272
+
273
+ log?.debug?.(`Captured cross-origin iframe (depth ${depth}): ${frameResult.frameUrl}`);
274
+
275
+ collected.push({
276
+ frameUrl: frameResult.frameUrl,
277
+ iframeData: { percyElementId: iframe.percyElementId },
278
+ iframeSnapshot: frameResult.snapshot
279
+ });
280
+
281
+ // Look for cross-origin iframes nested inside this frame and recurse into them.
282
+ // Same-origin descendants are already inlined as srcdoc by PercyDOM.serialize above.
283
+ if (depth < maxFrameDepth) {
284
+ let currentOrigin = getOrigin(frameResult.frameUrl);
285
+ let childIframesRaw = await executeScript(browser, enumerateIframesScript, [ignoreSelectors]);
286
+ let childIframes = Array.isArray(childIframesRaw) ? childIframesRaw : [];
287
+ let nextAncestors = new Set(ancestorUrls || []);
288
+ nextAncestors.add(frameResult.frameUrl);
289
+ nextAncestors.add(iframe.src);
290
+ for (let child of childIframes) {
291
+ if (shouldSkipIframe(child, currentOrigin, log)) continue;
292
+ let nested = await processFrameTree(browser, child, depth + 1, nextAncestors, ctx);
293
+ if (nested.length) collected.push(...nested);
294
+ }
295
+ }
296
+
297
+ return collected;
298
+ } catch (error) {
299
+ if (error && error.percyContextLost) {
300
+ // Merge any partial capture from the inner level into ours before propagating
301
+ if (Array.isArray(error.partialCapture) && error.partialCapture.length) {
302
+ collected.push(...error.partialCapture);
303
+ error.partialCapture = collected;
304
+ } else {
305
+ error.partialCapture = collected;
306
+ }
307
+ throw error;
308
+ }
309
+ log?.warn?.(`Failed to process cross-origin iframe ${iframe.src}: ${error.message}`);
310
+ capturedError = error;
311
+ return collected;
312
+ } finally {
313
+ if (switchedIn) {
314
+ // Step up exactly one level so an outer recursion can continue from its
315
+ // own context. If parentFrame fails we have no reliable way to land in
316
+ // the correct parent — fall back to top and signal the caller to stop
317
+ // iterating siblings (whose enumeration was performed in a now-lost
318
+ // context). Without this signal, sibling lookups would silently match
319
+ // against the top document and produce wrong percyElementId resolutions.
320
+ try {
321
+ await promisifyBrowserCommand(browser, 'frameParent');
322
+ } catch (e) {
323
+ log?.warn?.(`Failed to switch back to parent frame: ${e.message}`);
324
+ try { await promisifyBrowserCommand(browser, 'frame', null); } catch (_) {}
325
+ // Always raise percyContextLost regardless of depth: even at depth 1
326
+ // the fallback `frame(null)` leaves us at the top document, so the
327
+ // caller's pending sibling enumeration was performed in a now-stale
328
+ // context and must be aborted. Carry partial capture so the outer
329
+ // caller can keep what was already serialized successfully.
330
+ const err = new Error(`Lost parent frame context: ${e.message}`);
331
+ err.percyContextLost = true;
332
+ err.partialCapture = collected;
333
+ // Preserve the original error so it isn't swallowed by this throw
334
+ if (capturedError) err.cause = capturedError;
335
+ // eslint-disable-next-line no-unsafe-finally
336
+ throw err;
337
+ }
338
+ }
339
+ }
340
+ }
341
+
342
+ async function captureCorsIframes(browser, pageUrl, ctx) {
343
+ const { ignoreSelectors, log } = ctx;
344
+ try {
345
+ let iframeInfoRaw = await executeScript(browser, enumerateIframesScript, [ignoreSelectors]);
346
+ let iframeInfo = Array.isArray(iframeInfoRaw) ? iframeInfoRaw : [];
347
+ if (!iframeInfo.length) return [];
348
+
349
+ log?.debug?.(`Found ${iframeInfo.length} top-level iframe(s)`);
350
+
351
+ let pageOrigin = getOrigin(pageUrl);
352
+ let corsIframes = [];
353
+ let skippedCount = 0;
354
+
355
+ for (let iframe of iframeInfo) {
356
+ if (shouldSkipIframe(iframe, pageOrigin, log)) {
357
+ skippedCount++;
358
+ continue;
359
+ }
360
+ let entries;
361
+ try {
362
+ entries = await processFrameTree(browser, iframe, 1, new Set([pageUrl]), ctx);
363
+ } catch (error) {
364
+ if (error && error.percyContextLost) {
365
+ log?.warn?.('Aborting further nested CORS capture due to lost frame context');
366
+ if (Array.isArray(error.partialCapture) && error.partialCapture.length) {
367
+ corsIframes.push(...error.partialCapture);
368
+ }
369
+ break;
370
+ }
371
+ throw error;
372
+ }
373
+ if (entries && entries.length) corsIframes.push(...entries);
374
+ }
375
+
376
+ log?.debug?.(`Captured ${corsIframes.length} cross-origin iframe(s) (top-level skipped: ${skippedCount})`);
377
+
378
+ return corsIframes;
379
+ } catch (error) {
380
+ log?.warn?.(`Error capturing CORS iframes: ${error.message}`);
381
+ return [];
382
+ }
383
+ }
384
+
385
+ async function captureSerializedDOM(browser, options = {}, utils, domScript = null, log = null) {
106
386
  const serializeOptions = {
107
387
  ...options,
108
388
  ignoreCanvasSerializationErrors: ignoreCanvasSerializationErrors(options, utils),
@@ -120,6 +400,20 @@ async function captureSerializedDOM(browser, options = {}, utils) {
120
400
  if (!domSnapshot) domSnapshot = {};
121
401
  domSnapshot.cookies = await getCookies(browser);
122
402
 
403
+ // Capture cross-origin iframes. ctx carries the per-call domScript + log so
404
+ // concurrent percySnapshot invocations don't race on shared module state.
405
+ const ctx = {
406
+ maxFrameDepth: resolveMaxFrameDepth(options, utils),
407
+ ignoreSelectors: resolveIgnoreSelectors(options, utils),
408
+ serializeOptions,
409
+ domScript,
410
+ log
411
+ };
412
+ let corsIframes = await captureCorsIframes(browser, url, ctx);
413
+ if (corsIframes.length > 0) {
414
+ domSnapshot.corsIframes = corsIframes;
415
+ }
416
+
123
417
  return { domSnapshot, url };
124
418
  }
125
419
 
@@ -272,7 +566,12 @@ async function changeWindowDimensionAndWait(browser, width, height, resizeCount,
272
566
  async function maybeReloadPage(browser, domScript) {
273
567
  if (!process.env.PERCY_RESPONSIVE_CAPTURE_RELOAD_PAGE) return false;
274
568
  await promisifyBrowserCommand(browser, 'refresh');
275
- if (domScript) await executeScript(browser, domScript);
569
+ // Guard: if a consumer imported captureDOM directly (bypassing percySnapshot)
570
+ // domScript may be null. Skipping the re-injection is safe — the page reload
571
+ // will only matter when PercyDOM is also pinned.
572
+ if (domScript) {
573
+ await executeScript(browser, domScript);
574
+ }
276
575
  return true;
277
576
  }
278
577
 
@@ -296,7 +595,7 @@ async function getResponsiveHeight(browser, currentHeight, utils) {
296
595
  }, [minHeight]);
297
596
  }
298
597
 
299
- async function captureResponsiveDOM(browser, options, utils, log, domScript) {
598
+ async function captureResponsiveDOM(browser, options, utils, domScript = null, log = null) {
300
599
  const widths = getWidthsForMultiDOM(options.widths || [], utils?.percy?.widths || {});
301
600
  const domSnapshots = [];
302
601
  const { width: originalWidth, height: originalHeight } = await getWindowRect(browser);
@@ -331,7 +630,7 @@ async function captureResponsiveDOM(browser, options, utils, log, domScript) {
331
630
  await maybeSleepForResponsiveCapture();
332
631
  await maybeScrollForLazyLoad(browser);
333
632
 
334
- let { domSnapshot, url } = await captureSerializedDOM(browser, options, utils);
633
+ let { domSnapshot, url } = await captureSerializedDOM(browser, options, utils, domScript, log);
335
634
  domSnapshot.width = width;
336
635
  domSnapshots.push(domSnapshot);
337
636
  lastURL = url;
@@ -341,13 +640,36 @@ async function captureResponsiveDOM(browser, options, utils, log, domScript) {
341
640
  return { domSnapshot: domSnapshots, url: lastURL };
342
641
  }
343
642
 
344
- async function captureDOM(browser, options = {}, utils, log, domScript) {
643
+ // Backward-compatibility shim for the two trailing positional arguments.
644
+ //
645
+ // captureDOM is exported and was published (v2.2.1-beta.0) with the signature
646
+ // captureDOM(browser, options, utils, log, domScript)
647
+ // This branch reordered the trailing pair to (..., domScript, log) so the
648
+ // per-call domScript + logger could be threaded through ctx. Silently swapping
649
+ // two published positional args would break any external caller that imports
650
+ // captureDOM directly and still passes them in the old order.
651
+ //
652
+ // domScript is always the PercyDOM source (a string); log is always a logger
653
+ // object (or null/undefined). They are never the same type, so we can accept
654
+ // either order and route each value to its correct slot. This keeps both the
655
+ // old (log, domScript) and new (domScript, log) call shapes working.
656
+ function normalizeScriptAndLog(a, b) {
657
+ const isScript = v => typeof v === 'string';
658
+ if (isScript(a) && !isScript(b)) return { domScript: a, log: b ?? null };
659
+ if (isScript(b) && !isScript(a)) return { domScript: b, log: a ?? null };
660
+ // Neither is a string (e.g. both null, or domScript passed as non-string):
661
+ // fall back to the new positional order without reinterpreting.
662
+ return { domScript: a ?? null, log: b ?? null };
663
+ }
664
+
665
+ async function captureDOM(browser, options = {}, utils, arg4 = null, arg5 = null) {
666
+ const { domScript, log } = normalizeScriptAndLog(arg4, arg5);
345
667
  const responsiveEnabled = isResponsiveOptionEnabled(options, utils);
346
668
  if (responsiveEnabled) {
347
- return await captureResponsiveDOM(browser, options, utils, log, domScript);
669
+ return await captureResponsiveDOM(browser, options, utils, domScript, log);
348
670
  }
349
671
 
350
- return await captureSerializedDOM(browser, options, utils);
672
+ return await captureSerializedDOM(browser, options, utils, domScript, log);
351
673
  }
352
674
 
353
675
  async function slowScrollToBottom(browser, scrollSleep = SCROLL_DEFAULT_SLEEP_TIME) {
@@ -400,8 +722,12 @@ async function slowScrollToBottom(browser, scrollSleep = SCROLL_DEFAULT_SLEEP_TI
400
722
  module.exports = {
401
723
  captureSerializedDOM,
402
724
  captureDOM,
725
+ setSnapshotContext,
403
726
  slowScrollToBottom,
404
727
  ignoreCanvasSerializationErrors,
405
728
  ignoreStyleSheetSerializationErrors,
729
+ isUnsupportedIframeSrc,
730
+ getOrigin,
731
+ captureCorsIframes,
406
732
  waitForReady
407
733
  };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@percy/nightwatch",
3
3
  "description": "Nightwatch client library for visual testing with Percy",
4
- "version": "2.2.1-beta.0",
4
+ "version": "2.2.1-beta.1",
5
5
  "license": "MIT",
6
6
  "author": "Perceptual Inc.",
7
7
  "repository": "https://github.com/percy/percy-nightwatch",
@@ -29,14 +29,14 @@
29
29
  "test:types": "tsd"
30
30
  },
31
31
  "dependencies": {
32
- "@percy/sdk-utils": "^1.31.15-beta.0",
32
+ "@percy/sdk-utils": "1.32.3-beta.1",
33
33
  "@percy/selenium-webdriver": "^2.2.3"
34
34
  },
35
35
  "peerDependencies": {
36
36
  "nightwatch": ">=1 || >=2 || >=3"
37
37
  },
38
38
  "devDependencies": {
39
- "@percy/cli": "^1.31.4",
39
+ "@percy/cli": "1.31.14",
40
40
  "cross-env": "^10.1.0",
41
41
  "eslint": "^7.11.0",
42
42
  "eslint-config-standard": "^16.0.1",
@@ -49,5 +49,6 @@
49
49
  "nightwatch": "^3.12.3",
50
50
  "nyc": "^17.1.0",
51
51
  "tsd": "^0.33.0"
52
- }
52
+ },
53
+ "packageManager": "yarn@1.22.22+sha512.a6b2f7906b721bba3d67d4aff083df04dad64c399707841b7acf00f6b133b7ac24255f2652fa22ae3534329dc6180534e98d17432037ff6fd140556e2bb3137e"
53
54
  }