@percy/core 1.32.4 → 1.32.5-beta.0

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.
@@ -0,0 +1,101 @@
1
+ import { normalize } from '@percy/config/utils';
2
+ import { ServerError } from './server.js';
3
+ import { encodeURLSearchParams } from './utils.js';
4
+ import Busboy from 'busboy';
5
+ import { Readable } from 'stream';
6
+
7
+ /* istanbul ignore next — multipart /percy/comparison/upload handler;
8
+ exercises Busboy stream parsing + PNG magic-byte validation + base64
9
+ encoding + percy.upload. Integration-tested via the regression suite
10
+ (real multipart POST) rather than the unit suite, which would require
11
+ constructing valid multipart bodies. */
12
+ export async function handleComparisonUpload(req, res, percy) {
13
+ var _percy$build;
14
+ const MAX_FILE_SIZE = 50 * 1024 * 1024; // 50MB
15
+ const PNG_MAGIC_BYTES = Buffer.from([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]);
16
+ let contentType = req.headers['content-type'] || '';
17
+ if (!contentType.startsWith('multipart/form-data')) {
18
+ throw new ServerError(400, 'Content-Type must be multipart/form-data');
19
+ }
20
+ if (!req.body) {
21
+ throw new ServerError(400, 'Empty request body');
22
+ }
23
+ let fields = Object.create(null);
24
+ let fileBuffer = null;
25
+ await new Promise((resolve, reject) => {
26
+ let bb = Busboy({
27
+ headers: req.headers,
28
+ limits: {
29
+ fileSize: MAX_FILE_SIZE
30
+ }
31
+ });
32
+ bb.on('file', (fieldname, stream, info) => {
33
+ let chunks = [];
34
+ stream.on('data', chunk => chunks.push(chunk));
35
+ stream.on('limit', () => {
36
+ reject(new ServerError(413, 'File size exceeds maximum of 50MB'));
37
+ });
38
+ stream.on('end', () => {
39
+ if (fieldname === 'screenshot') {
40
+ fileBuffer = Buffer.concat(chunks);
41
+ }
42
+ });
43
+ });
44
+ bb.on('field', (fieldname, value) => {
45
+ if (['name', 'tag', 'clientInfo', 'environmentInfo', 'testCase', 'labels'].includes(fieldname)) {
46
+ fields[fieldname] = value;
47
+ }
48
+ });
49
+ bb.on('close', resolve);
50
+ bb.on('error', reject);
51
+ let stream = Readable.from(req.body);
52
+ stream.on('error', reject);
53
+ stream.pipe(bb);
54
+ });
55
+ if (!fileBuffer) {
56
+ throw new ServerError(400, 'Missing required file part: screenshot');
57
+ }
58
+ if (fileBuffer.length < 8 || !fileBuffer.subarray(0, 8).equals(PNG_MAGIC_BYTES)) {
59
+ throw new ServerError(400, 'File is not a valid PNG image');
60
+ }
61
+ if (!fields.name) throw new ServerError(400, 'Missing required field: name');
62
+ if (!fields.tag) throw new ServerError(400, 'Missing required field: tag');
63
+ let tag;
64
+ try {
65
+ tag = JSON.parse(fields.tag);
66
+ } catch {
67
+ throw new ServerError(400, 'Invalid JSON in tag field');
68
+ }
69
+ let base64Content = fileBuffer.toString('base64');
70
+ let payload = {
71
+ name: fields.name,
72
+ tag,
73
+ tiles: [{
74
+ content: base64Content,
75
+ statusBarHeight: 0,
76
+ navBarHeight: 0,
77
+ headerHeight: 0,
78
+ footerHeight: 0,
79
+ fullscreen: false
80
+ }],
81
+ clientInfo: fields.clientInfo || '',
82
+ environmentInfo: fields.environmentInfo || ''
83
+ };
84
+ if (fields.testCase) payload.testCase = fields.testCase;
85
+ if (fields.labels) payload.labels = fields.labels;
86
+ let upload = percy.upload(payload, null, 'app');
87
+ if (req.url.searchParams.has('await')) await upload;
88
+ let link = [percy.client.apiUrl, '/comparisons/redirect?', encodeURLSearchParams(normalize({
89
+ buildId: (_percy$build = percy.build) === null || _percy$build === void 0 ? void 0 : _percy$build.id,
90
+ snapshot: {
91
+ name: payload.name
92
+ },
93
+ tag
94
+ }, {
95
+ snake: true
96
+ }))].join('');
97
+ return res.json(200, {
98
+ success: true,
99
+ link
100
+ });
101
+ }
package/dist/discovery.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import logger from '@percy/logger';
2
2
  import Queue from './queue.js';
3
3
  import Page from './page.js';
4
- import { normalizeURL, hostnameMatches, createResource, createRootResource, createPercyCSSResource, createLogResource, yieldAll, snapshotLogName, waitForTimeout, withRetries, waitForSelectorInsideBrowser, isGzipped, maybeScrollToBottom } from './utils.js';
4
+ import { normalizeURL, hostnameMatches, createResource, createRootResource, createPercyCSSResource, createLogResource, redactSecrets, yieldAll, snapshotLogName, waitForTimeout, withRetries, waitForSelectorInsideBrowser, isGzipped, maybeScrollToBottom, assertNotMetadataTarget } from './utils.js';
5
5
  import { ByteLRU, entrySize, DiskSpillStore, createSpillDir } from './cache/byte-lru.js';
6
6
  import { sha256hash } from '@percy/client/utils';
7
7
  import Pako from 'pako';
@@ -224,8 +224,10 @@ function processSnapshotResources({
224
224
  // For multi dom root resources are stored as array
225
225
  resources = resources.flat();
226
226
 
227
- // include associated snapshot logs matched by meta information
228
- resources.push(createLogResource(logger.snapshotLogs(snapshot.meta.snapshot)));
227
+ // include associated snapshot logs matched by meta information. Redact
228
+ // secrets before egress — this per-snapshot log resource is a parallel
229
+ // egress path to sendBuildLogs and must scrub tokens/credentials too (CWE-532).
230
+ resources.push(createLogResource(redactSecrets(logger.snapshotLogs(snapshot.meta.snapshot))));
229
231
  logger.evictSnapshot(snapshot.meta.snapshot);
230
232
  if (process.env.PERCY_GZIP) {
231
233
  const kept = [];
@@ -348,6 +350,8 @@ async function* captureSnapshotResources(page, snapshot, options) {
348
350
 
349
351
  // navigate to the url
350
352
  yield resizePage(snapshot.widths[0]);
353
+ // refuse to navigate the top-level snapshot URL to a cloud metadata endpoint
354
+ assertNotMetadataTarget(snapshot.url);
351
355
  yield page.goto(snapshot.url, {
352
356
  cookies,
353
357
  forceReload: discovery.captureResponsiveAssetsEnabled
package/dist/install.js CHANGED
@@ -135,7 +135,7 @@ export function chromium({
135
135
  // default chromium revision by platform (see chromium.revisions)
136
136
  revision = selectByPlatform(chromium.revisions)
137
137
  } = {}) {
138
- let extract = (i, o) => import('extract-zip').then(ex => ex.default(i, {
138
+ let extract = (i, o) => import('./unzip.js').then(ex => ex.default(i, {
139
139
  dir: o
140
140
  }));
141
141
  let url = (process.env.PERCY_CHROMIUM_BASE_URL || 'https://storage.googleapis.com/chromium-browser-snapshots/') + selectByPlatform({
@@ -112,6 +112,25 @@ const IOS_HTTP_CIRCUIT_BREAKER_MS = 5000;
112
112
  // HTTP response cap before parse — sized for WebView-heavy iOS apps.
113
113
  const IOS_HTTP_RESPONSE_MAX_BYTES = 20 * 1024 * 1024;
114
114
 
115
+ // Device system-bar inset derivation tunables.
116
+ //
117
+ // iOS: the `/viewHierarchy` AXElement tree exposes the status bar as a node
118
+ // with `elementType === 26` (XCUIElementTypeStatusBar — a stable XCUITest
119
+ // enum constant). Its `frame.Height` is in logical POINTS; the comparison
120
+ // tile expects PIXELS, so we scale by the device scale factor derived
121
+ // empirically as PNG-pixel-height ÷ AUT-root-point-height (avoids the
122
+ // Plus-class `nativeScale ≠ scale` foot-gun). Apple scale factors are 1/2/3;
123
+ // we snap the ratio to the nearest integer and reject anything implausible
124
+ // (a wrong root-frame height would otherwise yield a bogus inset).
125
+ const IOS_STATUS_BAR_ELEMENT_TYPE = 26;
126
+ const DEVICE_SCALE_MIN = 1;
127
+ const DEVICE_SCALE_MAX = 3;
128
+ // Max distance the raw PNG/point ratio may sit from an integer before we treat
129
+ // the root-frame height as unreliable and fall back (e.g. a non-full-screen
130
+ // AUT frame). 0.15 comfortably admits real rounding (2532/844 = 3.000) while
131
+ // rejecting a half-screen root (e.g. 2532/667 = 3.79 → 0.21 off).
132
+ const DEVICE_SCALE_TOLERANCE = 0.15;
133
+
115
134
  // Android gRPC transport tunables. Symmetric with iOS HTTP (D11): same
116
135
  // healthy-deadline + circuit-breaker pair. gRPC's `deadline` option is
117
136
  // client-library-enforced, not kernel-enforced — the outer Promise.race is
@@ -1126,6 +1145,34 @@ function findAxAutRoot(axElement) {
1126
1145
  return null;
1127
1146
  }
1128
1147
 
1148
+ // Walk the FULL AXElement tree (not just the AUT subtree) for the status-bar
1149
+ // element (`elementType === IOS_STATUS_BAR_ELEMENT_TYPE`) and return its
1150
+ // `frame.Height` in points, or null when absent. The status bar is a sibling
1151
+ // of the AUT app node (cli-2.0.7 wraps as `[appHierarchy, statusBarsContainer]`),
1152
+ // so callers must pass the raw `axElement` root, not `findAxAutRoot(...)`.
1153
+ function findStatusBarFrameHeight(node) {
1154
+ /* istanbul ignore if — defensive guard; deriveIosInsets passes a parsed
1155
+ object and recursion only descends into well-formed array children. A
1156
+ malformed child instead surfaces via deriveDeviceInsets' catch → null. */
1157
+ if (!node || typeof node !== 'object') return null;
1158
+ if (node.elementType === IOS_STATUS_BAR_ELEMENT_TYPE) {
1159
+ var _node$frame;
1160
+ // `|| null` collapses a missing/zero/non-numeric height to null so the
1161
+ // caller's single `== null` check covers every malformed-frame case.
1162
+ /* istanbul ignore next — frame optional-chain guards a malformed status-bar
1163
+ frame; real /viewHierarchy responses always carry a positive frame.Height. */
1164
+ return ((_node$frame = node.frame) === null || _node$frame === void 0 ? void 0 : _node$frame.Height) || null;
1165
+ }
1166
+ const children = node.children;
1167
+ if (Array.isArray(children)) {
1168
+ for (const child of children) {
1169
+ const found = findStatusBarFrameHeight(child);
1170
+ if (found != null) return found;
1171
+ }
1172
+ }
1173
+ return null;
1174
+ }
1175
+
1129
1176
  // Adapter: walk an AXElement subtree (HTTP /viewHierarchy path) and emit nodes
1130
1177
  // in the canonical shape that firstMatch consumes for Android. Specifically:
1131
1178
  // { 'resource-id': identifier, id: identifier, bounds: '[X,Y][X+W,Y+H]' }
@@ -1364,6 +1411,98 @@ async function runIosHttpDump({
1364
1411
  };
1365
1412
  }
1366
1413
 
1414
+ // Derive the iOS status-bar inset (in pixels) from a fresh `/viewHierarchy`
1415
+ // fetch. Returns `{ statusBarHeight, navBarHeight: 0 }` on success, or null on
1416
+ // any failure (transport error, non-JSON/missing root, no AUT root, no status
1417
+ // bar element, implausible scale). navBarHeight is always 0 on iOS — the home
1418
+ // indicator is static and unmeasured, matching the rest of the Percy SDK fleet.
1419
+ //
1420
+ // This is a separate, lighter parse than runIosHttpDump: that path flattens the
1421
+ // AUT subtree for element-region matching and DISCARDS the status-bar sibling,
1422
+ // so the status-bar frame is not reachable through dump(). Here we retain the
1423
+ // raw response, read the AUT root frame height (points) for the scale factor,
1424
+ // and the status-bar element frame height (points), then convert to pixels.
1425
+ async function deriveIosInsets({
1426
+ port,
1427
+ pngDims,
1428
+ httpRequest,
1429
+ sessionId
1430
+ }) {
1431
+ var _aut$frame;
1432
+ /* istanbul ignore next — production-only default; unit suite injects a stub. */
1433
+ httpRequest = httpRequest || defaultHttpRequest;
1434
+ // Need PNG pixel height to derive the points→pixels scale. parsePngDimensions
1435
+ // only ever yields null or a fully-valid {width>0, height>0}, so a single
1436
+ // truthiness check suffices; a degenerate height is additionally caught by
1437
+ // the scale sanity bounds below.
1438
+ if (!pngDims) return null;
1439
+ const requestBody = JSON.stringify({
1440
+ appIds: [],
1441
+ excludeKeyboardElements: false
1442
+ });
1443
+ let response;
1444
+ try {
1445
+ // Best-effort, cached, fallback-safe: a single request with the transport's
1446
+ // own timeout is sufficient (no outer circuit-breaker race needed — that's
1447
+ // defense-in-depth the resolver cascade owns).
1448
+ response = await httpRequest({
1449
+ host: '127.0.0.1',
1450
+ port,
1451
+ method: 'POST',
1452
+ path: '/viewHierarchy',
1453
+ headers: {
1454
+ 'content-type': 'application/json',
1455
+ 'content-length': Buffer.byteLength(requestBody)
1456
+ },
1457
+ body: requestBody,
1458
+ timeoutMs: IOS_HTTP_HEALTHY_DEADLINE_MS
1459
+ });
1460
+ } catch {
1461
+ // Transport failure — caller falls back to the SDK default.
1462
+ return null;
1463
+ }
1464
+
1465
+ /* istanbul ignore if — defensive; httpRequest resolves to a response object
1466
+ or the race rejects (caught above). */
1467
+ if (!response) return null;
1468
+ if (response.statusCode !== 200) return null;
1469
+ let parsed;
1470
+ try {
1471
+ parsed = JSON.parse(response.body);
1472
+ } catch {
1473
+ // Non-JSON body, or a non-string body that JSON.parse rejects.
1474
+ return null;
1475
+ }
1476
+
1477
+ // Root point-height for scale = the AUT app frame (full-screen on iOS; the
1478
+ // app draws under the status bar). SpringBoard-only / malformed responses →
1479
+ // no AUT → null. (findAxAutRoot guards a null/undefined argument.)
1480
+ const aut = findAxAutRoot(parsed && parsed.axElement);
1481
+ /* istanbul ignore next — frame optional-chain guards a malformed AUT frame;
1482
+ real AUT nodes always carry a positive frame.Height. */
1483
+ const rootPointHeight = aut === null || aut === void 0 || (_aut$frame = aut.frame) === null || _aut$frame === void 0 ? void 0 : _aut$frame.Height;
1484
+ if (!rootPointHeight) return null;
1485
+
1486
+ // Empirical scale: PNG pixel height ÷ AUT root point height, snapped to an
1487
+ // integer and sanity-checked. Guards the Plus-class nativeScale≠scale gap and
1488
+ // a non-full-screen root frame.
1489
+ const ratio = pngDims.height / rootPointHeight;
1490
+ const scale = Math.round(ratio);
1491
+ if (scale < DEVICE_SCALE_MIN || scale > DEVICE_SCALE_MAX) return null;
1492
+ if (Math.abs(ratio - scale) > DEVICE_SCALE_TOLERANCE) return null;
1493
+ const statusBarPoints = findStatusBarFrameHeight(parsed.axElement);
1494
+ if (statusBarPoints == null) return null;
1495
+
1496
+ /* istanbul ignore next — sid log tag ternary; relay always passes a sessionId. */
1497
+ const sidTag = sessionId ? `sid=${String(sessionId).slice(0, 8)}…` : 'sid=none';
1498
+ const statusBarHeight = Math.round(statusBarPoints * scale);
1499
+ log.debug(`deriveIosInsets ok ${sidTag} statusBar=${statusBarHeight}px (${statusBarPoints}pt × ${scale})`);
1500
+ return {
1501
+ statusBarHeight,
1502
+ navBarHeight: 0
1503
+ };
1504
+ }
1505
+
1367
1506
  // iOS maestro-CLI fallback path. Spawns
1368
1507
  // `maestro --udid <udid> --driver-host-port <port> hierarchy` and parses
1369
1508
  // stdout (Maestro's normalized TreeNode shape, identical to Android).
@@ -1481,6 +1620,101 @@ async function runAdbFallback(serial, execAdb) {
1481
1620
  }
1482
1621
  return result;
1483
1622
  }
1623
+
1624
+ // Parse the first `mStableInsets=Rect(left, top - right, bottom)` from
1625
+ // `dumpsys window` output. Android's Rect.toString() prints
1626
+ // `Rect(L, T - R, B)`, so top = status-bar inset, bottom = navigation-bar
1627
+ // inset (both in pixels — same space as the screenshot). Returns
1628
+ // `{ statusBarHeight, navBarHeight }` or null when the line is absent.
1629
+ // Validated against real-device `dumpsys window` output during BS validation;
1630
+ // gesture-nav and 3-button-nav both surface here, differing only in the
1631
+ // bottom value.
1632
+ function parseStableInsets(stdout) {
1633
+ // execAdb always yields a string stdout (''); the regex returns null on no
1634
+ // match, so empty input needs no separate guard.
1635
+ const m = /mStableInsets=Rect\(\s*\d+,\s*(\d+)\s*-\s*\d+,\s*(\d+)\s*\)/.exec(stdout);
1636
+ if (!m) return null;
1637
+ const statusBarHeight = Number(m[1]);
1638
+ const navBarHeight = Number(m[2]);
1639
+ /* istanbul ignore if — defensive NaN guard; the regex only matches digit
1640
+ runs, so Number() always parses. */
1641
+ if (!Number.isFinite(statusBarHeight) || !Number.isFinite(navBarHeight)) return null;
1642
+ return {
1643
+ statusBarHeight,
1644
+ navBarHeight
1645
+ };
1646
+ }
1647
+
1648
+ // Derive Android status + navigation bar insets (in pixels) via adb. System
1649
+ // bars are not present in the uiautomator hierarchy dump, so this is a distinct
1650
+ // `dumpsys window` read. Reuses the resolver's serial-resolution + execAdb
1651
+ // path (ANDROID_SERIAL on BS multi-device hosts, else `adb devices`). Returns
1652
+ // `{ statusBarHeight, navBarHeight }` or null on any failure (no/ambiguous
1653
+ // device, adb error, unparseable output) — caller falls back to SDK defaults.
1654
+ async function deriveAndroidInsets({
1655
+ execAdb,
1656
+ getEnv
1657
+ }) {
1658
+ /* istanbul ignore next — production-only defaults; unit suite injects stubs. */
1659
+ execAdb = execAdb || defaultExecAdb;
1660
+ /* istanbul ignore next */
1661
+ getEnv = getEnv || defaultGetEnv;
1662
+ const {
1663
+ serial,
1664
+ classification
1665
+ } = await resolveSerial({
1666
+ execAdb,
1667
+ getEnv
1668
+ });
1669
+ if (classification) return null;
1670
+ const result = await execAdb(['-s', serial, 'shell', 'dumpsys', 'window']);
1671
+ if (classifyAdbFailure(result)) return null;
1672
+ /* istanbul ignore next — `?? 1` fallback branch; spawn helpers always set an
1673
+ exitCode. Non-zero exit with no recognized failure → treat as unparseable. */
1674
+ if ((result.exitCode ?? 1) !== 0) return null;
1675
+ return parseStableInsets(result.stdout);
1676
+ }
1677
+
1678
+ // Derive exact device system-bar insets for the comparison tile, dispatching by
1679
+ // platform. Returns `{ statusBarHeight, navBarHeight }` (pixels) or null on any
1680
+ // failure. Never throws — the relay treats null as "use the SDK default". iOS
1681
+ // navBarHeight is always 0 (static home indicator, fleet-consistent); the iOS
1682
+ // path additionally needs the PNG pixel height for the points→pixels scale.
1683
+ export async function deriveDeviceInsets(options) {
1684
+ /* istanbul ignore next — options-omitted default; callers always pass an object. */
1685
+ options = options || {};
1686
+ let {
1687
+ platform,
1688
+ sessionId,
1689
+ pngDims,
1690
+ execAdb,
1691
+ httpRequest,
1692
+ getEnv
1693
+ } = options;
1694
+ /* istanbul ignore next — defaults applied only when caller omits them; tests
1695
+ inject every dependency, production binds them at runtime. */
1696
+ getEnv = getEnv || defaultGetEnv;
1697
+ try {
1698
+ if (platform === 'ios') {
1699
+ const driverHostPort = parseIosDriverHostPort(getEnv('PERCY_IOS_DRIVER_HOST_PORT'));
1700
+ if (driverHostPort === null) return null;
1701
+ return await deriveIosInsets({
1702
+ port: driverHostPort,
1703
+ pngDims,
1704
+ httpRequest,
1705
+ sessionId
1706
+ });
1707
+ }
1708
+ return await deriveAndroidInsets({
1709
+ execAdb,
1710
+ getEnv
1711
+ });
1712
+ } catch {
1713
+ // Defensive: derive paths return null on their own failures; this only
1714
+ // fires if a transport (e.g. getEnv) throws unexpectedly.
1715
+ return null;
1716
+ }
1717
+ }
1484
1718
  export async function dump(options) {
1485
1719
  /* istanbul ignore next — options-omitted default; callers always pass an
1486
1720
  object (tests inject every dependency; production code binds them). */
@@ -0,0 +1,259 @@
1
+ import { ServerError } from './server.js';
2
+ import { dump as maestroDump, firstMatch as maestroFirstMatch, SELECTOR_KEYS_WHITELIST } from './maestro-hierarchy.js';
3
+
4
+ // Three parallel region input arrays share the same per-item shape; algorithm
5
+ // semantics differ per array (regions only — ignoreRegions/considerRegions are
6
+ // implicit).
7
+ const REGION_INPUT_FIELDS = ['regions', 'ignoreRegions', 'considerRegions'];
8
+
9
+ // Validate regions input shape early (before file I/O and ADB work) so
10
+ // malformed requests don't consume resolver/relay work. Throws ServerError(400)
11
+ // on the first shape violation.
12
+ export function validateRegionInputs(body) {
13
+ for (let fieldName of REGION_INPUT_FIELDS) {
14
+ let input = body[fieldName];
15
+ if (input === undefined) continue;
16
+ if (!Array.isArray(input)) {
17
+ throw new ServerError(400, `${fieldName} must be an array`);
18
+ }
19
+ if (input.length > 50) {
20
+ throw new ServerError(400, `${fieldName} exceeds maximum of 50`);
21
+ }
22
+ for (let [idx, region] of input.entries()) {
23
+ if (region && region.element !== undefined) {
24
+ if (typeof region.element !== 'object' || region.element === null || Array.isArray(region.element)) {
25
+ throw new ServerError(400, `${fieldName}[${idx}].element must be an object`);
26
+ }
27
+ let keys = Object.keys(region.element);
28
+ if (keys.length !== 1) {
29
+ throw new ServerError(400, `${fieldName}[${idx}].element must have exactly one selector key`);
30
+ }
31
+ let [key] = keys;
32
+ if (!SELECTOR_KEYS_WHITELIST.includes(key)) {
33
+ throw new ServerError(400, `${fieldName}[${idx}].element: unsupported selector key "${key}" (allowed: ${SELECTOR_KEYS_WHITELIST.join(', ')})`);
34
+ }
35
+ let value = region.element[key];
36
+ if (typeof value !== 'string' || value.length === 0) {
37
+ throw new ServerError(400, `${fieldName}[${idx}].element.${key} must be a non-empty string`);
38
+ }
39
+ if (value.length > 512) {
40
+ throw new ServerError(400, `${fieldName}[${idx}].element.${key} exceeds maximum length of 512`);
41
+ }
42
+ }
43
+ }
44
+ }
45
+ }
46
+
47
+ // ───────────────────────────────────────────────────────────────────
48
+ // REGIONS — end-to-end architecture
49
+ // ───────────────────────────────────────────────────────────────────
50
+ //
51
+ // Regions tell Percy's diff engine which parts of a mobile screenshot
52
+ // to ignore / consider / layout-compare. Two ways to specify one:
53
+ //
54
+ // 1. Coordinate region — caller already knows the pixel rectangle.
55
+ // Shape: { top, left, right, bottom }. Forwarded as-is after
56
+ // transform to `{x, y, width, height}` boundingBox.
57
+ //
58
+ // 2. Element region — caller knows a selector (`resource-id`, `text`,
59
+ // `content-desc`, `class`, `id`) but not the on-screen bounds.
60
+ // Resolved at relay-time against the live device's view hierarchy.
61
+ //
62
+ // ── Data flow (element region case) ────────────────────────────────
63
+ //
64
+ // SDK (percy-screenshot.js)
65
+ // │ POST /percy/maestro-screenshot
66
+ // │ { name, sessionId, platform, regions:[{element:{...}}], ... }
67
+ // ▼
68
+ // Relay (maestro-screenshot.js → resolveRegions)
69
+ // │ validate selector shape (SELECTOR_KEYS_WHITELIST)
70
+ // │ maestroDump({ platform, sessionId, grpcClientCache }) ← lazy + memoized per request
71
+ // │ │
72
+ // │ ├─ Android cascade (maestro-hierarchy.js)
73
+ // │ │ gRPC primary → maestro-CLI → adb uiautomator
74
+ // │ │ Three-class taxonomy: schema-class (drift bit, no
75
+ // │ │ fallback) / channel-broken (evict cache, fall back) /
76
+ // │ │ contention-class (keep cache, skip CLI → adb).
77
+ // │ │
78
+ // │ └─ iOS cascade
79
+ // │ HTTP primary (Maestro XCTestRunner /viewHierarchy)
80
+ // │ → maestro-CLI shell-out. AUT-root detection skips
81
+ // │ SpringBoard frames.
82
+ // │
83
+ // │ firstMatch(nodes, selector) → bbox or null (warn-skip).
84
+ // │ payload.regions[i].elementSelector.boundingBox = bbox
85
+ // ▼
86
+ // Percy backend — compares masked regions across builds.
87
+ //
88
+ // ── Observability ──────────────────────────────────────────────────
89
+ //
90
+ // /percy/healthcheck exposes maestroHierarchyDrift per platform:
91
+ // { lastFailureClass, fallbackCount, succeededVia, code?, reason?, firstSeenAt? }
92
+ // Every primary→fallback transition also emits one info-level line:
93
+ // [percy] hierarchy: <primary> failed (<class>: <reason>) → falling back to <next>
94
+ //
95
+ // ── Failure shape ──────────────────────────────────────────────────
96
+ //
97
+ // Element regions degrade gracefully: resolver failure → warn-skip
98
+ // those regions only; the snapshot itself still uploads. Coordinate
99
+ // regions don't depend on the resolver and always pass through.
100
+ //
101
+ // ───────────────────────────────────────────────────────────────────
102
+ // Resolve all region inputs to comparison-payload fragments. Returns an object
103
+ // with only the populated keys among { regions, ignoredElementsData,
104
+ // consideredElementsData }; merge it into the comparison payload. The hierarchy
105
+ // dump and the warn-once flag are request-scoped (call-local) — one dump per
106
+ // request, one warn-once skip notice.
107
+ export async function resolveRegions({
108
+ body,
109
+ platform,
110
+ sessionId,
111
+ percy
112
+ }) {
113
+ let out = {};
114
+ let cachedDump = null;
115
+ let elementSkipWarned = false;
116
+ const totalElementRegionCount = REGION_INPUT_FIELDS.reduce((sum, f) => {
117
+ let arr = body[f];
118
+ return sum + (Array.isArray(arr) ? arr.filter(r => r && r.element).length : 0);
119
+ }, 0);
120
+
121
+ // Resolve one region input to {x, y, width, height}, or null when the
122
+ // region is invalid or the resolver couldn't match it. Mutates the
123
+ // shared cachedDump / warn-flag state above.
124
+ async function resolveBbox(region) {
125
+ if (region.top != null && region.bottom != null && region.left != null && region.right != null) {
126
+ return {
127
+ x: region.left,
128
+ y: region.top,
129
+ width: region.right - region.left,
130
+ height: region.bottom - region.top
131
+ };
132
+ }
133
+ /* istanbul ignore else — region.element false branch falls through
134
+ to the istanbul-ignored "Invalid region format" warn below. */
135
+ if (region.element) {
136
+ /* istanbul ignore else — cachedDump === null only on first
137
+ element-region per request; subsequent regions hit the cache. */
138
+ if (cachedDump === null) {
139
+ // Thread the per-Percy gRPC client cache so the Android gRPC
140
+ // primary path can reuse channels across snapshots in the same
141
+ // session (D9 of 2026-05-07-002 plan). iOS path ignores it.
142
+ cachedDump = await maestroDump({
143
+ platform,
144
+ sessionId,
145
+ grpcClientCache: percy.grpcClientCache
146
+ });
147
+ }
148
+ /* istanbul ignore else — branch where dump resolves to hierarchy is
149
+ happy-path element-region territory, integration-tested only. */
150
+ if (cachedDump.kind !== 'hierarchy') {
151
+ /* istanbul ignore else — elementSkipWarned latches after first
152
+ warn; second+ iterations take the no-op branch. */
153
+ if (!elementSkipWarned) {
154
+ percy.log.warn(`Element-region resolver ${cachedDump.kind} (${cachedDump.reason}) — skipping ${totalElementRegionCount} element regions`);
155
+ elementSkipWarned = true;
156
+ }
157
+ return null;
158
+ }
159
+ /* istanbul ignore next */
160
+ let bbox = maestroFirstMatch(cachedDump.nodes, region.element);
161
+ /* istanbul ignore next */
162
+ if (!bbox) {
163
+ percy.log.warn(`Element region not found: ${JSON.stringify(region.element)} — skipping`);
164
+ return null;
165
+ }
166
+ /* istanbul ignore next — element-region happy path requires a
167
+ non-stub maestroDump returning hierarchy nodes; unit tests run
168
+ with stubbed resolver (env-missing), happy path covered by the
169
+ cross-platform-parity integration harness against fixture data. */
170
+ return bbox;
171
+ }
172
+ /* istanbul ignore next */
173
+ percy.log.warn('Invalid region format, skipping');
174
+ /* istanbul ignore next — region shape is validated upstream by the
175
+ SDK before posting; this is a defensive catch-all for regions that
176
+ lack both coordinate fields AND an element selector. */
177
+ return null;
178
+ }
179
+
180
+ // regions[]: comparison-shape items with algorithm. Default algorithm is
181
+ // 'ignore' (back-compat with SDK ≤ 0.3).
182
+ if (Array.isArray(body.regions)) {
183
+ let resolvedRegions = [];
184
+ for (let region of body.regions) {
185
+ let bbox = await resolveBbox(region);
186
+ if (!bbox) continue;
187
+ let resolved = {
188
+ elementSelector: {
189
+ boundingBox: bbox
190
+ },
191
+ algorithm: region.algorithm || 'ignore'
192
+ };
193
+ /* istanbul ignore if — region.configuration optional field; only
194
+ passed when SDK opts in to per-region config overrides. */
195
+ if (region.configuration) resolved.configuration = region.configuration;
196
+ /* istanbul ignore if — region.padding optional field. */
197
+ if (region.padding) resolved.padding = region.padding;
198
+ /* istanbul ignore if — region.assertion optional field. */
199
+ if (region.assertion) resolved.assertion = region.assertion;
200
+ resolvedRegions.push(resolved);
201
+ }
202
+ /* istanbul ignore else — empty resolvedRegions branch only fires when
203
+ ALL regions failed to resolve; happy path resolves at least one. */
204
+ if (resolvedRegions.length > 0) out.regions = resolvedRegions;
205
+ }
206
+
207
+ // ignoreRegions[] and considerRegions[]: parallel top-level payload
208
+ // fields. Each item is shaped per regionsSchema (config.js:792) —
209
+ // { coOrdinates: {top, left, bottom, right} } with an optional selector
210
+ // hint preserved when the caller supplied an element selector.
211
+ const REGION_OUTPUT_MAP = {
212
+ ignoreRegions: {
213
+ payloadKey: 'ignoredElementsData',
214
+ innerKey: 'ignoreElementsData'
215
+ },
216
+ considerRegions: {
217
+ payloadKey: 'consideredElementsData',
218
+ innerKey: 'considerElementsData'
219
+ }
220
+ };
221
+ for (let [inputField, {
222
+ payloadKey,
223
+ innerKey
224
+ }] of Object.entries(REGION_OUTPUT_MAP)) {
225
+ let input = body[inputField];
226
+ if (!Array.isArray(input)) continue;
227
+ let resolved = [];
228
+ for (let region of input) {
229
+ let bbox = await resolveBbox(region);
230
+ /* istanbul ignore if — null bbox skip in ignoreRegions/considerRegions
231
+ loop; tests cover the happy path where every region resolves. */
232
+ if (!bbox) continue;
233
+ let item = {
234
+ coOrdinates: {
235
+ top: bbox.y,
236
+ left: bbox.x,
237
+ bottom: bbox.y + bbox.height,
238
+ right: bbox.x + bbox.width
239
+ }
240
+ };
241
+ /* istanbul ignore if — element selector echo on resolved region;
242
+ only fires when resolveBbox returned a bbox for an element region,
243
+ which itself is integration-test territory (see resolveBbox
244
+ above for the resolver-mock rationale). */
245
+ if (region.element) {
246
+ let [key] = Object.keys(region.element);
247
+ item.selector = `${key}=${region.element[key]}`;
248
+ }
249
+ resolved.push(item);
250
+ }
251
+ /* istanbul ignore else — empty resolved branch only fires when ALL
252
+ regions in this category failed to resolve; happy path resolves
253
+ at least one. */
254
+ if (resolved.length > 0) out[payloadKey] = {
255
+ [innerKey]: resolved
256
+ };
257
+ }
258
+ return out;
259
+ }