@testver/testver 1.2.4 → 1.2.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,215 +1,236 @@
1
- /**
2
- * @testver/wdio-attach-service
3
- *
4
- * WebdriverIO launcher service that, when `TESTVER_REUSE_SESSION_ID`
5
- * is present in the environment, attaches to an existing Appium cloud
6
- * session instead of letting WDIO open a fresh one. Saves ~30-60s of
7
- * cloud device boot time and one provider minute per reuse.
8
- *
9
- * Plumbed in automatically by Testver's `wdio.testver.conf.{ts,js}`
10
- * overlay (see src/mobile/cloud-bridge.ts > renderWdioOverlay). The
11
- * service is only appended to the WDIO `services` array when the env
12
- * var is set — so non-reuse runs are completely unaffected.
13
- *
14
- * How it works
15
- * ─────────────
16
- * WDIO's launcher calls `before` on every service before spinning up
17
- * a session. We monkey-patch `global.browser`-builder by hooking into
18
- * the `beforeSession` lifecycle: before WDIO POSTs `/session`, we
19
- * pre-attach to the existing sessionId via `webdriverio.attach()` and
20
- * stash the result on `global.browser`. WDIO sees a browser already
21
- * exists and skips its own session creation.
22
- *
23
- * This is intentionally implemented as CommonJS (.cjs) so it can be
24
- * resolved by both TS and JS projects without ESM gymnastics.
25
- */
26
-
27
- 'use strict';
28
-
29
- /**
30
- * Resolve `webdriverio` from the USER's project, NOT from wherever this
31
- * vendored .cjs lives (e.g. E:\Testver\dist\wdio-attach-service), which
32
- * has no node_modules — a bare require() there throws
33
- * "Cannot find module 'webdriverio'" and the attach silently fails,
34
- * forcing WDIO into a broken fresh-session fallback. The WDIO run cwd is
35
- * the user's project (Testver `cd`s into it before invoking wdio), so we
36
- * resolve relative to that; TESTVER_PROJECT_DIR is preferred when set.
37
- */
38
- function loadWebdriverio() {
39
- const Module = require('node:module');
40
- const pathMod = require('node:path');
41
- const bases = [];
42
- if (process.env.TESTVER_PROJECT_DIR) bases.push(process.env.TESTVER_PROJECT_DIR);
43
- bases.push(process.cwd());
44
- for (const base of bases) {
45
- try {
46
- const req = Module.createRequire(pathMod.join(base, '__testver_attach_resolver__.cjs'));
47
- return req('webdriverio');
48
- } catch (_e) { /* try the next base */ }
49
- }
50
- // Last resort: resolve from this service's own location (works if the
51
- // user happens to have webdriverio hoisted somewhere reachable).
52
- return require('webdriverio');
53
- }
54
-
55
- /**
56
- * POST the live session back to Testver so the in-app live preview can
57
- * render it. Mirrors the mocha `--require` bootstrap's reportback, but
58
- * for the WDIO test-runner path. Fire-and-forget; a failure just means
59
- * the preview stays empty — the test runs unaffected.
60
- */
61
- async function reportSession(browser) {
62
- const reportUrl = process.env.TESTVER_REPORTBACK_URL;
63
- const clientId = process.env.TESTVER_CLIENT_ID;
64
- if (!reportUrl || !clientId || !browser || !browser.sessionId) return;
65
- if (typeof fetch !== 'function') return;
66
-
67
- const proto = process.env.APPIUM_HUB_PROTOCOL || 'http';
68
- const host = process.env.APPIUM_HUB_HOST || '127.0.0.1';
69
- const port = process.env.APPIUM_HUB_PORT || (proto === 'https' ? '443' : '4723');
70
- const rawPath = process.env.APPIUM_HUB_PATH || '/';
71
- const user = encodeURIComponent(process.env.APPIUM_HUB_USER || '');
72
- const key = encodeURIComponent(process.env.APPIUM_HUB_KEY || '');
73
- const hubUrl = `${proto}://${user}:${key}@${host}:${port}${rawPath}`;
74
-
75
- const caps = browser.capabilities || {};
76
- const body = JSON.stringify({
77
- clientId,
78
- sessionId: browser.sessionId,
79
- hubUrl,
80
- deviceName: caps['appium:deviceName'] || process.env.TESTVER_DEVICE_NAME,
81
- platformName: caps.platformName || process.env.TESTVER_PLATFORM_NAME,
82
- providerId: process.env.TESTVER_PROVIDER,
83
- // the run that opened it (several runs of one tab side by side)
84
- runId: process.env.TESTVER_RUN_ID,
85
- });
86
- try {
87
- await fetch(reportUrl.replace(/\/$/, '') + '/api/mobile/session/register-external', {
88
- method: 'POST',
89
- headers: { 'Content-Type': 'application/json' },
90
- body,
91
- });
92
- // eslint-disable-next-line no-console
93
- console.log(`[testver-attach] Reported sessionId ${String(browser.sessionId).slice(0, 12)}… to Testver for live preview`);
94
- } catch (err) {
95
- // eslint-disable-next-line no-console
96
- console.log(`[testver-attach] Reportback failed (live preview may be empty): ${err && err.message}`);
97
- }
98
- }
99
-
100
- async function unreportSession() {
101
- const reportUrl = process.env.TESTVER_REPORTBACK_URL;
102
- const clientId = process.env.TESTVER_CLIENT_ID;
103
- if (!reportUrl || !clientId || typeof fetch !== 'function') return;
104
- try {
105
- await fetch(reportUrl.replace(/\/$/, '') + '/api/mobile/session/unregister-external', {
106
- method: 'POST',
107
- headers: { 'Content-Type': 'application/json' },
108
- body: JSON.stringify({ clientId }),
109
- });
110
- } catch { /* best-effort */ }
111
- }
112
-
113
- class TestverAttachService {
114
- constructor(serviceOptions = {}, capabilities = {}, config = {}) {
115
- this.serviceOptions = serviceOptions;
116
- this.capabilities = capabilities;
117
- this.config = config;
118
- }
119
-
120
- /**
121
- * `onPrepare` runs once per WDIO launch, BEFORE any worker session.
122
- * We don't attach here — attach happens per-worker in `beforeSession`.
123
- * But we log clearly so users see reuse is engaged.
124
- */
125
- onPrepare() {
126
- const sid = process.env.TESTVER_REUSE_SESSION_ID;
127
- if (!sid) return;
128
- // eslint-disable-next-line no-console
129
- console.log(`[testver-attach] Reuse engaged — will attach to sessionId=${sid.slice(0, 12)}…`);
130
- }
131
-
132
- /**
133
- * `beforeSession` runs once per worker, BEFORE WDIO creates a session.
134
- * WDIO's runner (v7–v9) ATTACHES instead of opening a session when the
135
- * worker's config carries a `sessionId` — so the reused session and the
136
- * hub it lives on go onto that config. (A browser left on globalThis was
137
- * never read: WDIO opened a fresh session on the same device, restarting
138
- * UiAutomator2 under the AI Assistant's live session.)
139
- */
140
- async beforeSession(config, _capabilities) {
141
- const sid = process.env.TESTVER_REUSE_SESSION_ID;
142
- if (!sid) return; // No reuse — let WDIO open a fresh session.
143
- if (config && typeof config === 'object') {
144
- Object.assign(config, {
145
- sessionId: sid,
146
- hostname: process.env.APPIUM_HUB_HOST || config.hostname,
147
- port: Number(process.env.APPIUM_HUB_PORT || config.port || 443),
148
- protocol: process.env.APPIUM_HUB_PROTOCOL || config.protocol || 'https',
149
- path: process.env.APPIUM_HUB_PATH || config.path || '/wd/hub',
150
- user: process.env.APPIUM_HUB_USER || config.user,
151
- key: process.env.APPIUM_HUB_KEY || config.key,
152
- });
153
- // eslint-disable-next-line no-console
154
- console.log(`[testver-attach] Attaching to session ${sid.slice(0, 12)}…`);
155
- return;
156
- }
157
-
158
- const wdio = loadWebdriverio();
159
- const attachOpts = {
160
- sessionId: sid,
161
- hostname: process.env.APPIUM_HUB_HOST,
162
- port: Number(process.env.APPIUM_HUB_PORT || '443'),
163
- protocol: process.env.APPIUM_HUB_PROTOCOL || 'https',
164
- path: process.env.APPIUM_HUB_PATH || '/wd/hub',
165
- user: process.env.APPIUM_HUB_USER,
166
- key: process.env.APPIUM_HUB_KEY,
167
- // Cap object on attach is informational — WDIO uses it to populate
168
- // browser.capabilities for test code that reads it.
169
- capabilities: {
170
- platformName: process.env.TESTVER_PLATFORM_NAME || 'Android',
171
- 'appium:deviceName': process.env.TESTVER_DEVICE_NAME,
172
- 'appium:platformVersion': process.env.TESTVER_PLATFORM_VERSION,
173
- },
174
- };
175
- try {
176
- const browser = await wdio.attach(attachOpts);
177
- // Stash on globalThis so WDIO's worker process picks it up.
178
- // WDIO's launcher checks `globalThis.browser` before creating a
179
- // new session; if present, it adopts it.
180
- globalThis.browser = browser;
181
- // eslint-disable-next-line no-console
182
- console.log(`[testver-attach] Attached successfully to session ${sid.slice(0, 12)}…`);
183
- } catch (err) {
184
- // eslint-disable-next-line no-console
185
- console.warn(`[testver-attach] Attach failed (${err && err.message}); falling back to fresh session.`);
186
- // Don't throw — let WDIO open a fresh session. Reuse is an
187
- // optimisation, not a hard requirement.
188
- }
189
- }
190
-
191
- /**
192
- * `before` runs per-worker AFTER the session exists (whether WDIO
193
- * created it fresh OR we attached above) and hands us the live
194
- * `browser`. This is where we report the session back to Testver so
195
- * the in-app live preview renders it — covering BOTH the fresh-session
196
- * and reuse cases on the WDIO test-runner path.
197
- */
198
- async before(_capabilities, _specs, browser) {
199
- const b = browser || globalThis.browser;
200
- // A reused session belongs to the AI Assistant: WDIO's end-of-run
201
- // deleteSession (and the test's own) must leave it open.
202
- if (process.env.TESTVER_REUSE_SESSION_ID && b && typeof b.overwriteCommand === 'function') {
203
- try { b.overwriteCommand('deleteSession', async () => undefined); } catch { /* best-effort */ }
204
- }
205
- try { await reportSession(b); } catch { /* best-effort */ }
206
- }
207
-
208
- /** Tell Testver the session is over so the preview stops polling. */
209
- async after() {
210
- try { await unreportSession(); } catch { /* best-effort */ }
211
- }
212
- }
213
-
214
- module.exports = TestverAttachService;
215
- module.exports.default = TestverAttachService;
1
+ /**
2
+ * @testver/wdio-attach-service
3
+ *
4
+ * WebdriverIO launcher service that, when `TESTVER_REUSE_SESSION_ID`
5
+ * is present in the environment, attaches to an existing Appium cloud
6
+ * session instead of letting WDIO open a fresh one. Saves ~30-60s of
7
+ * cloud device boot time and one provider minute per reuse.
8
+ *
9
+ * Plumbed in automatically by Testver's `wdio.testver.conf.{ts,js}`
10
+ * overlay (see src/mobile/cloud-bridge.ts > renderWdioOverlay). The
11
+ * service is only appended to the WDIO `services` array when the env
12
+ * var is set — so non-reuse runs are completely unaffected.
13
+ *
14
+ * How it works
15
+ * ─────────────
16
+ * WDIO's launcher calls `before` on every service before spinning up
17
+ * a session. We monkey-patch `global.browser`-builder by hooking into
18
+ * the `beforeSession` lifecycle: before WDIO POSTs `/session`, we
19
+ * pre-attach to the existing sessionId via `webdriverio.attach()` and
20
+ * stash the result on `global.browser`. WDIO sees a browser already
21
+ * exists and skips its own session creation.
22
+ *
23
+ * This is intentionally implemented as CommonJS (.cjs) so it can be
24
+ * resolved by both TS and JS projects without ESM gymnastics.
25
+ */
26
+
27
+ 'use strict';
28
+
29
+ /**
30
+ * Resolve `webdriverio` from the USER's project, NOT from wherever this
31
+ * vendored .cjs lives (e.g. E:\Testver\dist\wdio-attach-service), which
32
+ * has no node_modules — a bare require() there throws
33
+ * "Cannot find module 'webdriverio'" and the attach silently fails,
34
+ * forcing WDIO into a broken fresh-session fallback. The WDIO run cwd is
35
+ * the user's project (Testver `cd`s into it before invoking wdio), so we
36
+ * resolve relative to that; TESTVER_PROJECT_DIR is preferred when set.
37
+ */
38
+ function loadWebdriverio() {
39
+ const Module = require('node:module');
40
+ const pathMod = require('node:path');
41
+ const bases = [];
42
+ if (process.env.TESTVER_PROJECT_DIR) bases.push(process.env.TESTVER_PROJECT_DIR);
43
+ bases.push(process.cwd());
44
+ for (const base of bases) {
45
+ try {
46
+ const req = Module.createRequire(pathMod.join(base, '__testver_attach_resolver__.cjs'));
47
+ return req('webdriverio');
48
+ } catch (_e) { /* try the next base */ }
49
+ }
50
+ // Last resort: resolve from this service's own location (works if the
51
+ // user happens to have webdriverio hoisted somewhere reachable).
52
+ return require('webdriverio');
53
+ }
54
+
55
+ /**
56
+ * POST the live session back to Testver so the in-app live preview can
57
+ * render it. Mirrors the mocha `--require` bootstrap's reportback, but
58
+ * for the WDIO test-runner path. Fire-and-forget; a failure just means
59
+ * the preview stays empty — the test runs unaffected.
60
+ */
61
+ async function reportSession(browser) {
62
+ const reportUrl = process.env.TESTVER_REPORTBACK_URL;
63
+ const clientId = process.env.TESTVER_CLIENT_ID;
64
+ if (!reportUrl || !clientId || !browser || !browser.sessionId) return;
65
+ if (typeof fetch !== 'function') return;
66
+
67
+ const proto = process.env.APPIUM_HUB_PROTOCOL || 'http';
68
+ const host = process.env.APPIUM_HUB_HOST || '127.0.0.1';
69
+ const port = process.env.APPIUM_HUB_PORT || (proto === 'https' ? '443' : '4723');
70
+ const rawPath = process.env.APPIUM_HUB_PATH || '/';
71
+ const user = encodeURIComponent(process.env.APPIUM_HUB_USER || '');
72
+ const key = encodeURIComponent(process.env.APPIUM_HUB_KEY || '');
73
+ const hubUrl = `${proto}://${user}:${key}@${host}:${port}${rawPath}`;
74
+
75
+ const caps = browser.capabilities || {};
76
+ const body = JSON.stringify({
77
+ clientId,
78
+ sessionId: browser.sessionId,
79
+ hubUrl,
80
+ deviceName: caps['appium:deviceName'] || process.env.TESTVER_DEVICE_NAME,
81
+ platformName: caps.platformName || process.env.TESTVER_PLATFORM_NAME,
82
+ providerId: process.env.TESTVER_PROVIDER,
83
+ // the run that opened it (several runs of one tab side by side)
84
+ runId: process.env.TESTVER_RUN_ID,
85
+ });
86
+ try {
87
+ await fetch(reportUrl.replace(/\/$/, '') + '/api/mobile/session/register-external', {
88
+ method: 'POST',
89
+ headers: { 'Content-Type': 'application/json' },
90
+ body,
91
+ });
92
+ // eslint-disable-next-line no-console
93
+ console.log(`[testver-attach] Reported sessionId ${String(browser.sessionId).slice(0, 12)}… to Testver for live preview`);
94
+ } catch (err) {
95
+ // eslint-disable-next-line no-console
96
+ console.log(`[testver-attach] Reportback failed (live preview may be empty): ${err && err.message}`);
97
+ }
98
+ }
99
+
100
+ /**
101
+ * A local device run: tell Testver which Appium session this test opened,
102
+ * so Auto-Heal can read the device screen and Stop can end the session
103
+ * (Appium 3 does not list its sessions to other programs). Only the
104
+ * session id goes; the run's one-time token proves it is this run.
105
+ */
106
+ async function reportDeviceSession(sessionId) {
107
+ const url = process.env.TESTVER_SESSION_REPORT_URL;
108
+ const token = process.env.TESTVER_SESSION_REPORT_TOKEN;
109
+ const runId = process.env.TESTVER_RUN_ID;
110
+ if (!url || !token || !runId || !sessionId || typeof fetch !== 'function') return;
111
+ try {
112
+ await fetch(url, {
113
+ method: 'POST',
114
+ headers: { 'Content-Type': 'application/json' },
115
+ body: JSON.stringify({ runId, token, sessionId: String(sessionId) }),
116
+ });
117
+ } catch (_) { /* best-effort — capture and Stop clean-up only */ }
118
+ }
119
+
120
+ async function unreportSession() {
121
+ const reportUrl = process.env.TESTVER_REPORTBACK_URL;
122
+ const clientId = process.env.TESTVER_CLIENT_ID;
123
+ if (!reportUrl || !clientId || typeof fetch !== 'function') return;
124
+ try {
125
+ await fetch(reportUrl.replace(/\/$/, '') + '/api/mobile/session/unregister-external', {
126
+ method: 'POST',
127
+ headers: { 'Content-Type': 'application/json' },
128
+ body: JSON.stringify({ clientId }),
129
+ });
130
+ } catch { /* best-effort */ }
131
+ }
132
+
133
+ class TestverAttachService {
134
+ constructor(serviceOptions = {}, capabilities = {}, config = {}) {
135
+ this.serviceOptions = serviceOptions;
136
+ this.capabilities = capabilities;
137
+ this.config = config;
138
+ }
139
+
140
+ /**
141
+ * `onPrepare` runs once per WDIO launch, BEFORE any worker session.
142
+ * We don't attach here — attach happens per-worker in `beforeSession`.
143
+ * But we log clearly so users see reuse is engaged.
144
+ */
145
+ onPrepare() {
146
+ const sid = process.env.TESTVER_REUSE_SESSION_ID;
147
+ if (!sid) return;
148
+ // eslint-disable-next-line no-console
149
+ console.log(`[testver-attach] Reuse engaged — will attach to sessionId=${sid.slice(0, 12)}…`);
150
+ }
151
+
152
+ /**
153
+ * `beforeSession` runs once per worker, BEFORE WDIO creates a session.
154
+ * WDIO's runner (v7–v9) ATTACHES instead of opening a session when the
155
+ * worker's config carries a `sessionId` — so the reused session and the
156
+ * hub it lives on go onto that config. (A browser left on globalThis was
157
+ * never read: WDIO opened a fresh session on the same device, restarting
158
+ * UiAutomator2 under the AI Assistant's live session.)
159
+ */
160
+ async beforeSession(config, _capabilities) {
161
+ const sid = process.env.TESTVER_REUSE_SESSION_ID;
162
+ if (!sid) return; // No reuse — let WDIO open a fresh session.
163
+ if (config && typeof config === 'object') {
164
+ Object.assign(config, {
165
+ sessionId: sid,
166
+ hostname: process.env.APPIUM_HUB_HOST || config.hostname,
167
+ port: Number(process.env.APPIUM_HUB_PORT || config.port || 443),
168
+ protocol: process.env.APPIUM_HUB_PROTOCOL || config.protocol || 'https',
169
+ path: process.env.APPIUM_HUB_PATH || config.path || '/wd/hub',
170
+ user: process.env.APPIUM_HUB_USER || config.user,
171
+ key: process.env.APPIUM_HUB_KEY || config.key,
172
+ });
173
+ // eslint-disable-next-line no-console
174
+ console.log(`[testver-attach] Attaching to session ${sid.slice(0, 12)}…`);
175
+ return;
176
+ }
177
+
178
+ const wdio = loadWebdriverio();
179
+ const attachOpts = {
180
+ sessionId: sid,
181
+ hostname: process.env.APPIUM_HUB_HOST,
182
+ port: Number(process.env.APPIUM_HUB_PORT || '443'),
183
+ protocol: process.env.APPIUM_HUB_PROTOCOL || 'https',
184
+ path: process.env.APPIUM_HUB_PATH || '/wd/hub',
185
+ user: process.env.APPIUM_HUB_USER,
186
+ key: process.env.APPIUM_HUB_KEY,
187
+ // Cap object on attach is informational — WDIO uses it to populate
188
+ // browser.capabilities for test code that reads it.
189
+ capabilities: {
190
+ platformName: process.env.TESTVER_PLATFORM_NAME || 'Android',
191
+ 'appium:deviceName': process.env.TESTVER_DEVICE_NAME,
192
+ 'appium:platformVersion': process.env.TESTVER_PLATFORM_VERSION,
193
+ },
194
+ };
195
+ try {
196
+ const browser = await wdio.attach(attachOpts);
197
+ // Stash on globalThis so WDIO's worker process picks it up.
198
+ // WDIO's launcher checks `globalThis.browser` before creating a
199
+ // new session; if present, it adopts it.
200
+ globalThis.browser = browser;
201
+ // eslint-disable-next-line no-console
202
+ console.log(`[testver-attach] Attached successfully to session ${sid.slice(0, 12)}…`);
203
+ } catch (err) {
204
+ // eslint-disable-next-line no-console
205
+ console.warn(`[testver-attach] Attach failed (${err && err.message}); falling back to fresh session.`);
206
+ // Don't throw — let WDIO open a fresh session. Reuse is an
207
+ // optimisation, not a hard requirement.
208
+ }
209
+ }
210
+
211
+ /**
212
+ * `before` runs per-worker AFTER the session exists (whether WDIO
213
+ * created it fresh OR we attached above) and hands us the live
214
+ * `browser`. This is where we report the session back to Testver so
215
+ * the in-app live preview renders it — covering BOTH the fresh-session
216
+ * and reuse cases on the WDIO test-runner path.
217
+ */
218
+ async before(_capabilities, _specs, browser) {
219
+ const b = browser || globalThis.browser;
220
+ // A reused session belongs to the AI Assistant: WDIO's end-of-run
221
+ // deleteSession (and the test's own) must leave it open.
222
+ if (process.env.TESTVER_REUSE_SESSION_ID && b && typeof b.overwriteCommand === 'function') {
223
+ try { b.overwriteCommand('deleteSession', async () => undefined); } catch { /* best-effort */ }
224
+ }
225
+ try { await reportSession(b); } catch { /* best-effort */ }
226
+ try { await reportDeviceSession(b && b.sessionId); } catch { /* best-effort */ }
227
+ }
228
+
229
+ /** Tell Testver the session is over so the preview stops polling. */
230
+ async after() {
231
+ try { await unreportSession(); } catch { /* best-effort */ }
232
+ }
233
+ }
234
+
235
+ module.exports = TestverAttachService;
236
+ module.exports.default = TestverAttachService;