Repository navigation
Expand file tree
/
Copy pathagent-device.js
More file actions
337 lines (314 loc) · 14.7 KB
/
Copy pathagent-device.js
File metadata and controls
337 lines (314 loc) · 14.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
/**
* TestingBot provider plugin for agent-device (plugin API 2): describes
* TestingBot's Appium hub as a cloud WebDriver service, and agent-device
* builds and drives the session from that description.
*
* Shipped inside `@testingbot/e2e` and registered in each lease daemon's home
* by `testingbot()`; it can also be installed on its own for
* `agent-device connect testingbot`.
*
* Plain ESM without dependencies, so the daemon can load it from wherever it
* is linked.
*/
import { openAsBlob, statSync } from 'node:fs';
import path from 'node:path';
const PROVIDER = 'testingbot';
const LABEL = 'TestingBot';
const KEY = 'TESTINGBOT_KEY';
const SECRET = 'TESTINGBOT_SECRET';
const DEFAULT_HUB = 'https://hub.testingbot.com/wd/hub/';
const DEFAULT_API = 'https://api.testingbot.com/v1';
const REQUEST_TIMEOUT_MS = 15_000;
const UPLOAD_TIMEOUT_MS = 10 * 60_000;
/** What the plugin does with each agent-device provider profile field; a field it refuses fails the lease when set. */
const PROFILE_FIELDS = {
provider: PROVIDER,
label: LABEL,
fields: {
providerApp: 'consumed',
providerOsVersion: 'consumed',
providerDeviceType: 'consumed',
// TestingBot groups sessions by build only.
providerProject: 'refused',
providerBuild: 'consumed',
providerSessionName: 'consumed',
providerDeviceOrientation: 'consumed',
providerGeoLocation: 'consumed',
providerTimezone: 'consumed',
providerAppiumVersion: 'consumed',
providerLanguage: 'consumed',
providerLocale: 'consumed',
providerNetworkProfile: 'refused',
providerCustomNetwork: 'refused',
providerNoResignApp: 'refused',
providerNetworkLogs: 'refused',
providerNetworkHosts: 'refused',
awsProjectArn: 'refused',
awsDeviceArn: 'refused',
awsAppArn: 'refused',
awsRegion: 'refused',
awsInteractionMode: 'refused',
},
};
const CAPABILITY_OVERRIDES = {
install: { support: 'unsupported', note: 'TestingBot installs the app named by --provider-app when the session starts.' },
portReverse: { support: 'unsupported', note: 'Use TestingBot Tunnel for network access to local hosts; agent-device port reverse is not available.' },
artifacts: { support: 'unsupported', note: 'Session video and logs are on the TestingBot dashboard.' },
};
const CONNECTION_CAPABILITIES = {
leaseKind: 'direct-device-provider',
requiresAppAttachment: false,
requiresRemoteDaemon: false,
supportsArtifacts: false,
supportsDeferredAppSelection: false,
supportsDirectPortReverse: false,
usesCloudWebDriverLease: true,
holdsCloudDevice: true,
};
/**
* The plugin factory. `options.credentials` lets a JS host pass the key and
* secret directly instead of through the environment.
*
* @param {{ credentials?: { key?: string, secret?: string } }} [options]
*/
export default function testingbotPlugin(options = {}) {
const { credentials } = options;
/** The host with any factory credentials put on its environment. */
const withCredentials = (host) =>
credentials
? { ...host, env: { ...host.env, ...(credentials.key ? { [KEY]: credentials.key } : {}), ...(credentials.secret ? { [SECRET]: credentials.secret } : {}) } }
: host;
return {
apiVersion: 2,
provider: PROVIDER,
credentials: { variables: [...(credentials?.key ? [] : [KEY]), ...(credentials?.secret ? [] : [SECRET])] },
connection: {
capabilities: CONNECTION_CAPABILITIES,
resolve: (context) => resolveConnection(context, withCredentials(context.host)),
verify: (context) => verifyConnection(context, withCredentials(context.host)),
},
setup: (host) => ({ webDriver: createWebDriver(withCredentials(host)) }),
};
}
/**
* A lease holds its device for the whole run, so the session must outlive the
* gaps e2e leaves in it: the other targets leasing before tests start (each
* may wait minutes for a device), and setup between test files. TestingBot's
* defaults (120 s idle, 30 min in all) would end it during either. The hub
* caps both at 7200 s.
*/
const IDLE_TIMEOUT_SECONDS = 900;
const MAX_DURATION_SECONDS = 7200;
/** The cloud WebDriver descriptor agent-device builds TestingBot sessions from. */
export function createWebDriver(host) {
const { env } = host;
return {
provider: PROVIDER,
profileFields: PROFILE_FIELDS,
platform: 'android',
deviceName: 'TestingBot device',
endpoint: env.TESTINGBOT_WEBDRIVER_ENDPOINT ?? DEFAULT_HUB,
capabilityOverrides: CAPABILITY_OVERRIDES,
// TestingBot allocates the device inside the create-session request.
requestPolicy: { sessionCreateTimeoutMs: 10 * 60_000 },
prepareSession: async ({ req, lease, base }) => {
const flags = req?.flags;
if (!flags) throw host.createError('INVALID_ARGS', `${LABEL} lease allocation requires provider profile flags on the request.`);
const platform = requirePlatform(host, flags);
const deviceName = requireFlag(host, flags, 'device', `${LABEL} requires --device <name>.`);
const osVersion = requireFlag(host, flags, 'providerOsVersion', `${LABEL} requires --provider-os-version <version>.`);
const appSource = requireFlag(host, flags, 'providerApp', `${LABEL} requires --provider-app <tb:// app URL, https URL, or local path>.`);
const auth = requireCredentials(host);
const app = await resolveApp(host, appSource, { cwd: req.cwd ?? process.cwd(), signal: req.signal, auth });
return {
...base,
platform,
deviceName,
auth: { username: auth.key, accessKey: auth.secret },
webdriverCapabilities: testingbotCapabilities({
platform,
deviceName,
osVersion,
app,
deviceType: deviceTypeOf(host, flags),
build: stringFlag(flags, 'providerBuild') ?? lease.runId,
name: stringFlag(flags, 'providerSessionName') ?? lease.leaseId,
flags,
}),
};
},
};
}
/**
* The W3C capabilities of one TestingBot Appium session
* (https://testingbot.com/support/app-automate/appium/options).
*/
export function testingbotCapabilities({ platform, deviceName, osVersion, app, deviceType, build, name, flags }) {
const orientation = stringFlag(flags, 'providerDeviceOrientation');
const locale = stringFlag(flags, 'providerLocale');
const language = stringFlag(flags, 'providerLanguage');
const geo = stringFlag(flags, 'providerGeoLocation');
const timeZone = stringFlag(flags, 'providerTimezone');
const appiumVersion = stringFlag(flags, 'providerAppiumVersion');
return {
platformName: platform === 'ios' ? 'iOS' : 'Android',
'appium:automationName': platform === 'ios' ? 'XCUITest' : 'UiAutomator2',
'appium:deviceName': deviceName,
'appium:platformVersion': osVersion,
'appium:app': app,
...(orientation ? { 'appium:orientation': orientation.toUpperCase() } : {}),
...(locale ? { 'appium:locale': locale } : {}),
...(language ? { 'appium:language': language } : {}),
'tb:options': {
name,
build,
idletimeout: IDLE_TIMEOUT_SECONDS,
maxduration: MAX_DURATION_SECONDS,
...(deviceType === 'real' ? { realDevice: true } : {}),
...(appiumVersion ? { appiumVersion } : {}),
...(timeZone ? { timeZone } : {}),
...(geo ? { 'testingbot.geoCountryCode': geo } : {}),
},
};
}
/** `agent-device connect testingbot`: the profile the flags describe. */
function resolveConnection({ flags, cwd }, host) {
refuseFlags(host, flags);
requireCredentials(host);
const platform = requirePlatform(host, flags);
const appSource = requireFlag(host, flags, 'providerApp', `connect ${PROVIDER} requires --provider-app <tb:// app URL, https URL, or local path>.`);
const providerApp = isRemoteApp(appSource) ? appSource : localApp(host, appSource, cwd);
return {
profile: {
leaseProvider: PROVIDER,
platform,
device: requireFlag(host, flags, 'device', `connect ${PROVIDER} requires --device <name>.`),
providerOsVersion: requireFlag(host, flags, 'providerOsVersion', `connect ${PROVIDER} requires --provider-os-version <version>.`),
providerApp,
providerDeviceType: deviceTypeOf(host, flags),
providerBuild: flags.providerBuild,
providerSessionName: flags.providerSessionName,
...pickFeatureFlags(flags),
},
extraFlags: { providerApp },
};
}
/** `agent-device connect testingbot`: checks the credentials and, for a `tb://` app, that it is in the account's storage. */
async function verifyConnection({ flags }, host) {
const auth = requireCredentials(host);
const api = apiEndpoint(host);
await requestJson(host, new URL(`${api}/user`), auth, { method: 'GET' }, undefined, `${LABEL} credential check`);
const app = stringFlag(flags, 'providerApp') ?? '';
let appStatus;
if (app.startsWith('tb://')) {
const body = await requestJson(host, new URL(`${api}/storage/${encodeURIComponent(app.slice('tb://'.length))}`), auth, { method: 'GET' }, undefined, `${LABEL} app lookup`);
appStatus = { status: 'verified', reference: app, ...(typeof body.name === 'string' ? { name: body.name } : {}), ...(typeof body.version === 'string' ? { version: body.version } : {}) };
} else if (/^https:\/\//i.test(app)) {
appStatus = { status: 'configured', reference: app, message: 'Public app URL configured; TestingBot downloads it when creating the session.' };
} else {
appStatus = { status: 'configured', name: path.basename(app), reference: app, message: 'Local app is uploaded to TestingBot Storage when creating the session.' };
}
const platform = requirePlatform(host, flags);
return {
provider: PROVIDER,
service: LABEL,
verificationMessage: appStatus.status === 'verified' ? 'Credentials and uploaded app verified; device availability is checked when the session is created.' : 'Credentials verified; device and app are checked when the session is created.',
device: { status: 'configured', name: flags.device, platform, osVersion: flags.providerOsVersion },
app: appStatus,
};
}
/** A `tb://` URL or https URL as written; a local file uploaded to TestingBot Storage. */
async function resolveApp(host, source, { cwd, signal, auth }) {
if (isRemoteApp(source)) return source;
const file = localApp(host, source, cwd);
const form = new FormData();
form.set('file', await openAsBlob(file), path.basename(file));
const body = await requestJson(host, new URL(`${apiEndpoint(host)}/storage`), auth, { method: 'POST', body: form }, signal, `${LABEL} upload of ${path.basename(file)}`, UPLOAD_TIMEOUT_MS);
if (typeof body.app_url !== 'string' || !body.app_url.startsWith('tb://')) {
throw host.createError('COMMAND_FAILED', `${LABEL} upload of ${path.basename(file)} returned no tb:// app_url.`);
}
return body.app_url;
}
function isRemoteApp(source) {
return /^tb:\/\/[\w.-]+$/.test(source) || /^https:\/\//i.test(source);
}
function localApp(host, source, cwd) {
const file = path.resolve(cwd, source);
if (statSync(file, { throwIfNoEntry: false })?.isFile()) return file;
throw host.createError('INVALID_ARGS', `${LABEL} app file not found: ${file}`, { hint: 'Pass a tb:// app URL, an https URL, or the path of an .apk, .aab, .ipa, or zipped .app.' });
}
function requireCredentials(host) {
const key = host.env[KEY]?.trim() || host.env.TB_KEY?.trim();
const secret = host.env[SECRET]?.trim() || host.env.TB_SECRET?.trim();
if (key && secret) return { key, secret };
throw host.createError('INVALID_ARGS', `${LABEL} requires ${KEY} and ${SECRET} in the environment.`);
}
function apiEndpoint(host) {
return (host.env.TESTINGBOT_API_ENDPOINT?.trim() || DEFAULT_API).replace(/\/+$/, '');
}
function requirePlatform(host, flags) {
const platform = flags?.platform;
if (platform === 'android' || platform === 'ios') return platform;
throw host.createError('INVALID_ARGS', `${LABEL} requires --platform ios|android.`);
}
function requireFlag(host, flags, name, message) {
const value = stringFlag(flags, name);
if (value) return value;
throw host.createError('INVALID_ARGS', message);
}
function stringFlag(flags, name) {
const value = flags?.[name];
return typeof value === 'string' && value.length > 0 ? value : undefined;
}
function deviceTypeOf(host, flags) {
const value = flags?.providerDeviceType;
if (value === undefined || value === '') return 'virtual';
if (value === 'virtual' || value === 'real') return value;
throw host.createError('INVALID_ARGS', `Invalid --provider-device-type value: ${String(value)}.`, { hint: 'Use virtual|real.', flag: '--provider-device-type' });
}
const FEATURE_FLAGS = ['providerDeviceOrientation', 'providerGeoLocation', 'providerTimezone', 'providerAppiumVersion', 'providerLanguage', 'providerLocale'];
function pickFeatureFlags(flags) {
const picked = {};
for (const name of FEATURE_FLAGS) {
const value = stringFlag(flags, name);
if (value) picked[name] = value;
}
return picked;
}
function refuseFlags(host, flags) {
const refused = Object.keys(PROFILE_FIELDS.fields).filter((name) => PROFILE_FIELDS.fields[name] === 'refused' && flags?.[name] != null && flags[name] !== false && flags[name] !== '');
if (refused.length === 0) return;
throw host.createError('INVALID_ARGS', `${refused.join(', ')} ${refused.length === 1 ? 'is' : 'are'} not supported by ${LABEL}.`, { provider: PROVIDER });
}
/** One authenticated request answered with a JSON object; errors carry the status and API message, never the credentials. */
async function requestJson(host, url, { key, secret }, init, signal, what, timeoutMs = REQUEST_TIMEOUT_MS) {
const timeout = AbortSignal.timeout(timeoutMs);
let response;
let text;
try {
response = await fetch(url, {
...init,
headers: { Authorization: `Basic ${Buffer.from(`${key}:${secret}`).toString('base64')}`, Accept: 'application/json', 'User-Agent': `agent-device-testingbot/${host.clientVersion}` },
signal: signal ? AbortSignal.any([signal, timeout]) : timeout,
});
text = await response.text();
} catch (cause) {
throw host.createError('COMMAND_FAILED', `${what} failed: ${timeout.aborted ? `no answer within ${Math.round(timeoutMs / 1000)} s` : cause instanceof Error ? cause.message : String(cause)}`);
}
let body;
try {
const parsed = JSON.parse(text);
body = typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed) ? parsed : undefined;
} catch {
body = undefined;
}
if (!response.ok) {
const message = body?.error ?? body?.message;
throw host.createError('COMMAND_FAILED', `${what} failed: HTTP ${response.status}${typeof message === 'string' && message ? ` (${message.slice(0, 200)})` : ''}`, {
status: response.status,
...(response.status === 401 ? { hint: `Check ${KEY} and ${SECRET}.` } : {}),
});
}
if (!body) throw host.createError('COMMAND_FAILED', `${what} failed: HTTP ${response.status}, not JSON`);
return body;
}