@testver/testver 1.2.5 → 1.3.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.
@@ -1,666 +1,687 @@
1
- /**
2
- * Testver mobile cloud-bridge bootstrap (Node `--require` hook).
3
- *
4
- * Loaded via `NODE_OPTIONS=--require=<absolute-path>/bootstrap.cjs`
5
- * BEFORE the user's test code runs. Monkey-patches the `webdriverio`
6
- * package's `remote()` function to override:
7
- * - hostname / port / protocol / path → the Appium cloud hub
8
- * - user / key → provider credentials
9
- * - capabilities → device + app + provider opts
10
- *
11
- * Reads everything from TESTVER_* and APPIUM_HUB_* env vars Testver injects.
12
- * No-op when those env vars aren't set (so non-Testver invocations
13
- * keep working exactly as before).
14
- *
15
- * Why this exists: mocha-based mobile projects don't load wdio.conf —
16
- * they `require('webdriverio')` and call `remote({ hostname: 'localhost'
17
- * })` directly. Without this bootstrap, env-var injection alone can't
18
- * override those hardcoded values. The bootstrap intercepts at the
19
- * package boundary so user code stays untouched.
20
- *
21
- * Strategy: install a require hook (via Module.prototype.require)
22
- * that wraps `webdriverio` and `wdio-webdriver` on first import. Works
23
- * for CommonJS test runners (mocha being the prime target). ESM-only
24
- * projects fall through harmlessly — they typically already use
25
- * wdio.conf so the overlay path handles them.
26
- */
27
-
28
- 'use strict';
29
-
30
- // Skip when Testver env vars aren't present — safety net for users
31
- // who accidentally inherit NODE_OPTIONS in unrelated processes.
32
- if (!process.env.TESTVER_PROVIDER && !process.env.APPIUM_HUB_HOST) {
33
- return;
34
- }
35
-
36
- const Module = require('module');
37
- const origRequire = Module.prototype.require;
38
-
39
- /**
40
- * Standard W3C WebDriver capabilities — these stay unprefixed.
41
- * Any other key without a `vendor:` prefix is treated as a legacy
42
- * Appium cap and gets auto-prefixed with `appium:` below. List from
43
- * https://w3c.github.io/webdriver/#capabilities (May 2026).
44
- */
45
- const W3C_STANDARD_CAPS = new Set([
46
- 'browserName',
47
- 'browserVersion',
48
- 'platformName',
49
- 'acceptInsecureCerts',
50
- 'pageLoadStrategy',
51
- 'proxy',
52
- 'setWindowRect',
53
- 'timeouts',
54
- 'strictFileInteractability',
55
- 'unhandledPromptBehavior',
56
- 'webSocketUrl',
57
- 'fedcm:accounts',
58
- ]);
59
-
60
- /**
61
- * Auto-prefix unprefixed Appium-specific keys with `appium:` so a
62
- * W3C-compliant server (BrowserStack, Sauce, Appium 2.x) accepts them.
63
- * Anything that's already `vendor:foo` (contains a colon) is left alone.
64
- * Standard W3C caps stay unprefixed. Mutates `caps` in place.
65
- */
66
- function appiumPrefixCaps(caps) {
67
- for (const k of Object.keys(caps)) {
68
- if (k.includes(':')) continue; // already vendor-prefixed
69
- if (W3C_STANDARD_CAPS.has(k)) continue; // standard W3C cap
70
- // Legacy Appium key → re-key under `appium:` namespace.
71
- const v = caps[k];
72
- delete caps[k];
73
- caps['appium:' + k] = v;
74
- }
75
- }
76
-
77
- /**
78
- * Normalise a capabilities object to the flat shape webdriverio v8+
79
- * accepts at the user-facing API. Some test code (esp. ones authored
80
- * against the raw W3C spec or older WebDriver clients) hands wdio a
81
- * `{ alwaysMatch: {...}, firstMatch: [...] }` payload, which wdio
82
- * rejects with:
83
- * Invalid or unsupported WebDriver capabilities found
84
- * ("alwaysMatch", "firstMatch").
85
- * We unwrap alwaysMatch into the flat shape and discard firstMatch
86
- * (Testver overrides supply everything that matters for cloud runs).
87
- */
88
- function flattenCaps(caps) {
89
- if (!caps || typeof caps !== 'object') return {};
90
- if (Array.isArray(caps)) return {};
91
- if ('alwaysMatch' in caps || 'firstMatch' in caps) {
92
- const flat = Object.assign({}, caps.alwaysMatch || {});
93
- // Preserve any non-W3C-internal keys the user attached alongside.
94
- for (const k of Object.keys(caps)) {
95
- if (k !== 'alwaysMatch' && k !== 'firstMatch') flat[k] = caps[k];
96
- }
97
- return flat;
98
- }
99
- return caps;
100
- }
101
-
102
- /**
103
- * Local Devices (Settings → Local Devices): capabilities the project doesn't
104
- * set itself (TESTVER_LOCAL_CAPS_DEFAULTS — WebDriverAgent port and signing),
105
- * then Testver's own over the project's (TESTVER_LOCAL_CAPS — app launch mode).
106
- */
107
- function applyLocalCaps(caps) {
108
- let defaults = {};
109
- let overrides = {};
110
- try { defaults = process.env.TESTVER_LOCAL_CAPS_DEFAULTS ? JSON.parse(process.env.TESTVER_LOCAL_CAPS_DEFAULTS) : {}; } catch (e) { defaults = {}; }
111
- try { overrides = process.env.TESTVER_LOCAL_CAPS ? JSON.parse(process.env.TESTVER_LOCAL_CAPS) : {}; } catch (e) { overrides = {}; }
112
- for (const k of Object.keys(defaults)) {
113
- if (caps[k] === undefined && caps[k.replace(/^appium:/, '')] === undefined) caps[k] = defaults[k];
114
- }
115
- for (const k of Object.keys(overrides)) {
116
- delete caps[k.replace(/^appium:/, '')];
117
- caps[k] = overrides[k];
118
- }
119
- }
120
-
121
- /**
122
- * The key the capabilities already use for a vendor block, matched without
123
- * regard to case (`LT:Options` / `lt:options`), else `key` — Testver merges
124
- * into the project's own block rather than adding a second one.
125
- */
126
- function vendorKeyIn(caps, key) {
127
- if (!key || !caps || typeof caps !== 'object' || Object.prototype.hasOwnProperty.call(caps, key)) return key;
128
- const lower = key.toLowerCase();
129
- return Object.keys(caps).find((k) => k.toLowerCase() === lower) || key;
130
- }
131
-
132
- /** Apply Testver cloud overrides to a wdio `remote()` options object. */
133
- function applyTestverOverrides(opts) {
134
- opts = opts || {};
135
- // Connection details
136
- if (process.env.APPIUM_HUB_HOST) opts.hostname = process.env.APPIUM_HUB_HOST;
137
- if (process.env.APPIUM_HUB_PORT) opts.port = Number(process.env.APPIUM_HUB_PORT);
138
- if (process.env.APPIUM_HUB_PROTOCOL) opts.protocol = process.env.APPIUM_HUB_PROTOCOL;
139
- if (process.env.APPIUM_HUB_PATH) opts.path = process.env.APPIUM_HUB_PATH;
140
- if (process.env.APPIUM_HUB_USER) opts.user = process.env.APPIUM_HUB_USER;
141
- if (process.env.APPIUM_HUB_KEY) opts.key = process.env.APPIUM_HUB_KEY;
142
-
143
- // Local-Appium has NO credentials. The user's test code may have set
144
- // `user`/`key` from a BrowserStack-shaped .env — if we leave them on
145
- // the options, WebdriverIO's detectBackend() sees user+key present
146
- // with hostname 127.0.0.1 (not a known cloud) and throws:
147
- // 'A "user" or "key" was provided but could not be connected to a
148
- // known cloud service'.
149
- // Strip them so wdio treats this as a plain local Appium endpoint.
150
- if (process.env.TESTVER_PROVIDER === 'local-appium') {
151
- delete opts.user;
152
- delete opts.key;
153
- }
154
-
155
- // Force the flat capabilities shape — strips out any alwaysMatch /
156
- // firstMatch the user's code might have built manually. wdio v8+
157
- // builds the W3C envelope internally; passing one in errors.
158
- const caps = flattenCaps(opts.capabilities);
159
- opts.capabilities = caps;
160
-
161
- // Auto-prefix legacy unprefixed Appium keys (deviceName, appPackage,
162
- // automationName, …) with `appium:` so W3C-compliant servers accept
163
- // them. Caps that are already vendor-prefixed (`bstack:options`,
164
- // `appium:foo`) and standard W3C caps (`platformName`) stay as-is.
165
- appiumPrefixCaps(caps);
166
-
167
- if (process.env.TESTVER_PLATFORM_NAME) caps.platformName = process.env.TESTVER_PLATFORM_NAME;
168
- if (process.env.TESTVER_DEVICE_NAME) caps['appium:deviceName'] = process.env.TESTVER_DEVICE_NAME;
169
- if (process.env.TESTVER_PLATFORM_VERSION) caps['appium:platformVersion'] = process.env.TESTVER_PLATFORM_VERSION;
170
- // The device: a local one by its serial / udid (Appium picks the device by
171
- // appium:udid, never by deviceName); on a vendor's cloud a local udid / AVD
172
- // means nothing.
173
- if (process.env.TESTVER_PROVIDER === 'local-appium') {
174
- if (process.env.TESTVER_DEVICE_UDID) {
175
- caps['appium:udid'] = process.env.TESTVER_DEVICE_UDID;
176
- delete caps['appium:avd'];
177
- }
178
- applyLocalCaps(caps);
179
- } else {
180
- delete caps['appium:udid'];
181
- delete caps['appium:avd'];
182
- }
183
- if (process.env.TESTVER_APP_URL) {
184
- caps['appium:app'] = process.env.TESTVER_APP_URL;
185
- // The user's test code may hard-code app-identifier caps that
186
- // belong to a DIFFERENT build than what Testver just uploaded
187
- // (e.g., appPackage / appActivity / bundleId). Cloud providers
188
- // (BrowserStack, Sauce, LambdaTest) auto-detect these from the
189
- // uploaded APK/IPA metadata when omitted, so dropping them here
190
- // makes the run robust against mismatches like:
191
- // [BROWSERSTACK_INVALID_APP_ACTIVITY] Activity name "..." used
192
- // to start the app doesn't exist. Supported values: "c".
193
- // (the project's package / bundle id is kept aside for the app reset
194
- // on a reused session)
195
- projectAppId = caps['appium:appPackage'] || caps['appium:bundleId'] || projectAppId;
196
- delete caps['appium:appPackage'];
197
- delete caps['appium:appActivity'];
198
- delete caps['appium:appWaitActivity'];
199
- delete caps['appium:appWaitPackage'];
200
- delete caps['appium:bundleId']; // iOS counterpart
201
- delete caps['appium:appWaitForLaunch'];
202
- }
203
-
204
- // Sensible automation name default — required by cloud providers.
205
- // Only set if the user didn't already pick one (e.g. Espresso, XCUITest).
206
- if (!caps['appium:automationName']) {
207
- caps['appium:automationName'] = caps.platformName === 'iOS' ? 'XCUITest' : 'UiAutomator2';
208
- }
209
-
210
- // Provider-specific options block.
211
- //
212
- // CRITICAL: BrowserStack / Sauce Labs / LambdaTest route to a
213
- // specific cloud device by reading the device name from THEIR own
214
- // options block (e.g. `bstack:options.deviceName`), NOT from
215
- // `appium:deviceName`. The latter is the *Appium server's* internal
216
- // device label, which on cloud hubs is often the same string but
217
- // can also be the cloud's internal udid — providers reject device
218
- // selection when only `appium:deviceName` is set:
219
- // [BROWSERSTACK_NO_DEVICE_SPECIFIED] The 'device' capability is
220
- // missing in your test script.
221
- //
222
- // So we ALWAYS mirror the device + OS version into the
223
- // provider-options block. The source of truth is whichever was
224
- // already populated on caps — either by the user's test code (caps
225
- // built manually) or by Testver overrides above (caps['appium:*']
226
- // populated from TESTVER_* env vars). Order of preference:
227
- // 1. Testver env var (explicit selection by UI / Runner)
228
- // 2. User-provided `appium:deviceName` from their caps
229
- // 3. Anything the user already put in `bstack:options.deviceName`
230
- // The vendor block Testver built for this run (TESTVER_VENDOR_OPTIONS):
231
- // each vendor's own field names, the tunnel, the picked device. Names and
232
- // tunnel: the project's own values win; the picked device wins over the
233
- // project's. Without it (an older run plan) the device and OS version are
234
- // still mirrored into the vendor's block.
235
- let vendor = null;
236
- try { vendor = process.env.TESTVER_VENDOR_OPTIONS ? JSON.parse(process.env.TESTVER_VENDOR_OPTIONS) : null; } catch (e) { vendor = null; }
237
- if (vendor && vendor.key) {
238
- // the project's own spelling of the block (`LT:Options` / `lt:options`)
239
- const key = vendorKeyIn(caps, vendor.key);
240
- caps[key] = Object.assign({}, vendor.options || {}, caps[key] || {}, vendor.overrides || {});
241
- } else {
242
- const key = vendorKeyIn(caps, { browserstack: 'bstack:options', saucelabs: 'sauce:options', lambdatest: 'lt:options' }[process.env.TESTVER_PROVIDER || ''] || '');
243
- const device = process.env.TESTVER_DEVICE_NAME || caps['appium:deviceName'];
244
- if (key && device) {
245
- const existing = caps[key] || {};
246
- caps[key] = Object.assign({}, existing, existing.deviceName ? {} : { deviceName: device });
247
- }
248
- }
249
- return opts;
250
- }
251
-
252
- /**
253
- * Wrap the `remote` export on a webdriverio module. Idempotent.
254
- *
255
- * Two behaviours, selected at call time by env state:
256
- * - TESTVER_REUSE_SESSION_ID present → call wdio.attach() to ATTACH
257
- * to the existing AI Assistant / AI Record live session. Saves the
258
- * 30-60s device-boot cost + one cloud minute per claim.
259
- * - Otherwise → call the original wdio.remote() with cloud-redirected
260
- * connection + Testver-normalized capabilities (fresh session).
261
- */
262
- /**
263
- * When the test code is running on a SHARED reused session, the
264
- * test's teardown call to `driver.quit()` / `driver.deleteSession()`
265
- * would terminate the entire BrowserStack session — killing the
266
- * live session AI Assistant is still using. We can't have that.
267
- *
268
- * Wrap the attached browser so those teardown methods become no-ops
269
- * (but still return a resolved promise so existing `await driver.quit()`
270
- * code keeps working). Other operations on the browser remain
271
- * untouched. Idempotent — only wraps once per browser instance.
272
- *
273
- * For non-reuse runs (fresh `remote()`), this wrapper is NOT applied:
274
- * `quit()` works normally and cleanly tears down the freshly-created
275
- * cloud session as the test author expects.
276
- */
277
- /**
278
- * Reset the app to a fresh launch state on an attached session.
279
- *
280
- * When AI Assistant has been driving the device, the app is sitting on
281
- * whatever screen the user navigated to. A test attached to this
282
- * session expects a clean launch (welcome screen, login screen, etc.).
283
- * Without resetting, every test fails on its first assertion because
284
- * the screen it expects to see isn't there.
285
- *
286
- * Strategy:
287
- * 1. terminateApp(appId) → kills the running app process
288
- * 2. activateApp(appId) → relaunches it (same as a cold-launch from
289
- * the user's perspective)
290
- *
291
- * The cloud SESSION stays alive across both calls — only the app
292
- * process is recycled. ~1-2 seconds total. Cheaper than booting a
293
- * fresh device (30-60s).
294
- *
295
- * App identifier sources, in order:
296
- * - caps['appium:appPackage'] (Android, set by user test code)
297
- * - caps['appium:bundleId'] (iOS, set by user test code)
298
- * - TESTVER_APP_PACKAGE env var (override hook for future use)
299
- * - TESTVER_APP_BUNDLE_ID env var
300
- *
301
- * Disable: set TESTVER_SKIP_APP_RESET=1 in the run env.
302
- */
303
- /** The project's own app package / bundle id, before an uploaded app replaced it in the caps. */
304
- let projectAppId;
305
-
306
- async function resetAppOnAttach(browser, caps) {
307
- // Idempotency guard — if the browser already went through a reset
308
- // (e.g. wdio.remote() delegated to wdio.attach() which is also
309
- // wrapped), don't reset twice.
310
- if (browser.__testverResetDone) return;
311
- try { Object.defineProperty(browser, '__testverResetDone', { value: true, enumerable: false }); }
312
- catch (_) { browser.__testverResetDone = true; }
313
-
314
- if (process.env.TESTVER_SKIP_APP_RESET === '1') {
315
- // eslint-disable-next-line no-console
316
- console.log('[testver-bootstrap] App reset skipped (TESTVER_SKIP_APP_RESET=1)');
317
- return;
318
- }
319
- const appId = (caps && (caps['appium:appPackage'] || caps['appium:bundleId']))
320
- || projectAppId
321
- || process.env.TESTVER_APP_PACKAGE
322
- || process.env.TESTVER_APP_BUNDLE_ID;
323
- if (!appId) {
324
- // eslint-disable-next-line no-console
325
- console.log('[testver-bootstrap] App reset on attach: no appPackage/bundleId in caps — skipping ' +
326
- '(test may see stale UI state from prior AI Assistant interactions). ' +
327
- 'Set caps.appPackage (Android) or caps.bundleId (iOS) in your test code, ' +
328
- 'or export TESTVER_APP_PACKAGE / TESTVER_APP_BUNDLE_ID to enable auto-reset.');
329
- return;
330
- }
331
-
332
- // Platform detection — drives whether we issue `mobile: clearApp`
333
- // (Android only — wipes SharedPreferences + cache + databases so
334
- // the app launches as if freshly installed, including onboarding
335
- // screens). iOS doesn't have a direct equivalent at the WebDriver
336
- // protocol level; terminate + activate is the best we can do.
337
- const platform = String((caps && caps.platformName) || process.env.TESTVER_PLATFORM_NAME || '').toLowerCase();
338
- const isAndroid = platform === 'android';
339
- const skipClear = process.env.TESTVER_SKIP_APP_CLEAR === '1';
340
-
341
- // eslint-disable-next-line no-console
342
- console.log('[testver-bootstrap] Resetting app "' + appId + '" on attached session ' +
343
- '(' + (isAndroid && !skipClear ? 'clearApp + ' : '') + 'terminate + activate) ' +
344
- 'so test starts from a fresh launch...');
345
- try {
346
- // Step 1 (Android only): clear app DATA so onboarding state, login
347
- // state, cached pages, etc. all reset. Without this, terminate +
348
- // activate just kills + restarts the process — the user's previous
349
- // "completed onboarding" flag persists and the welcome screen
350
- // never appears. Skippable via TESTVER_SKIP_APP_CLEAR=1 when the
351
- // test expects to inherit state from prior interactions.
352
- if (isAndroid && !skipClear) {
353
- try {
354
- await browser.execute('mobile: clearApp', { appId });
355
- // eslint-disable-next-line no-console
356
- console.log('[testver-bootstrap] App data cleared (onboarding + cached state reset).');
357
- } catch (err) {
358
- // Some Appium-server / cloud-driver configs don't expose
359
- // clearApp — fall back to terminate + activate alone. Most
360
- // tests still work; the onboarding flag is the edge case.
361
- // eslint-disable-next-line no-console
362
- console.log('[testver-bootstrap] clearApp not available: ' + (err && err.message) +
363
- ' — proceeding with terminate+activate (onboarding state may persist).');
364
- }
365
- }
366
- // Step 2: terminate (if running). Failure is fine — activate
367
- // launches anyway.
368
- const terminate = async () => {
369
- if (typeof browser.terminateApp === 'function') return browser.terminateApp(appId);
370
- return browser.execute('mobile: terminateApp', { appId });
371
- };
372
- try {
373
- await terminate();
374
- } catch (err) {
375
- // eslint-disable-next-line no-console
376
- console.log('[testver-bootstrap] terminateApp non-fatal: ' + (err && err.message));
377
- }
378
- // Step 3: cold-launch the app.
379
- const activate = async () => {
380
- if (typeof browser.activateApp === 'function') return browser.activateApp(appId);
381
- return browser.execute('mobile: activateApp', { appId });
382
- };
383
- await activate();
384
- // eslint-disable-next-line no-console
385
- console.log('[testver-bootstrap] App reset complete — test starts from fresh launch state');
386
- } catch (err) {
387
- // eslint-disable-next-line no-console
388
- console.log('[testver-bootstrap] App reset failed: ' + (err && err.message) +
389
- ' — continuing anyway. If the test fails on the first assertion, set TESTVER_SKIP_APP_RESET=1 ' +
390
- 'and reset the app manually in your test setup.');
391
- }
392
- }
393
-
394
- function suppressSessionTeardown(browser) {
395
- if (!browser || browser.__testverTeardownSuppressed) return browser;
396
- const noopMethodNames = ['deleteSession', 'quit', 'endSession', 'end'];
397
- const noopFor = (name) => function suppressedQuit() {
398
- // eslint-disable-next-line no-console
399
- console.log('[testver-bootstrap] ' + name + '() suppressed — session is SHARED with AI Assistant ' +
400
- '(use driver.terminateApp()/activateApp() to reset state instead).');
401
- return Promise.resolve();
402
- };
403
-
404
- // Strategy A: Object.defineProperty (works when the property is
405
- // non-writable but still configurable — wdio v8.27+ marks
406
- // deleteSession non-writable via getters but leaves it configurable).
407
- let allOverridden = true;
408
- for (const m of noopMethodNames) {
409
- try {
410
- Object.defineProperty(browser, m, {
411
- value: noopFor(m),
412
- writable: true,
413
- configurable: true,
414
- enumerable: false,
415
- });
416
- } catch (err) {
417
- allOverridden = false;
418
- // eslint-disable-next-line no-console
419
- console.warn('[testver-bootstrap] defineProperty(' + m + ') failed: ' + (err && err.message));
420
- }
421
- }
422
-
423
- if (allOverridden) {
424
- try { Object.defineProperty(browser, '__testverTeardownSuppressed', { value: true, enumerable: false }); }
425
- catch (_) { /* swallow — flag is best-effort */ }
426
- return browser;
427
- }
428
-
429
- // Strategy B (fallback): wrap in a Proxy that intercepts the four
430
- // teardown methods. We bind every OTHER method to the original
431
- // target so wdio internals that rely on `this` keep working.
432
- // Proxy never breaks for read-only props — gets always return the
433
- // value we choose.
434
- const noopSet = new Set(noopMethodNames);
435
- const proxied = new Proxy(browser, {
436
- get(target, prop, receiver) {
437
- if (typeof prop === 'string' && noopSet.has(prop)) {
438
- return noopFor(prop);
439
- }
440
- const v = Reflect.get(target, prop, receiver);
441
- // Methods need their `this` rebound to the real browser so
442
- // wdio's command pipeline (which inspects `this.options`,
443
- // `this.capabilities`, etc.) still sees a valid context.
444
- return typeof v === 'function' ? v.bind(target) : v;
445
- },
446
- set(target, prop, value) {
447
- return Reflect.set(target, prop, value);
448
- },
449
- });
450
- try { Object.defineProperty(proxied, '__testverTeardownSuppressed', { value: true, enumerable: false }); }
451
- catch (_) { /* swallow */ }
452
- return proxied;
453
- }
454
-
455
- /**
456
- * POST the cloud sessionId back to Testver so the Runner's live-preview
457
- * panel can render screenshots from this very session. Fire-and-forget;
458
- * a failure here just means the live panel stays empty — the test still
459
- * runs unaffected. We pass the FULL hub URL (with credentials) so the
460
- * server can authenticate direct screenshot calls without needing to
461
- * re-resolve creds from disk.
462
- */
463
- function reportExternalSession(browser, patched) {
464
- const reportUrl = process.env.TESTVER_REPORTBACK_URL;
465
- const clientId = process.env.TESTVER_CLIENT_ID;
466
- if (!reportUrl || !clientId || !browser || !browser.sessionId) return;
467
-
468
- // Reconstruct the hub URL with embedded credentials — Testver's
469
- // register endpoint parses this with new URL(...) to extract host/
470
- // port/path/user/key without separate fields.
471
- const proto = patched.protocol || 'https';
472
- const host = patched.hostname;
473
- const port = patched.port || (proto === 'https' ? 443 : 80);
474
- const path = patched.path || '/wd/hub';
475
- const user = encodeURIComponent(patched.user || '');
476
- const key = encodeURIComponent(patched.key || '');
477
- const hubUrl = `${proto}://${user}:${key}@${host}:${port}${path}`;
478
- const body = JSON.stringify({
479
- clientId,
480
- sessionId: browser.sessionId,
481
- hubUrl,
482
- deviceName: patched.capabilities && patched.capabilities['appium:deviceName'],
483
- platformName: patched.capabilities && patched.capabilities.platformName,
484
- providerId: process.env.TESTVER_PROVIDER,
485
- // the run that opened it (several runs of one tab side by side)
486
- runId: process.env.TESTVER_RUN_ID,
487
- });
488
- const endpoint = reportUrl.replace(/\/$/, '') + '/api/mobile/session/register-external';
489
- // Node 18+ has global fetch — we target Node 20 in the parent app.
490
- if (typeof fetch !== 'function') {
491
- // eslint-disable-next-line no-console
492
- console.log('[testver-bootstrap] No global fetch available — live-preview reportback skipped.');
493
- return;
494
- }
495
- fetch(endpoint, {
496
- method: 'POST',
497
- headers: { 'Content-Type': 'application/json' },
498
- body,
499
- }).then(() => {
500
- // eslint-disable-next-line no-console
501
- console.log('[testver-bootstrap] Reported sessionId ' + browser.sessionId.slice(0, 12) + '… to Testver for live preview');
502
- }).catch((err) => {
503
- // eslint-disable-next-line no-console
504
- console.log('[testver-bootstrap] Reportback failed (live preview may be empty): ' + (err && err.message));
505
- });
506
- }
507
-
508
- /**
509
- * Tell Testver this external session is over so it stops trying to
510
- * poll its screenshots. Fire-and-forget; the registry has a TTL
511
- * fallback if this call drops.
512
- */
513
- function unreportExternalSession() {
514
- const reportUrl = process.env.TESTVER_REPORTBACK_URL;
515
- const clientId = process.env.TESTVER_CLIENT_ID;
516
- if (!reportUrl || !clientId || typeof fetch !== 'function') return;
517
- const endpoint = reportUrl.replace(/\/$/, '') + '/api/mobile/session/unregister-external';
518
- fetch(endpoint, {
519
- method: 'POST',
520
- headers: { 'Content-Type': 'application/json' },
521
- body: JSON.stringify({ clientId }),
522
- }).catch(() => { /* best-effort */ });
523
- }
524
-
525
- // Wire up process exit hooks so the registry doesn't keep a stale
526
- // entry after the test process dies. The TTL on the server side
527
- // catches anything we miss here.
528
- process.on('exit', unreportExternalSession);
529
- process.on('SIGINT', () => { unreportExternalSession(); process.exit(130); });
530
- process.on('SIGTERM', () => { unreportExternalSession(); process.exit(143); });
531
-
532
- function wrapWdioModule(mod) {
533
- if (!mod || mod.__testverWrapped) return mod;
534
-
535
- // Capture the ORIGINAL attach() reference BEFORE wrapping — we use
536
- // this directly inside the remote() wrapper so we don't accidentally
537
- // double-invoke our own attach wrapper (which would suppress +
538
- // reset twice). After we install our wrapped attach below, all
539
- // EXTERNAL callers (user test code calling wdio.attach() directly)
540
- // hit the wrapped version; the remote() wrapper bypasses it.
541
- const origAttach = typeof mod.attach === 'function' ? mod.attach : null;
542
- const origRemote = typeof mod.remote === 'function' ? mod.remote : null;
543
-
544
- if (origRemote) {
545
- mod.remote = async function testverWrappedRemote(opts) {
546
- const reuseId = process.env.TESTVER_REUSE_SESSION_ID;
547
- // Always normalise/apply overrides — even attach() needs the
548
- // hub host/port/user/key + flattened caps so wdio knows where
549
- // to send subsequent commands.
550
- const patched = applyTestverOverrides(opts);
551
-
552
- if (reuseId && origAttach) {
553
- // eslint-disable-next-line no-console
554
- console.log('[testver-bootstrap] Attaching to live session ' + reuseId.slice(0, 12) + '… on ' +
555
- (patched.hostname || '?') + ' (skips device boot)');
556
- // webdriverio's attach() reads its connection details from
557
- // `attachOptions.options` via detectBackend(), NOT from the
558
- // top-level object. detectBackend(undefined) returns
559
- // { hostname: undefined, port: undefined, … } which then
560
- // OVERRIDES any flat top-level values we pass — producing the
561
- // malformed `http://127.0.0.1:undefined/…` URL. So we MUST nest
562
- // the connection params under `options` (and mirror them at the
563
- // top level for older wdio versions that read both).
564
- const connOpts = {
565
- hostname: patched.hostname,
566
- port: patched.port,
567
- protocol: patched.protocol,
568
- path: patched.path,
569
- capabilities: patched.capabilities,
570
- };
571
- const attachOpts = Object.assign({}, patched, {
572
- sessionId: reuseId,
573
- capabilities: patched.capabilities,
574
- requestedCapabilities: patched.capabilities,
575
- options: connOpts,
576
- });
577
- // Use the ORIGINAL attach (not mod.attach) so we don't double
578
- // through the wrapped version below.
579
- const browser = await origAttach.call(this, attachOpts);
580
- const suppressed = suppressSessionTeardown(browser);
581
- await resetAppOnAttach(suppressed, patched.capabilities || {});
582
- return suppressed;
583
- }
584
-
585
- // eslint-disable-next-line no-console
586
- console.log('[testver-bootstrap] Redirecting wdio.remote() → ' +
587
- (patched.protocol || 'https') + '://' + (patched.hostname || '?') + ':' + (patched.port || '?') +
588
- (patched.path || '/wd/hub') +
589
- ' device=' + (patched.capabilities && patched.capabilities['appium:deviceName']));
590
- // Fresh sessions: pass through unchanged. Test's quit() correctly
591
- // tears down the cloud session it created.
592
- const browser = await origRemote.call(this, patched);
593
- // Report this session id back to Testver so the Runner UI can
594
- // render its live preview. Fire-and-forget — best-effort,
595
- // doesn't block test execution.
596
- try { reportExternalSession(browser, patched); } catch (_) { /* swallow */ }
597
- return browser;
598
- };
599
- }
600
-
601
- // Patch attach() for user code that calls it directly (uncommon — most
602
- // call remote()). When the env var indicates Testver reuse, apply
603
- // suppress + reset. Otherwise pass through.
604
- if (origAttach) {
605
- mod.attach = async function testverWrappedAttach(opts) {
606
- // Apply the SAME normalisation the remote() wrapper does — strip
607
- // user/key for local, nest connection params under `options` so
608
- // webdriverio's detectBackend() reads host/port/path correctly.
609
- // Without this, a direct wdio.attach() call hits the identical
610
- // "port: undefined" / "unknown cloud service" bugs.
611
- const patched = applyTestverOverrides(opts);
612
- const connOpts = {
613
- hostname: patched.hostname,
614
- port: patched.port,
615
- protocol: patched.protocol,
616
- path: patched.path,
617
- capabilities: patched.capabilities,
618
- };
619
- const attachOpts = Object.assign({}, patched, {
620
- capabilities: patched.capabilities,
621
- requestedCapabilities: patched.capabilities,
622
- options: connOpts,
623
- });
624
- const browser = await origAttach.call(this, attachOpts);
625
- if (process.env.TESTVER_REUSE_SESSION_ID) {
626
- const suppressed = suppressSessionTeardown(browser);
627
- await resetAppOnAttach(suppressed, patched.capabilities || {});
628
- return suppressed;
629
- }
630
- return browser;
631
- };
632
- }
633
- // Default export sometimes differs (e.g. ESM bundlers).
634
- if (mod.default && typeof mod.default.remote === 'function' && mod.default !== mod) {
635
- wrapWdioModule(mod.default);
636
- }
637
- try { Object.defineProperty(mod, '__testverWrapped', { value: true, enumerable: false }); }
638
- catch (_) { mod.__testverWrapped = true; }
639
- return mod;
640
- }
641
-
642
- // Install require hook — fires every time the user (or any dep) does
643
- // `require('webdriverio')` etc. We patch the export on first load
644
- // and re-return the same instance afterwards (Node's require cache
645
- // gives us identity for free).
646
- Module.prototype.require = function patchedRequire(id) {
647
- const exp = origRequire.apply(this, arguments);
648
- if (id === 'webdriverio' || id === 'wdio-webdriver') {
649
- return wrapWdioModule(exp);
650
- }
651
- return exp;
652
- };
653
-
654
- // Also patch any webdriverio module already loaded BEFORE this
655
- // bootstrap (rare, but possible if --require ordering is off).
656
- try {
657
- for (const cached of Object.keys(require.cache)) {
658
- if (/[/\\]webdriverio[/\\]/.test(cached) && /index\.[cm]?js$/.test(cached)) {
659
- wrapWdioModule(require.cache[cached].exports);
660
- }
661
- }
662
- } catch (_) { /* swallow — best-effort */ }
663
-
664
- // eslint-disable-next-line no-console
665
- console.log('[testver-bootstrap] wdio cloud-bridge bootstrap active (' +
666
- (process.env.TESTVER_PROVIDER || 'no provider') + ')');
1
+ /**
2
+ * Testver mobile cloud-bridge bootstrap (Node `--require` hook).
3
+ *
4
+ * Loaded via `NODE_OPTIONS=--require=<absolute-path>/bootstrap.cjs`
5
+ * BEFORE the user's test code runs. Monkey-patches the `webdriverio`
6
+ * package's `remote()` function to override:
7
+ * - hostname / port / protocol / path → the Appium cloud hub
8
+ * - user / key → provider credentials
9
+ * - capabilities → device + app + provider opts
10
+ *
11
+ * Reads everything from TESTVER_* and APPIUM_HUB_* env vars Testver injects.
12
+ * No-op when those env vars aren't set (so non-Testver invocations
13
+ * keep working exactly as before).
14
+ *
15
+ * Why this exists: mocha-based mobile projects don't load wdio.conf —
16
+ * they `require('webdriverio')` and call `remote({ hostname: 'localhost'
17
+ * })` directly. Without this bootstrap, env-var injection alone can't
18
+ * override those hardcoded values. The bootstrap intercepts at the
19
+ * package boundary so user code stays untouched.
20
+ *
21
+ * Strategy: install a require hook (via Module.prototype.require)
22
+ * that wraps `webdriverio` and `wdio-webdriver` on first import. Works
23
+ * for CommonJS test runners (mocha being the prime target). ESM-only
24
+ * projects fall through harmlessly — they typically already use
25
+ * wdio.conf so the overlay path handles them.
26
+ */
27
+
28
+ 'use strict';
29
+
30
+ // Skip when Testver env vars aren't present — safety net for users
31
+ // who accidentally inherit NODE_OPTIONS in unrelated processes.
32
+ if (!process.env.TESTVER_PROVIDER && !process.env.APPIUM_HUB_HOST) {
33
+ return;
34
+ }
35
+
36
+ const Module = require('module');
37
+ const origRequire = Module.prototype.require;
38
+
39
+ /**
40
+ * Standard W3C WebDriver capabilities — these stay unprefixed.
41
+ * Any other key without a `vendor:` prefix is treated as a legacy
42
+ * Appium cap and gets auto-prefixed with `appium:` below. List from
43
+ * https://w3c.github.io/webdriver/#capabilities (May 2026).
44
+ */
45
+ const W3C_STANDARD_CAPS = new Set([
46
+ 'browserName',
47
+ 'browserVersion',
48
+ 'platformName',
49
+ 'acceptInsecureCerts',
50
+ 'pageLoadStrategy',
51
+ 'proxy',
52
+ 'setWindowRect',
53
+ 'timeouts',
54
+ 'strictFileInteractability',
55
+ 'unhandledPromptBehavior',
56
+ 'webSocketUrl',
57
+ 'fedcm:accounts',
58
+ ]);
59
+
60
+ /**
61
+ * Auto-prefix unprefixed Appium-specific keys with `appium:` so a
62
+ * W3C-compliant server (BrowserStack, Sauce, Appium 2.x) accepts them.
63
+ * Anything that's already `vendor:foo` (contains a colon) is left alone.
64
+ * Standard W3C caps stay unprefixed. Mutates `caps` in place.
65
+ */
66
+ function appiumPrefixCaps(caps) {
67
+ for (const k of Object.keys(caps)) {
68
+ if (k.includes(':')) continue; // already vendor-prefixed
69
+ if (W3C_STANDARD_CAPS.has(k)) continue; // standard W3C cap
70
+ // Legacy Appium key → re-key under `appium:` namespace.
71
+ const v = caps[k];
72
+ delete caps[k];
73
+ caps['appium:' + k] = v;
74
+ }
75
+ }
76
+
77
+ /**
78
+ * Normalise a capabilities object to the flat shape webdriverio v8+
79
+ * accepts at the user-facing API. Some test code (esp. ones authored
80
+ * against the raw W3C spec or older WebDriver clients) hands wdio a
81
+ * `{ alwaysMatch: {...}, firstMatch: [...] }` payload, which wdio
82
+ * rejects with:
83
+ * Invalid or unsupported WebDriver capabilities found
84
+ * ("alwaysMatch", "firstMatch").
85
+ * We unwrap alwaysMatch into the flat shape and discard firstMatch
86
+ * (Testver overrides supply everything that matters for cloud runs).
87
+ */
88
+ function flattenCaps(caps) {
89
+ if (!caps || typeof caps !== 'object') return {};
90
+ if (Array.isArray(caps)) return {};
91
+ if ('alwaysMatch' in caps || 'firstMatch' in caps) {
92
+ const flat = Object.assign({}, caps.alwaysMatch || {});
93
+ // Preserve any non-W3C-internal keys the user attached alongside.
94
+ for (const k of Object.keys(caps)) {
95
+ if (k !== 'alwaysMatch' && k !== 'firstMatch') flat[k] = caps[k];
96
+ }
97
+ return flat;
98
+ }
99
+ return caps;
100
+ }
101
+
102
+ /**
103
+ * Local Devices (Settings → Local Devices): capabilities the project doesn't
104
+ * set itself (TESTVER_LOCAL_CAPS_DEFAULTS — WebDriverAgent port and signing),
105
+ * then Testver's own over the project's (TESTVER_LOCAL_CAPS — app launch mode).
106
+ */
107
+ function applyLocalCaps(caps) {
108
+ let defaults = {};
109
+ let overrides = {};
110
+ try { defaults = process.env.TESTVER_LOCAL_CAPS_DEFAULTS ? JSON.parse(process.env.TESTVER_LOCAL_CAPS_DEFAULTS) : {}; } catch (e) { defaults = {}; }
111
+ try { overrides = process.env.TESTVER_LOCAL_CAPS ? JSON.parse(process.env.TESTVER_LOCAL_CAPS) : {}; } catch (e) { overrides = {}; }
112
+ for (const k of Object.keys(defaults)) {
113
+ if (caps[k] === undefined && caps[k.replace(/^appium:/, '')] === undefined) caps[k] = defaults[k];
114
+ }
115
+ for (const k of Object.keys(overrides)) {
116
+ delete caps[k.replace(/^appium:/, '')];
117
+ caps[k] = overrides[k];
118
+ }
119
+ }
120
+
121
+ /**
122
+ * The key the capabilities already use for a vendor block, matched without
123
+ * regard to case (`LT:Options` / `lt:options`), else `key` — Testver merges
124
+ * into the project's own block rather than adding a second one.
125
+ */
126
+ function vendorKeyIn(caps, key) {
127
+ if (!key || !caps || typeof caps !== 'object' || Object.prototype.hasOwnProperty.call(caps, key)) return key;
128
+ const lower = key.toLowerCase();
129
+ return Object.keys(caps).find((k) => k.toLowerCase() === lower) || key;
130
+ }
131
+
132
+ /** Apply Testver cloud overrides to a wdio `remote()` options object. */
133
+ function applyTestverOverrides(opts) {
134
+ opts = opts || {};
135
+ // Connection details
136
+ if (process.env.APPIUM_HUB_HOST) opts.hostname = process.env.APPIUM_HUB_HOST;
137
+ if (process.env.APPIUM_HUB_PORT) opts.port = Number(process.env.APPIUM_HUB_PORT);
138
+ if (process.env.APPIUM_HUB_PROTOCOL) opts.protocol = process.env.APPIUM_HUB_PROTOCOL;
139
+ if (process.env.APPIUM_HUB_PATH) opts.path = process.env.APPIUM_HUB_PATH;
140
+ if (process.env.APPIUM_HUB_USER) opts.user = process.env.APPIUM_HUB_USER;
141
+ if (process.env.APPIUM_HUB_KEY) opts.key = process.env.APPIUM_HUB_KEY;
142
+
143
+ // Local-Appium has NO credentials. The user's test code may have set
144
+ // `user`/`key` from a BrowserStack-shaped .env — if we leave them on
145
+ // the options, WebdriverIO's detectBackend() sees user+key present
146
+ // with hostname 127.0.0.1 (not a known cloud) and throws:
147
+ // 'A "user" or "key" was provided but could not be connected to a
148
+ // known cloud service'.
149
+ // Strip them so wdio treats this as a plain local Appium endpoint.
150
+ if (process.env.TESTVER_PROVIDER === 'local-appium') {
151
+ delete opts.user;
152
+ delete opts.key;
153
+ }
154
+
155
+ // Force the flat capabilities shape — strips out any alwaysMatch /
156
+ // firstMatch the user's code might have built manually. wdio v8+
157
+ // builds the W3C envelope internally; passing one in errors.
158
+ const caps = flattenCaps(opts.capabilities);
159
+ opts.capabilities = caps;
160
+
161
+ // Auto-prefix legacy unprefixed Appium keys (deviceName, appPackage,
162
+ // automationName, …) with `appium:` so W3C-compliant servers accept
163
+ // them. Caps that are already vendor-prefixed (`bstack:options`,
164
+ // `appium:foo`) and standard W3C caps (`platformName`) stay as-is.
165
+ appiumPrefixCaps(caps);
166
+
167
+ if (process.env.TESTVER_PLATFORM_NAME) caps.platformName = process.env.TESTVER_PLATFORM_NAME;
168
+ if (process.env.TESTVER_DEVICE_NAME) caps['appium:deviceName'] = process.env.TESTVER_DEVICE_NAME;
169
+ if (process.env.TESTVER_PLATFORM_VERSION) caps['appium:platformVersion'] = process.env.TESTVER_PLATFORM_VERSION;
170
+ // The device: a local one by its serial / udid (Appium picks the device by
171
+ // appium:udid, never by deviceName); on a vendor's cloud a local udid / AVD
172
+ // means nothing.
173
+ if (process.env.TESTVER_PROVIDER === 'local-appium') {
174
+ if (process.env.TESTVER_DEVICE_UDID) {
175
+ caps['appium:udid'] = process.env.TESTVER_DEVICE_UDID;
176
+ delete caps['appium:avd'];
177
+ }
178
+ applyLocalCaps(caps);
179
+ } else {
180
+ delete caps['appium:udid'];
181
+ delete caps['appium:avd'];
182
+ }
183
+ if (process.env.TESTVER_APP_URL) {
184
+ caps['appium:app'] = process.env.TESTVER_APP_URL;
185
+ // The user's test code may hard-code app-identifier caps that
186
+ // belong to a DIFFERENT build than what Testver just uploaded
187
+ // (e.g., appPackage / appActivity / bundleId). Cloud providers
188
+ // (BrowserStack, Sauce, LambdaTest) auto-detect these from the
189
+ // uploaded APK/IPA metadata when omitted, so dropping them here
190
+ // makes the run robust against mismatches like:
191
+ // [BROWSERSTACK_INVALID_APP_ACTIVITY] Activity name "..." used
192
+ // to start the app doesn't exist. Supported values: "c".
193
+ // (the project's package / bundle id is kept aside for the app reset
194
+ // on a reused session)
195
+ projectAppId = caps['appium:appPackage'] || caps['appium:bundleId'] || projectAppId;
196
+ delete caps['appium:appPackage'];
197
+ delete caps['appium:appActivity'];
198
+ delete caps['appium:appWaitActivity'];
199
+ delete caps['appium:appWaitPackage'];
200
+ delete caps['appium:bundleId']; // iOS counterpart
201
+ delete caps['appium:appWaitForLaunch'];
202
+ }
203
+
204
+ // Sensible automation name default — required by cloud providers.
205
+ // Only set if the user didn't already pick one (e.g. Espresso, XCUITest).
206
+ if (!caps['appium:automationName']) {
207
+ caps['appium:automationName'] = caps.platformName === 'iOS' ? 'XCUITest' : 'UiAutomator2';
208
+ }
209
+
210
+ // Provider-specific options block.
211
+ //
212
+ // CRITICAL: BrowserStack / Sauce Labs / LambdaTest route to a
213
+ // specific cloud device by reading the device name from THEIR own
214
+ // options block (e.g. `bstack:options.deviceName`), NOT from
215
+ // `appium:deviceName`. The latter is the *Appium server's* internal
216
+ // device label, which on cloud hubs is often the same string but
217
+ // can also be the cloud's internal udid — providers reject device
218
+ // selection when only `appium:deviceName` is set:
219
+ // [BROWSERSTACK_NO_DEVICE_SPECIFIED] The 'device' capability is
220
+ // missing in your test script.
221
+ //
222
+ // So we ALWAYS mirror the device + OS version into the
223
+ // provider-options block. The source of truth is whichever was
224
+ // already populated on caps — either by the user's test code (caps
225
+ // built manually) or by Testver overrides above (caps['appium:*']
226
+ // populated from TESTVER_* env vars). Order of preference:
227
+ // 1. Testver env var (explicit selection by UI / Runner)
228
+ // 2. User-provided `appium:deviceName` from their caps
229
+ // 3. Anything the user already put in `bstack:options.deviceName`
230
+ // The vendor block Testver built for this run (TESTVER_VENDOR_OPTIONS):
231
+ // each vendor's own field names, the tunnel, the picked device. Names and
232
+ // tunnel: the project's own values win; the picked device wins over the
233
+ // project's. Without it (an older run plan) the device and OS version are
234
+ // still mirrored into the vendor's block.
235
+ let vendor = null;
236
+ try { vendor = process.env.TESTVER_VENDOR_OPTIONS ? JSON.parse(process.env.TESTVER_VENDOR_OPTIONS) : null; } catch (e) { vendor = null; }
237
+ if (vendor && vendor.key) {
238
+ // the project's own spelling of the block (`LT:Options` / `lt:options`)
239
+ const key = vendorKeyIn(caps, vendor.key);
240
+ caps[key] = Object.assign({}, vendor.options || {}, caps[key] || {}, vendor.overrides || {});
241
+ } else {
242
+ const key = vendorKeyIn(caps, { browserstack: 'bstack:options', saucelabs: 'sauce:options', lambdatest: 'lt:options' }[process.env.TESTVER_PROVIDER || ''] || '');
243
+ const device = process.env.TESTVER_DEVICE_NAME || caps['appium:deviceName'];
244
+ if (key && device) {
245
+ const existing = caps[key] || {};
246
+ caps[key] = Object.assign({}, existing, existing.deviceName ? {} : { deviceName: device });
247
+ }
248
+ }
249
+ return opts;
250
+ }
251
+
252
+ /**
253
+ * Wrap the `remote` export on a webdriverio module. Idempotent.
254
+ *
255
+ * Two behaviours, selected at call time by env state:
256
+ * - TESTVER_REUSE_SESSION_ID present → call wdio.attach() to ATTACH
257
+ * to the existing AI Assistant / AI Record live session. Saves the
258
+ * 30-60s device-boot cost + one cloud minute per claim.
259
+ * - Otherwise → call the original wdio.remote() with cloud-redirected
260
+ * connection + Testver-normalized capabilities (fresh session).
261
+ */
262
+ /**
263
+ * When the test code is running on a SHARED reused session, the
264
+ * test's teardown call to `driver.quit()` / `driver.deleteSession()`
265
+ * would terminate the entire BrowserStack session — killing the
266
+ * live session AI Assistant is still using. We can't have that.
267
+ *
268
+ * Wrap the attached browser so those teardown methods become no-ops
269
+ * (but still return a resolved promise so existing `await driver.quit()`
270
+ * code keeps working). Other operations on the browser remain
271
+ * untouched. Idempotent — only wraps once per browser instance.
272
+ *
273
+ * For non-reuse runs (fresh `remote()`), this wrapper is NOT applied:
274
+ * `quit()` works normally and cleanly tears down the freshly-created
275
+ * cloud session as the test author expects.
276
+ */
277
+ /**
278
+ * Reset the app to a fresh launch state on an attached session.
279
+ *
280
+ * When AI Assistant has been driving the device, the app is sitting on
281
+ * whatever screen the user navigated to. A test attached to this
282
+ * session expects a clean launch (welcome screen, login screen, etc.).
283
+ * Without resetting, every test fails on its first assertion because
284
+ * the screen it expects to see isn't there.
285
+ *
286
+ * Strategy:
287
+ * 1. terminateApp(appId) → kills the running app process
288
+ * 2. activateApp(appId) → relaunches it (same as a cold-launch from
289
+ * the user's perspective)
290
+ *
291
+ * The cloud SESSION stays alive across both calls — only the app
292
+ * process is recycled. ~1-2 seconds total. Cheaper than booting a
293
+ * fresh device (30-60s).
294
+ *
295
+ * App identifier sources, in order:
296
+ * - caps['appium:appPackage'] (Android, set by user test code)
297
+ * - caps['appium:bundleId'] (iOS, set by user test code)
298
+ * - TESTVER_APP_PACKAGE env var (override hook for future use)
299
+ * - TESTVER_APP_BUNDLE_ID env var
300
+ *
301
+ * Disable: set TESTVER_SKIP_APP_RESET=1 in the run env.
302
+ */
303
+ /** The project's own app package / bundle id, before an uploaded app replaced it in the caps. */
304
+ let projectAppId;
305
+
306
+ async function resetAppOnAttach(browser, caps) {
307
+ // Idempotency guard — if the browser already went through a reset
308
+ // (e.g. wdio.remote() delegated to wdio.attach() which is also
309
+ // wrapped), don't reset twice.
310
+ if (browser.__testverResetDone) return;
311
+ try { Object.defineProperty(browser, '__testverResetDone', { value: true, enumerable: false }); }
312
+ catch (_) { browser.__testverResetDone = true; }
313
+
314
+ if (process.env.TESTVER_SKIP_APP_RESET === '1') {
315
+ // eslint-disable-next-line no-console
316
+ console.log('[testver-bootstrap] App reset skipped (TESTVER_SKIP_APP_RESET=1)');
317
+ return;
318
+ }
319
+ const appId = (caps && (caps['appium:appPackage'] || caps['appium:bundleId']))
320
+ || projectAppId
321
+ || process.env.TESTVER_APP_PACKAGE
322
+ || process.env.TESTVER_APP_BUNDLE_ID;
323
+ if (!appId) {
324
+ // eslint-disable-next-line no-console
325
+ console.log('[testver-bootstrap] App reset on attach: no appPackage/bundleId in caps — skipping ' +
326
+ '(test may see stale UI state from prior AI Assistant interactions). ' +
327
+ 'Set caps.appPackage (Android) or caps.bundleId (iOS) in your test code, ' +
328
+ 'or export TESTVER_APP_PACKAGE / TESTVER_APP_BUNDLE_ID to enable auto-reset.');
329
+ return;
330
+ }
331
+
332
+ // Platform detection — drives whether we issue `mobile: clearApp`
333
+ // (Android only — wipes SharedPreferences + cache + databases so
334
+ // the app launches as if freshly installed, including onboarding
335
+ // screens). iOS doesn't have a direct equivalent at the WebDriver
336
+ // protocol level; terminate + activate is the best we can do.
337
+ const platform = String((caps && caps.platformName) || process.env.TESTVER_PLATFORM_NAME || '').toLowerCase();
338
+ const isAndroid = platform === 'android';
339
+ const skipClear = process.env.TESTVER_SKIP_APP_CLEAR === '1';
340
+
341
+ // eslint-disable-next-line no-console
342
+ console.log('[testver-bootstrap] Resetting app "' + appId + '" on attached session ' +
343
+ '(' + (isAndroid && !skipClear ? 'clearApp + ' : '') + 'terminate + activate) ' +
344
+ 'so test starts from a fresh launch...');
345
+ try {
346
+ // Step 1 (Android only): clear app DATA so onboarding state, login
347
+ // state, cached pages, etc. all reset. Without this, terminate +
348
+ // activate just kills + restarts the process — the user's previous
349
+ // "completed onboarding" flag persists and the welcome screen
350
+ // never appears. Skippable via TESTVER_SKIP_APP_CLEAR=1 when the
351
+ // test expects to inherit state from prior interactions.
352
+ if (isAndroid && !skipClear) {
353
+ try {
354
+ await browser.execute('mobile: clearApp', { appId });
355
+ // eslint-disable-next-line no-console
356
+ console.log('[testver-bootstrap] App data cleared (onboarding + cached state reset).');
357
+ } catch (err) {
358
+ // Some Appium-server / cloud-driver configs don't expose
359
+ // clearApp — fall back to terminate + activate alone. Most
360
+ // tests still work; the onboarding flag is the edge case.
361
+ // eslint-disable-next-line no-console
362
+ console.log('[testver-bootstrap] clearApp not available: ' + (err && err.message) +
363
+ ' — proceeding with terminate+activate (onboarding state may persist).');
364
+ }
365
+ }
366
+ // Step 2: terminate (if running). Failure is fine — activate
367
+ // launches anyway.
368
+ const terminate = async () => {
369
+ if (typeof browser.terminateApp === 'function') return browser.terminateApp(appId);
370
+ return browser.execute('mobile: terminateApp', { appId });
371
+ };
372
+ try {
373
+ await terminate();
374
+ } catch (err) {
375
+ // eslint-disable-next-line no-console
376
+ console.log('[testver-bootstrap] terminateApp non-fatal: ' + (err && err.message));
377
+ }
378
+ // Step 3: cold-launch the app.
379
+ const activate = async () => {
380
+ if (typeof browser.activateApp === 'function') return browser.activateApp(appId);
381
+ return browser.execute('mobile: activateApp', { appId });
382
+ };
383
+ await activate();
384
+ // eslint-disable-next-line no-console
385
+ console.log('[testver-bootstrap] App reset complete — test starts from fresh launch state');
386
+ } catch (err) {
387
+ // eslint-disable-next-line no-console
388
+ console.log('[testver-bootstrap] App reset failed: ' + (err && err.message) +
389
+ ' — continuing anyway. If the test fails on the first assertion, set TESTVER_SKIP_APP_RESET=1 ' +
390
+ 'and reset the app manually in your test setup.');
391
+ }
392
+ }
393
+
394
+ function suppressSessionTeardown(browser) {
395
+ if (!browser || browser.__testverTeardownSuppressed) return browser;
396
+ const noopMethodNames = ['deleteSession', 'quit', 'endSession', 'end'];
397
+ const noopFor = (name) => function suppressedQuit() {
398
+ // eslint-disable-next-line no-console
399
+ console.log('[testver-bootstrap] ' + name + '() suppressed — session is SHARED with AI Assistant ' +
400
+ '(use driver.terminateApp()/activateApp() to reset state instead).');
401
+ return Promise.resolve();
402
+ };
403
+
404
+ // Strategy A: Object.defineProperty (works when the property is
405
+ // non-writable but still configurable — wdio v8.27+ marks
406
+ // deleteSession non-writable via getters but leaves it configurable).
407
+ let allOverridden = true;
408
+ for (const m of noopMethodNames) {
409
+ try {
410
+ Object.defineProperty(browser, m, {
411
+ value: noopFor(m),
412
+ writable: true,
413
+ configurable: true,
414
+ enumerable: false,
415
+ });
416
+ } catch (err) {
417
+ allOverridden = false;
418
+ // eslint-disable-next-line no-console
419
+ console.warn('[testver-bootstrap] defineProperty(' + m + ') failed: ' + (err && err.message));
420
+ }
421
+ }
422
+
423
+ if (allOverridden) {
424
+ try { Object.defineProperty(browser, '__testverTeardownSuppressed', { value: true, enumerable: false }); }
425
+ catch (_) { /* swallow — flag is best-effort */ }
426
+ return browser;
427
+ }
428
+
429
+ // Strategy B (fallback): wrap in a Proxy that intercepts the four
430
+ // teardown methods. We bind every OTHER method to the original
431
+ // target so wdio internals that rely on `this` keep working.
432
+ // Proxy never breaks for read-only props — gets always return the
433
+ // value we choose.
434
+ const noopSet = new Set(noopMethodNames);
435
+ const proxied = new Proxy(browser, {
436
+ get(target, prop, receiver) {
437
+ if (typeof prop === 'string' && noopSet.has(prop)) {
438
+ return noopFor(prop);
439
+ }
440
+ const v = Reflect.get(target, prop, receiver);
441
+ // Methods need their `this` rebound to the real browser so
442
+ // wdio's command pipeline (which inspects `this.options`,
443
+ // `this.capabilities`, etc.) still sees a valid context.
444
+ return typeof v === 'function' ? v.bind(target) : v;
445
+ },
446
+ set(target, prop, value) {
447
+ return Reflect.set(target, prop, value);
448
+ },
449
+ });
450
+ try { Object.defineProperty(proxied, '__testverTeardownSuppressed', { value: true, enumerable: false }); }
451
+ catch (_) { /* swallow */ }
452
+ return proxied;
453
+ }
454
+
455
+ /**
456
+ * POST the cloud sessionId back to Testver so the Runner's live-preview
457
+ * panel can render screenshots from this very session. Fire-and-forget;
458
+ * a failure here just means the live panel stays empty — the test still
459
+ * runs unaffected. We pass the FULL hub URL (with credentials) so the
460
+ * server can authenticate direct screenshot calls without needing to
461
+ * re-resolve creds from disk.
462
+ */
463
+ function reportExternalSession(browser, patched) {
464
+ const reportUrl = process.env.TESTVER_REPORTBACK_URL;
465
+ const clientId = process.env.TESTVER_CLIENT_ID;
466
+ if (!reportUrl || !clientId || !browser || !browser.sessionId) return;
467
+
468
+ // Reconstruct the hub URL with embedded credentials — Testver's
469
+ // register endpoint parses this with new URL(...) to extract host/
470
+ // port/path/user/key without separate fields.
471
+ const proto = patched.protocol || 'https';
472
+ const host = patched.hostname;
473
+ const port = patched.port || (proto === 'https' ? 443 : 80);
474
+ const path = patched.path || '/wd/hub';
475
+ const user = encodeURIComponent(patched.user || '');
476
+ const key = encodeURIComponent(patched.key || '');
477
+ const hubUrl = `${proto}://${user}:${key}@${host}:${port}${path}`;
478
+ const body = JSON.stringify({
479
+ clientId,
480
+ sessionId: browser.sessionId,
481
+ hubUrl,
482
+ deviceName: patched.capabilities && patched.capabilities['appium:deviceName'],
483
+ platformName: patched.capabilities && patched.capabilities.platformName,
484
+ providerId: process.env.TESTVER_PROVIDER,
485
+ // the run that opened it (several runs of one tab side by side)
486
+ runId: process.env.TESTVER_RUN_ID,
487
+ });
488
+ const endpoint = reportUrl.replace(/\/$/, '') + '/api/mobile/session/register-external';
489
+ // Node 18+ has global fetch — we target Node 20 in the parent app.
490
+ if (typeof fetch !== 'function') {
491
+ // eslint-disable-next-line no-console
492
+ console.log('[testver-bootstrap] No global fetch available — live-preview reportback skipped.');
493
+ return;
494
+ }
495
+ fetch(endpoint, {
496
+ method: 'POST',
497
+ headers: { 'Content-Type': 'application/json' },
498
+ body,
499
+ }).then(() => {
500
+ // eslint-disable-next-line no-console
501
+ console.log('[testver-bootstrap] Reported sessionId ' + browser.sessionId.slice(0, 12) + '… to Testver for live preview');
502
+ }).catch((err) => {
503
+ // eslint-disable-next-line no-console
504
+ console.log('[testver-bootstrap] Reportback failed (live preview may be empty): ' + (err && err.message));
505
+ });
506
+ }
507
+
508
+ /**
509
+ * A local device run: tell Testver which Appium session this test opened,
510
+ * so Auto-Heal can read the device screen and Stop can end the session
511
+ * (Appium 3 does not list its sessions to other programs). Only the
512
+ * session id goes; the run's one-time token proves it is this run.
513
+ */
514
+ async function reportDeviceSession(sessionId) {
515
+ const url = process.env.TESTVER_SESSION_REPORT_URL;
516
+ const token = process.env.TESTVER_SESSION_REPORT_TOKEN;
517
+ const runId = process.env.TESTVER_RUN_ID;
518
+ if (!url || !token || !runId || !sessionId || typeof fetch !== 'function') return;
519
+ try {
520
+ await fetch(url, {
521
+ method: 'POST',
522
+ headers: { 'Content-Type': 'application/json' },
523
+ body: JSON.stringify({ runId, token, sessionId: String(sessionId) }),
524
+ });
525
+ } catch (_) { /* best-effort — capture and Stop clean-up only */ }
526
+ }
527
+
528
+ /**
529
+ * Tell Testver this external session is over so it stops trying to
530
+ * poll its screenshots. Fire-and-forget; the registry has a TTL
531
+ * fallback if this call drops.
532
+ */
533
+ function unreportExternalSession() {
534
+ const reportUrl = process.env.TESTVER_REPORTBACK_URL;
535
+ const clientId = process.env.TESTVER_CLIENT_ID;
536
+ if (!reportUrl || !clientId || typeof fetch !== 'function') return;
537
+ const endpoint = reportUrl.replace(/\/$/, '') + '/api/mobile/session/unregister-external';
538
+ fetch(endpoint, {
539
+ method: 'POST',
540
+ headers: { 'Content-Type': 'application/json' },
541
+ body: JSON.stringify({ clientId }),
542
+ }).catch(() => { /* best-effort */ });
543
+ }
544
+
545
+ // Wire up process exit hooks so the registry doesn't keep a stale
546
+ // entry after the test process dies. The TTL on the server side
547
+ // catches anything we miss here.
548
+ process.on('exit', unreportExternalSession);
549
+ process.on('SIGINT', () => { unreportExternalSession(); process.exit(130); });
550
+ process.on('SIGTERM', () => { unreportExternalSession(); process.exit(143); });
551
+
552
+ function wrapWdioModule(mod) {
553
+ if (!mod || mod.__testverWrapped) return mod;
554
+
555
+ // Capture the ORIGINAL attach() reference BEFORE wrapping — we use
556
+ // this directly inside the remote() wrapper so we don't accidentally
557
+ // double-invoke our own attach wrapper (which would suppress +
558
+ // reset twice). After we install our wrapped attach below, all
559
+ // EXTERNAL callers (user test code calling wdio.attach() directly)
560
+ // hit the wrapped version; the remote() wrapper bypasses it.
561
+ const origAttach = typeof mod.attach === 'function' ? mod.attach : null;
562
+ const origRemote = typeof mod.remote === 'function' ? mod.remote : null;
563
+
564
+ if (origRemote) {
565
+ mod.remote = async function testverWrappedRemote(opts) {
566
+ const reuseId = process.env.TESTVER_REUSE_SESSION_ID;
567
+ // Always normalise/apply overrides — even attach() needs the
568
+ // hub host/port/user/key + flattened caps so wdio knows where
569
+ // to send subsequent commands.
570
+ const patched = applyTestverOverrides(opts);
571
+
572
+ if (reuseId && origAttach) {
573
+ // eslint-disable-next-line no-console
574
+ console.log('[testver-bootstrap] Attaching to live session ' + reuseId.slice(0, 12) + '… on ' +
575
+ (patched.hostname || '?') + ' (skips device boot)');
576
+ // webdriverio's attach() reads its connection details from
577
+ // `attachOptions.options` via detectBackend(), NOT from the
578
+ // top-level object. detectBackend(undefined) returns
579
+ // { hostname: undefined, port: undefined, … } which then
580
+ // OVERRIDES any flat top-level values we pass — producing the
581
+ // malformed `http://127.0.0.1:undefined/…` URL. So we MUST nest
582
+ // the connection params under `options` (and mirror them at the
583
+ // top level for older wdio versions that read both).
584
+ const connOpts = {
585
+ hostname: patched.hostname,
586
+ port: patched.port,
587
+ protocol: patched.protocol,
588
+ path: patched.path,
589
+ capabilities: patched.capabilities,
590
+ };
591
+ const attachOpts = Object.assign({}, patched, {
592
+ sessionId: reuseId,
593
+ capabilities: patched.capabilities,
594
+ requestedCapabilities: patched.capabilities,
595
+ options: connOpts,
596
+ });
597
+ // Use the ORIGINAL attach (not mod.attach) so we don't double
598
+ // through the wrapped version below.
599
+ const browser = await origAttach.call(this, attachOpts);
600
+ const suppressed = suppressSessionTeardown(browser);
601
+ await resetAppOnAttach(suppressed, patched.capabilities || {});
602
+ return suppressed;
603
+ }
604
+
605
+ // eslint-disable-next-line no-console
606
+ console.log('[testver-bootstrap] Redirecting wdio.remote() → ' +
607
+ (patched.protocol || 'https') + '://' + (patched.hostname || '?') + ':' + (patched.port || '?') +
608
+ (patched.path || '/wd/hub') +
609
+ ' device=' + (patched.capabilities && patched.capabilities['appium:deviceName']));
610
+ // Fresh sessions: pass through unchanged. Test's quit() correctly
611
+ // tears down the cloud session it created.
612
+ const browser = await origRemote.call(this, patched);
613
+ // Report this session id back to Testver so the Runner UI can
614
+ // render its live preview. Fire-and-forget — best-effort,
615
+ // doesn't block test execution.
616
+ try { reportExternalSession(browser, patched); } catch (_) { /* swallow */ }
617
+ void reportDeviceSession(browser && browser.sessionId);
618
+ return browser;
619
+ };
620
+ }
621
+
622
+ // Patch attach() for user code that calls it directly (uncommon — most
623
+ // call remote()). When the env var indicates Testver reuse, apply
624
+ // suppress + reset. Otherwise pass through.
625
+ if (origAttach) {
626
+ mod.attach = async function testverWrappedAttach(opts) {
627
+ // Apply the SAME normalisation the remote() wrapper does — strip
628
+ // user/key for local, nest connection params under `options` so
629
+ // webdriverio's detectBackend() reads host/port/path correctly.
630
+ // Without this, a direct wdio.attach() call hits the identical
631
+ // "port: undefined" / "unknown cloud service" bugs.
632
+ const patched = applyTestverOverrides(opts);
633
+ const connOpts = {
634
+ hostname: patched.hostname,
635
+ port: patched.port,
636
+ protocol: patched.protocol,
637
+ path: patched.path,
638
+ capabilities: patched.capabilities,
639
+ };
640
+ const attachOpts = Object.assign({}, patched, {
641
+ capabilities: patched.capabilities,
642
+ requestedCapabilities: patched.capabilities,
643
+ options: connOpts,
644
+ });
645
+ const browser = await origAttach.call(this, attachOpts);
646
+ if (process.env.TESTVER_REUSE_SESSION_ID) {
647
+ const suppressed = suppressSessionTeardown(browser);
648
+ await resetAppOnAttach(suppressed, patched.capabilities || {});
649
+ return suppressed;
650
+ }
651
+ return browser;
652
+ };
653
+ }
654
+ // Default export sometimes differs (e.g. ESM bundlers).
655
+ if (mod.default && typeof mod.default.remote === 'function' && mod.default !== mod) {
656
+ wrapWdioModule(mod.default);
657
+ }
658
+ try { Object.defineProperty(mod, '__testverWrapped', { value: true, enumerable: false }); }
659
+ catch (_) { mod.__testverWrapped = true; }
660
+ return mod;
661
+ }
662
+
663
+ // Install require hook — fires every time the user (or any dep) does
664
+ // `require('webdriverio')` etc. We patch the export on first load
665
+ // and re-return the same instance afterwards (Node's require cache
666
+ // gives us identity for free).
667
+ Module.prototype.require = function patchedRequire(id) {
668
+ const exp = origRequire.apply(this, arguments);
669
+ if (id === 'webdriverio' || id === 'wdio-webdriver') {
670
+ return wrapWdioModule(exp);
671
+ }
672
+ return exp;
673
+ };
674
+
675
+ // Also patch any webdriverio module already loaded BEFORE this
676
+ // bootstrap (rare, but possible if --require ordering is off).
677
+ try {
678
+ for (const cached of Object.keys(require.cache)) {
679
+ if (/[/\\]webdriverio[/\\]/.test(cached) && /index\.[cm]?js$/.test(cached)) {
680
+ wrapWdioModule(require.cache[cached].exports);
681
+ }
682
+ }
683
+ } catch (_) { /* swallow — best-effort */ }
684
+
685
+ // eslint-disable-next-line no-console
686
+ console.log('[testver-bootstrap] wdio cloud-bridge bootstrap active (' +
687
+ (process.env.TESTVER_PROVIDER || 'no provider') + ')');