@percy/cli-app 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.
package/dist/exec.js CHANGED
@@ -1,8 +1,6 @@
1
- import fs from 'fs';
2
- import os from 'os';
3
- import path from 'path';
4
1
  import command from '@percy/cli-command';
5
2
  import * as ExecPlugin from '@percy/cli-exec';
3
+ import { maybeInjectMaestroServer, maybeInjectScreenshotDir, maybeInjectDriverHostPort } from './maestro-inject.js';
6
4
  export const ping = ExecPlugin.ping;
7
5
  export const stop = ExecPlugin.stop;
8
6
  export const start = command('start', {
@@ -14,158 +12,6 @@ export const start = command('start', {
14
12
  skipDiscovery: true
15
13
  }
16
14
  }, ExecPlugin.start.callback);
17
-
18
- // Locate the `test` subcommand in argv. Maestro accepts global parent
19
- // flags before the subcommand, e.g.:
20
- // maestro test flow.yaml
21
- // maestro --udid <serial> test flow.yaml
22
- // maestro --platform=android test flow.yaml
23
- // maestro --verbose --no-ansi test flow.yaml
24
- // We must find `test` by scanning rather than checking args[1] === 'test',
25
- // or our injects silently no-op when the customer pins a device.
26
- //
27
- // Returns the index of the `test` literal, or -1 if not present. Skips
28
- // over the value of known value-taking parent flags so a literal `test`
29
- // supplied as a flag value (e.g. `--udid test`) isn't mistaken for the
30
- // subcommand. Equals-form (`--flag=value`) doesn't need a skip — the
31
- // value is part of the same argv token.
32
- const MAESTRO_PARENT_VALUE_FLAGS = new Set(['--udid', '--device', '-p', '--platform', '--host', '--port', '--driver-host-port']);
33
- function findTestSubcommandIdx(args) {
34
- for (let i = 1; i < args.length; i++) {
35
- const tok = args[i];
36
- if (tok === 'test') return i;
37
- if (typeof tok === 'string' && MAESTRO_PARENT_VALUE_FLAGS.has(tok)) {
38
- i++; // skip the value of this flag
39
- }
40
- }
41
- return -1;
42
- }
43
- function hasExistingPercyServerFlag(args, testIdx) {
44
- for (let i = testIdx + 1; i < args.length - 1; i++) {
45
- if (args[i] === '-e' && /^PERCY_SERVER=/.test(args[i + 1])) return true;
46
- }
47
- return false;
48
- }
49
-
50
- // Returns the customer-supplied value of `--test-output-dir` (whether the
51
- // space-form `--test-output-dir <path>` or the equals-form
52
- // `--test-output-dir=<path>` — both are valid picocli syntax), or null if
53
- // absent. Returning the value (not just an index) lets the screenshot-dir
54
- // helper align PERCY_MAESTRO_SCREENSHOT_DIR with the customer's value in
55
- // either form without re-deriving it.
56
- //
57
- // An empty value (space-form value === '' or equals-form `--test-output-dir=`
58
- // with nothing after the `=`) is treated as ABSENT — returning the empty
59
- // string would tell the caller "customer set this" and bypass the
60
- // auto-resolve fallback, leaving Maestro to default its output location
61
- // while PERCY_MAESTRO_SCREENSHOT_DIR stays unset. That mismatch silently
62
- // produces all-404 snapshots, so fall through to the auto-resolve path
63
- // instead.
64
- const TEST_OUTPUT_DIR_EQ_PREFIX = '--test-output-dir=';
65
- function findTestOutputDirValue(args, testIdx) {
66
- for (let i = testIdx + 1; i < args.length; i++) {
67
- const tok = args[i];
68
- if (tok === '--test-output-dir' && i + 1 < args.length) {
69
- const val = args[i + 1];
70
- if (typeof val === 'string' && val.length > 0) return val;
71
- } else if (typeof tok === 'string' && tok.startsWith(TEST_OUTPUT_DIR_EQ_PREFIX)) {
72
- const val = tok.slice(TEST_OUTPUT_DIR_EQ_PREFIX.length);
73
- if (val.length > 0) return val;
74
- }
75
- }
76
- return null;
77
- }
78
-
79
- // Maestro's GraalJS sandbox does NOT inherit the parent process's env,
80
- // so `PERCY_SERVER_ADDRESS` exported by app:exec is invisible to the
81
- // SDK. When wrapping `maestro test`, surface the CLI address through
82
- // Maestro's only env channel — `-e KEY=VALUE` flags — so the SDK
83
- // healthcheck can find the local CLI without the customer having to
84
- // pair ports manually. No-op when the customer already supplied their
85
- // own `-e PERCY_SERVER=...`.
86
- //
87
- // When percy?.address() is falsy (percy disabled, start failed), emit a
88
- // WARN so the customer is not surprised by a silent zero-snapshot build.
89
- // The customer-override skip case (their own `-e PERCY_SERVER=...` is in
90
- // argv) does NOT warn — that's intentional flow control, not a problem.
91
- export function maybeInjectMaestroServer(ctx, log) {
92
- var _ctx$percy;
93
- const args = ctx === null || ctx === void 0 ? void 0 : ctx.argv;
94
- if (!Array.isArray(args) || args.length < 2) return;
95
- if (path.basename(args[0]) !== 'maestro') return;
96
- const testIdx = findTestSubcommandIdx(args);
97
- if (testIdx < 0) return;
98
- if (hasExistingPercyServerFlag(args, testIdx)) return;
99
- const addr = (_ctx$percy = ctx.percy) === null || _ctx$percy === void 0 ? void 0 : _ctx$percy.address();
100
- if (!addr) {
101
- log === null || log === void 0 || log.warn('app:exec did not start the Percy CLI server (percy disabled or start ' + 'failed); -e PERCY_SERVER not injected into maestro test. Snapshots will ' + 'NOT be uploaded. Set PERCY_TOKEN and re-run, or check the percy log above.');
102
- return;
103
- }
104
- // Inject after `test` so `-e KEY=VAL` is bound to the `test` subcommand
105
- // (the only Maestro subcommand that accepts `-e`).
106
- args.splice(testIdx + 1, 0, '-e', `PERCY_SERVER=${addr}`);
107
- }
108
-
109
- // Auto-resolve the Maestro screenshot output directory so customers don't
110
- // have to pair `export PERCY_MAESTRO_SCREENSHOT_DIR=...` with a matching
111
- // `--test-output-dir <same>` in their maestro test command.
112
- //
113
- // Resolution order:
114
- // 1. Customer set BOTH process.env.PERCY_MAESTRO_SCREENSHOT_DIR and
115
- // --test-output-dir in argv → trust them, do nothing.
116
- // 2. Customer set PERCY_MAESTRO_SCREENSHOT_DIR only → use it, inject
117
- // `--test-output-dir <env value>` into argv.
118
- // 3. Customer set --test-output-dir only → use that value, mirror it
119
- // into process.env.PERCY_MAESTRO_SCREENSHOT_DIR (so the SDK +
120
- // CLI relay see the same path).
121
- // 4. Neither set → pick `${process.cwd()}/.percy-out`. On any mkdir
122
- // failure (read-only CWD, EACCES, EEXIST as a file), fall back to
123
- // `${os.tmpdir()}/percy-maestro-<pid>` with a WARN log.
124
- //
125
- // The env-var update and argv splice always keep both sources of truth
126
- // (SDK reads env var; Maestro reads the flag) aligned to the same path.
127
- export function maybeInjectScreenshotDir(ctx, log) {
128
- const args = ctx === null || ctx === void 0 ? void 0 : ctx.argv;
129
- if (!Array.isArray(args) || args.length < 2) return;
130
- if (path.basename(args[0]) !== 'maestro') return;
131
- const testIdx = findTestSubcommandIdx(args);
132
- if (testIdx < 0) return;
133
- const envSet = !!process.env.PERCY_MAESTRO_SCREENSHOT_DIR;
134
- const existingFlagValue = findTestOutputDirValue(args, testIdx);
135
- const flagSet = existingFlagValue !== null;
136
-
137
- // Fully customer-controlled — nothing to do.
138
- if (envSet && flagSet) return;
139
- let resolved;
140
- if (envSet) {
141
- resolved = process.env.PERCY_MAESTRO_SCREENSHOT_DIR;
142
- } else if (flagSet) {
143
- resolved = existingFlagValue;
144
- } else {
145
- const preferred = path.join(process.cwd(), '.percy-out');
146
- try {
147
- fs.mkdirSync(preferred, {
148
- recursive: true
149
- });
150
- resolved = preferred;
151
- } catch (err) {
152
- const fallback = path.join(os.tmpdir(), `percy-maestro-${process.pid}`);
153
- try {
154
- fs.mkdirSync(fallback, {
155
- recursive: true
156
- });
157
- } catch (_) {
158
- // tmpdir mkdir failure is exceedingly rare; fall through and let
159
- // downstream code surface a clearer error than this helper can.
160
- }
161
- resolved = fallback;
162
- log === null || log === void 0 || log.warn(`Could not create ${preferred} (${err.code || err.message}); ` + `falling back to ${fallback}. Set PERCY_MAESTRO_SCREENSHOT_DIR to ` + 'pick a specific location.');
163
- }
164
- }
165
- if (!envSet) process.env.PERCY_MAESTRO_SCREENSHOT_DIR = resolved;
166
- // Inject right after `test` (the subcommand that owns `--test-output-dir`).
167
- if (!flagSet) args.splice(testIdx + 1, 0, '--test-output-dir', resolved);
168
- }
169
15
  export const exec = command('exec', {
170
16
  description: 'Start and stop Percy around a supplied command for native apps',
171
17
  usage: '[options] [--] <command>',
@@ -182,16 +28,21 @@ export const exec = command('exec', {
182
28
  skipDiscovery: true
183
29
  }
184
30
  }, async function* (ctx) {
185
- // The two helpers splice their flag groups at argv index 2 (between `test`
186
- // and the flow file) because `-e` and `--test-output-dir` are
187
- // `test`-subcommand options. Resulting argv for `maestro test flow.yaml`:
188
- // maestro test --test-output-dir <dir> -e PERCY_SERVER=<url> flow.yaml
189
- // iOS driver port: not prescribed from this side — the @percy/core relay
190
- // reads `PERCY_IOS_DRIVER_HOST_PORT` (BS-host-injected on production
191
- // hosts) and probes the documented Maestro 2.4.0 single-simulator default
192
- // (`127.0.0.1:7001`) when it isn't set. See `packages/core/src/maestro-hierarchy.js`.
31
+ // The helpers splice their flag groups right after `test` because `-e` and
32
+ // `--test-output-dir` are `test`-subcommand options; on iOS + Maestro >= 2.6 a
33
+ // third adds `--driver-host-port <port>`. Resulting argv for
34
+ // `maestro --platform=ios test flow.yaml`:
35
+ // maestro --platform=ios test --driver-host-port <port> --test-output-dir <dir> -e PERCY_SERVER=<url> flow.yaml
36
+ // iOS driver port: on Maestro >= 2.6 (ephemeral driver port) we prescribe a
37
+ // free port via `--driver-host-port` and mirror it to PERCY_IOS_DRIVER_HOST_PORT
38
+ // so the @percy/core relay reaches `/viewHierarchy` deterministically for
39
+ // element regions and device insets. On Maestro <= 2.4 the helper no-ops and
40
+ // the relay's `127.0.0.1:7001` probe (the deterministic 2.4.0 default) serves
41
+ // those customers. On BrowserStack the port is host-injected and this path
42
+ // never runs. See `packages/core/src/maestro-hierarchy.js`.
193
43
  maybeInjectMaestroServer(ctx, ctx.log);
194
44
  maybeInjectScreenshotDir(ctx, ctx.log);
45
+ await maybeInjectDriverHostPort(ctx, ctx.log);
195
46
  yield* ExecPlugin.default.callback(ctx);
196
47
  });
197
48
  export default exec;
package/dist/index.js CHANGED
@@ -1,2 +1,3 @@
1
1
  export { default, app } from './app.js';
2
- export { exec, start, stop, ping, maybeInjectMaestroServer, maybeInjectScreenshotDir } from './exec.js';
2
+ export { exec, start, stop, ping } from './exec.js';
3
+ export { maybeInjectMaestroServer, maybeInjectScreenshotDir, maybeInjectDriverHostPort } from './maestro-inject.js';
@@ -0,0 +1,339 @@
1
+ import fs from 'fs';
2
+ import os from 'os';
3
+ import net from 'net';
4
+ import path from 'path';
5
+ import { spawnSync } from 'child_process';
6
+
7
+ // Locate the `test` subcommand in argv. Maestro accepts global parent
8
+ // flags before the subcommand, e.g.:
9
+ // maestro test flow.yaml
10
+ // maestro --udid <serial> test flow.yaml
11
+ // maestro --platform=android test flow.yaml
12
+ // maestro --verbose --no-ansi test flow.yaml
13
+ // We must find `test` by scanning rather than checking args[1] === 'test',
14
+ // or our injects silently no-op when the customer pins a device.
15
+ //
16
+ // Returns the index of the `test` literal, or -1 if not present. Skips
17
+ // over the value of known value-taking parent flags so a literal `test`
18
+ // supplied as a flag value (e.g. `--udid test`) isn't mistaken for the
19
+ // subcommand. Equals-form (`--flag=value`) doesn't need a skip — the
20
+ // value is part of the same argv token.
21
+ const MAESTRO_PARENT_VALUE_FLAGS = new Set(['--udid', '--device', '-p', '--platform', '--host', '--port', '--driver-host-port']);
22
+ function findTestSubcommandIdx(args) {
23
+ for (let i = 1; i < args.length; i++) {
24
+ const tok = args[i];
25
+ if (tok === 'test') return i;
26
+ if (typeof tok === 'string' && MAESTRO_PARENT_VALUE_FLAGS.has(tok)) {
27
+ i++; // skip the value of this flag
28
+ }
29
+ }
30
+ return -1;
31
+ }
32
+ function hasExistingPercyServerFlag(args, testIdx) {
33
+ for (let i = testIdx + 1; i < args.length - 1; i++) {
34
+ if (args[i] === '-e' && /^PERCY_SERVER=/.test(args[i + 1])) return true;
35
+ }
36
+ return false;
37
+ }
38
+
39
+ // Returns the customer-supplied value of `--test-output-dir` (whether the
40
+ // space-form `--test-output-dir <path>` or the equals-form
41
+ // `--test-output-dir=<path>` — both are valid picocli syntax), or null if
42
+ // absent. Returning the value (not just an index) lets the screenshot-dir
43
+ // helper align PERCY_MAESTRO_SCREENSHOT_DIR with the customer's value in
44
+ // either form without re-deriving it.
45
+ //
46
+ // An empty value (space-form value === '' or equals-form `--test-output-dir=`
47
+ // with nothing after the `=`) is treated as ABSENT — returning the empty
48
+ // string would tell the caller "customer set this" and bypass the
49
+ // auto-resolve fallback, leaving Maestro to default its output location
50
+ // while PERCY_MAESTRO_SCREENSHOT_DIR stays unset. That mismatch silently
51
+ // produces all-404 snapshots, so fall through to the auto-resolve path
52
+ // instead.
53
+ const TEST_OUTPUT_DIR_EQ_PREFIX = '--test-output-dir=';
54
+ function findTestOutputDirValue(args, testIdx) {
55
+ for (let i = testIdx + 1; i < args.length; i++) {
56
+ const tok = args[i];
57
+ if (tok === '--test-output-dir' && i + 1 < args.length) {
58
+ const val = args[i + 1];
59
+ if (typeof val === 'string' && val.length > 0) return val;
60
+ } else if (typeof tok === 'string' && tok.startsWith(TEST_OUTPUT_DIR_EQ_PREFIX)) {
61
+ const val = tok.slice(TEST_OUTPUT_DIR_EQ_PREFIX.length);
62
+ if (val.length > 0) return val;
63
+ }
64
+ }
65
+ return null;
66
+ }
67
+
68
+ // Maestro's GraalJS sandbox does NOT inherit the parent process's env,
69
+ // so `PERCY_SERVER_ADDRESS` exported by app:exec is invisible to the
70
+ // SDK. When wrapping `maestro test`, surface the CLI address through
71
+ // Maestro's only env channel — `-e KEY=VALUE` flags — so the SDK
72
+ // healthcheck can find the local CLI without the customer having to
73
+ // pair ports manually. No-op when the customer already supplied their
74
+ // own `-e PERCY_SERVER=...`.
75
+ //
76
+ // When percy?.address() is falsy (percy disabled, start failed), emit a
77
+ // WARN so the customer is not surprised by a silent zero-snapshot build.
78
+ // The customer-override skip case (their own `-e PERCY_SERVER=...` is in
79
+ // argv) does NOT warn — that's intentional flow control, not a problem.
80
+ export function maybeInjectMaestroServer(ctx, log) {
81
+ var _ctx$percy;
82
+ const args = ctx === null || ctx === void 0 ? void 0 : ctx.argv;
83
+ if (!Array.isArray(args) || args.length < 2) return;
84
+ if (path.basename(args[0]) !== 'maestro') return;
85
+ const testIdx = findTestSubcommandIdx(args);
86
+ if (testIdx < 0) return;
87
+ if (hasExistingPercyServerFlag(args, testIdx)) return;
88
+ const addr = (_ctx$percy = ctx.percy) === null || _ctx$percy === void 0 ? void 0 : _ctx$percy.address();
89
+ if (!addr) {
90
+ log === null || log === void 0 || log.warn('app:exec did not start the Percy CLI server (percy disabled or start ' + 'failed); -e PERCY_SERVER not injected into maestro test. Snapshots will ' + 'NOT be uploaded. Set PERCY_TOKEN and re-run, or check the percy log above.');
91
+ return;
92
+ }
93
+ // Inject after `test` so `-e KEY=VAL` is bound to the `test` subcommand
94
+ // (the only Maestro subcommand that accepts `-e`).
95
+ args.splice(testIdx + 1, 0, '-e', `PERCY_SERVER=${addr}`);
96
+ }
97
+
98
+ // Auto-resolve the Maestro screenshot output directory so customers don't
99
+ // have to pair `export PERCY_MAESTRO_SCREENSHOT_DIR=...` with a matching
100
+ // `--test-output-dir <same>` in their maestro test command.
101
+ //
102
+ // Resolution order:
103
+ // 1. Customer set BOTH process.env.PERCY_MAESTRO_SCREENSHOT_DIR and
104
+ // --test-output-dir in argv → trust them, do nothing.
105
+ // 2. Customer set PERCY_MAESTRO_SCREENSHOT_DIR only → use it, inject
106
+ // `--test-output-dir <env value>` into argv.
107
+ // 3. Customer set --test-output-dir only → use that value, mirror it
108
+ // into process.env.PERCY_MAESTRO_SCREENSHOT_DIR (so the SDK +
109
+ // CLI relay see the same path).
110
+ // 4. Neither set → pick `${process.cwd()}/.percy-out`. On any mkdir
111
+ // failure (read-only CWD, EACCES, EEXIST as a file), fall back to
112
+ // `${os.tmpdir()}/percy-maestro-<pid>` with a WARN log.
113
+ //
114
+ // The env-var update and argv splice always keep both sources of truth
115
+ // (SDK reads env var; Maestro reads the flag) aligned to the same path.
116
+ export function maybeInjectScreenshotDir(ctx, log) {
117
+ const args = ctx === null || ctx === void 0 ? void 0 : ctx.argv;
118
+ if (!Array.isArray(args) || args.length < 2) return;
119
+ if (path.basename(args[0]) !== 'maestro') return;
120
+ const testIdx = findTestSubcommandIdx(args);
121
+ if (testIdx < 0) return;
122
+ const envSet = !!process.env.PERCY_MAESTRO_SCREENSHOT_DIR;
123
+ const existingFlagValue = findTestOutputDirValue(args, testIdx);
124
+ const flagSet = existingFlagValue !== null;
125
+
126
+ // Fully customer-controlled — nothing to do.
127
+ if (envSet && flagSet) return;
128
+ let resolved;
129
+ if (envSet) {
130
+ resolved = process.env.PERCY_MAESTRO_SCREENSHOT_DIR;
131
+ } else if (flagSet) {
132
+ resolved = existingFlagValue;
133
+ } else {
134
+ const preferred = path.join(process.cwd(), '.percy-out');
135
+ try {
136
+ fs.mkdirSync(preferred, {
137
+ recursive: true
138
+ });
139
+ resolved = preferred;
140
+ } catch (err) {
141
+ const fallback = path.join(os.tmpdir(), `percy-maestro-${process.pid}`);
142
+ try {
143
+ fs.mkdirSync(fallback, {
144
+ recursive: true
145
+ });
146
+ } catch (_) {
147
+ // tmpdir mkdir failure is exceedingly rare; fall through and let
148
+ // downstream code surface a clearer error than this helper can.
149
+ }
150
+ resolved = fallback;
151
+ log === null || log === void 0 || log.warn(`Could not create ${preferred} (${err.code || err.message}); ` + `falling back to ${fallback}. Set PERCY_MAESTRO_SCREENSHOT_DIR to ` + 'pick a specific location.');
152
+ }
153
+ }
154
+ if (!envSet) process.env.PERCY_MAESTRO_SCREENSHOT_DIR = resolved;
155
+ // Inject right after `test` (the subcommand that owns `--test-output-dir`).
156
+ if (!flagSet) args.splice(testIdx + 1, 0, '--test-output-dir', resolved);
157
+ }
158
+
159
+ // ─── iOS driver-host-port prescription ──────────────────────────────────────
160
+ //
161
+ // Maestro 2.6.0 changed the iOS driver to bind an OS-assigned ephemeral port
162
+ // (`ServerSocket(0)`); Maestro ≤ 2.4.0 bound the deterministic `7001`. The
163
+ // @percy/core relay resolves the iOS `/viewHierarchy` port by reading
164
+ // `PERCY_IOS_DRIVER_HOST_PORT` first, then probing `127.0.0.1:7001`. On Maestro
165
+ // 2.6+ the probe finds nothing (ephemeral), so self-hosted iOS element regions
166
+ // (and device insets, whose relay path is env-only with no probe) degrade.
167
+ //
168
+ // Fix: pick a free port, pin Maestro's iOS driver to it via `--driver-host-port
169
+ // <port>`, and mirror it to `process.env.PERCY_IOS_DRIVER_HOST_PORT` so the
170
+ // relay (same Node process — env IS inherited there) targets it. This only fires
171
+ // on Maestro ≥ 2.6.0: the flag does not exist on 2.4.0 and passing it there is a
172
+ // fatal `Unknown option` (the reason commit 13616a87 was reverted). On ≤ 2.4.0
173
+ // the helper no-ops and the relay's 7001 probe serves those customers.
174
+ //
175
+ // Gated conservatively to iOS (`--platform=ios`/`-p ios`), non-sharded runs (a
176
+ // single pinned port collides across shards), and no-ops on any version-detection
177
+ // failure — degrading to the existing 7001-probe + warn-skip path.
178
+ const DRIVER_HOST_PORT_EQ_PREFIX = '--driver-host-port=';
179
+ const DRIVER_HOST_PORT_MIN_MAJOR = 2;
180
+ const DRIVER_HOST_PORT_MIN_MINOR = 6;
181
+ // Sharding flags — a single prescribed port cannot serve parallel shards
182
+ // (Maestro 2.6+ throws CliError on the second shard's bind).
183
+ const MAESTRO_SHARDING_FLAGS = new Set(['--shards', '--shard-split', '--shard-all', '-s']);
184
+ const MAESTRO_SHARDING_EQ_PREFIXES = ['--shards=', '--shard-split=', '--shard-all='];
185
+
186
+ /* istanbul ignore next — production default; tests inject deps.execMaestro. */
187
+ function defaultExecMaestro() {
188
+ return spawnSync('maestro', ['--version'], {
189
+ encoding: 'utf8'
190
+ });
191
+ }
192
+
193
+ /* istanbul ignore next — production default; tests inject deps.pickFreePort. */
194
+ function defaultPickFreePort() {
195
+ return new Promise((resolve, reject) => {
196
+ const srv = net.createServer();
197
+ srv.on('error', reject);
198
+ srv.listen(0, '127.0.0.1', () => {
199
+ const {
200
+ port
201
+ } = srv.address();
202
+ srv.close(() => resolve(port));
203
+ });
204
+ });
205
+ }
206
+
207
+ // Explicit iOS platform signal — `--platform=ios`, `--platform ios`, or `-p ios`.
208
+ // Case-sensitive (Maestro is). Scans the whole argv so a parent-position flag
209
+ // (the usual place) or an after-`test` one is both detected.
210
+ function isIosPlatform(args) {
211
+ for (let i = 1; i < args.length; i++) {
212
+ const tok = args[i];
213
+ if ((tok === '--platform' || tok === '-p') && args[i + 1] === 'ios') return true;
214
+ if (tok === '--platform=ios') return true;
215
+ }
216
+ return false;
217
+ }
218
+
219
+ // True when argv requests sharded/parallel execution (space- or equals-form).
220
+ // argv tokens are always strings (process argv / spliced literals).
221
+ function hasShardingFlag(args) {
222
+ for (let i = 1; i < args.length; i++) {
223
+ const tok = args[i];
224
+ if (MAESTRO_SHARDING_FLAGS.has(tok)) return true;
225
+ if (MAESTRO_SHARDING_EQ_PREFIXES.some(p => tok.startsWith(p))) return true;
226
+ }
227
+ return false;
228
+ }
229
+
230
+ // Returns the customer-supplied `--driver-host-port` value (space- or
231
+ // equals-form), or null if absent. An empty value is treated as ABSENT (mirrors
232
+ // findTestOutputDirValue) so `--driver-host-port=` falls through to our own pick.
233
+ function findDriverHostPortValue(args) {
234
+ for (let i = 1; i < args.length; i++) {
235
+ const tok = args[i];
236
+ if (tok === '--driver-host-port' && i + 1 < args.length) {
237
+ const val = args[i + 1];
238
+ if (typeof val === 'string' && val.length > 0) return val;
239
+ } else if (typeof tok === 'string' && tok.startsWith(DRIVER_HOST_PORT_EQ_PREFIX)) {
240
+ const val = tok.slice(DRIVER_HOST_PORT_EQ_PREFIX.length);
241
+ if (val.length > 0) return val;
242
+ }
243
+ }
244
+ return null;
245
+ }
246
+
247
+ // Validate a port string as an integer in 1..65535 (mirrors @percy/core's
248
+ // parseIosDriverHostPort). Returns the number, or null when absent/invalid so a
249
+ // stale/garbage PERCY_IOS_DRIVER_HOST_PORT export is treated as unset.
250
+ function validDriverHostPort(raw) {
251
+ if (typeof raw !== 'string') return null;
252
+ const trimmed = raw.trim();
253
+ if (!/^\d+$/.test(trimmed)) return null;
254
+ const n = Number(trimmed);
255
+ return n >= 1 && n <= 65535 ? n : null;
256
+ }
257
+
258
+ // Detect the installed Maestro MAJOR.MINOR via `maestro --version`. Returns
259
+ // { major, minor } or null on any spawn/parse failure (helper then no-ops).
260
+ // The flag is `hidden` in Maestro's CLI, so version — not `--help` — is the
261
+ // only reliable capability signal.
262
+ function detectMaestroVersion(execMaestro, log) {
263
+ let result;
264
+ try {
265
+ result = execMaestro();
266
+ } catch (err) {
267
+ log === null || log === void 0 || log.debug(`maestro --version failed (${err.code || err.message}); skipping --driver-host-port injection`);
268
+ return null;
269
+ }
270
+ if (!result || result.error || result.status !== 0) {
271
+ log === null || log === void 0 || log.debug('maestro --version returned no usable output; skipping --driver-host-port injection');
272
+ return null;
273
+ }
274
+ const out = `${result.stdout || ''}${result.stderr || ''}`;
275
+ const m = out.match(/(\d+)\.(\d+)/);
276
+ if (!m) {
277
+ log === null || log === void 0 || log.debug('could not parse maestro version; skipping --driver-host-port injection');
278
+ return null;
279
+ }
280
+ return {
281
+ major: Number(m[1]),
282
+ minor: Number(m[2])
283
+ };
284
+ }
285
+
286
+ // Prescribe the iOS Maestro driver port on Maestro ≥ 2.6.0 so the @percy/core
287
+ // relay can reach `/viewHierarchy` deterministically (regions + insets) without
288
+ // customer-side `PERCY_IOS_DRIVER_HOST_PORT` configuration. No-ops on every path
289
+ // that would be unsafe or unnecessary (non-maestro, non-`test`, sharded,
290
+ // non-iOS, customer already pinned, Maestro < 2.6, detection failure). Async
291
+ // because picking a free port (`net`) is inherently async.
292
+ export async function maybeInjectDriverHostPort(ctx, log, deps = {}) {
293
+ const args = ctx === null || ctx === void 0 ? void 0 : ctx.argv;
294
+ if (!Array.isArray(args) || args.length < 2) return;
295
+ if (path.basename(args[0]) !== 'maestro') return;
296
+ const testIdx = findTestSubcommandIdx(args);
297
+ if (testIdx < 0) return;
298
+
299
+ // Sharded runs can't share one pinned port — leave them to the relay probe.
300
+ if (hasShardingFlag(args)) return;
301
+ // Conservative: the flag is an iOS-driver concern; require an explicit signal.
302
+ if (!isIosPlatform(args)) return;
303
+ // Customer already pinned the port — stay fully passive (argv + env untouched).
304
+ if (findDriverHostPortValue(args) !== null) return;
305
+
306
+ // Capability gate: the flag only exists on Maestro ≥ 2.6.0. Injecting it on
307
+ // 2.4.0 is a fatal `Unknown option`, so detect first and bail otherwise.
308
+ /* istanbul ignore next -- production DI default; unit tests always inject deps.execMaestro. */
309
+ const execMaestro = deps.execMaestro || defaultExecMaestro;
310
+ const version = detectMaestroVersion(execMaestro, log);
311
+ if (!version) return;
312
+ if (version.major < DRIVER_HOST_PORT_MIN_MAJOR || version.major === DRIVER_HOST_PORT_MIN_MAJOR && version.minor < DRIVER_HOST_PORT_MIN_MINOR) {
313
+ log === null || log === void 0 || log.debug(`Maestro ${version.major}.${version.minor} predates --driver-host-port ` + '(>= 2.6.0); relying on the 127.0.0.1:7001 relay probe');
314
+ return;
315
+ }
316
+
317
+ // A valid customer-exported port wins its value; otherwise pick a free one.
318
+ // Either way we splice the argv flag (so Maestro binds it) and mirror env (so
319
+ // the relay targets it). Stale/invalid env values fall through to a fresh pick.
320
+ /* istanbul ignore next -- production DI default; unit tests always inject deps.pickFreePort. */
321
+ const pickFreePort = deps.pickFreePort || defaultPickFreePort;
322
+ const envPort = validDriverHostPort(process.env.PERCY_IOS_DRIVER_HOST_PORT);
323
+ let port = envPort;
324
+ if (port === null) {
325
+ // Picking a free port can reject (OS resource exhaustion on listen(0), etc.).
326
+ // Degrade gracefully like every other failure path here — no-op and let the
327
+ // relay's 127.0.0.1:7001 probe handle it — rather than crashing app:exec with
328
+ // an unattributed rejection AND leaving Maestro 2.6+ with no port at all.
329
+ try {
330
+ port = await pickFreePort();
331
+ } catch (err) {
332
+ log === null || log === void 0 || log.warn(`[percy] could not reserve a free port for --driver-host-port (${err.message}); ` + 'relying on the 127.0.0.1:7001 relay probe');
333
+ return;
334
+ }
335
+ }
336
+ args.splice(testIdx + 1, 0, '--driver-host-port', String(port));
337
+ process.env.PERCY_IOS_DRIVER_HOST_PORT = String(port);
338
+ log === null || log === void 0 || log.info(`[percy] iOS Maestro driver port prescribed → ${port} (Maestro ${version.major}.${version.minor})`);
339
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@percy/cli-app",
3
- "version": "1.32.4",
3
+ "version": "1.32.5-beta.0",
4
4
  "license": "MIT",
5
5
  "repository": {
6
6
  "type": "git",
@@ -9,7 +9,7 @@
9
9
  },
10
10
  "publishConfig": {
11
11
  "access": "public",
12
- "tag": "latest"
12
+ "tag": "beta"
13
13
  },
14
14
  "engines": {
15
15
  "node": ">=14"
@@ -33,8 +33,8 @@
33
33
  ]
34
34
  },
35
35
  "dependencies": {
36
- "@percy/cli-command": "1.32.4",
37
- "@percy/cli-exec": "1.32.4"
36
+ "@percy/cli-command": "1.32.5-beta.0",
37
+ "@percy/cli-exec": "1.32.5-beta.0"
38
38
  },
39
- "gitHead": "3cc47184f972f991e35b5cc58d3035ecca6cf221"
39
+ "gitHead": "768c93a69060d3abe8dd4db57768c0970d2a9b79"
40
40
  }