aboutsummaryrefslogtreecommitdiffstats
path: root/test/runner/browserstack/api.js
blob: 40982c9b3980184e09e44bfc994762083c53109a (plain)
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
/**
 * Browserstack API is documented at
 * https://github.com/browserstack/api
 */

import { createAuthHeader } from "./createAuthHeader.js";

const browserstackApi = "https://api.browserstack.com";
const apiVersion = 5;

const username = process.env.BROWSERSTACK_USERNAME;
const accessKey = process.env.BROWSERSTACK_ACCESS_KEY;

// iOS has null for version numbers,
// and we do not need a similar check for OS versions.
const rfinalVersion = /(?:^[0-9\.]+$)|(?:^null$)/;

const rnonDigits = /(?:[^\d\.]+)|(?:20\d{2})/g;

async function fetchAPI( path, options = {}, versioned = true ) {
	if ( !username || !accessKey ) {
		throw new Error(
			"BROWSERSTACK_USERNAME and BROWSERSTACK_ACCESS_KEY environment variables must be set."
		);
	}
	const init = {
		method: "GET",
		...options,
		headers: {
			authorization: createAuthHeader( username, accessKey ),
			accept: "application/json",
			"content-type": "application/json",
			...options.headers
		}
	};
	const response = await fetch(
		`${ browserstackApi }/${ versioned ? `${ apiVersion }/` : "" }${ path }`,
		init
	);
	if ( !response.ok ) {
		console.log(
			`\n${ init.method } ${ path }`,
			response.status,
			response.statusText
		);
		throw new Error( `Error fetching ${ path }` );
	}
	return response.json();
}

/**
 * =============================
 * Browsers API
 * =============================
 */

function compareVersionNumbers( a, b ) {
	if ( a != null && b == null ) {
		return -1;
	}
	if ( a == null && b != null ) {
		return 1;
	}
	if ( a == null && b == null ) {
		return 0;
	}
	const aParts = a.replace( rnonDigits, "" ).split( "." );
	const bParts = b.replace( rnonDigits, "" ).split( "." );

	if ( aParts.length > bParts.length ) {
		return -1;
	}
	if ( aParts.length < bParts.length ) {
		return 1;
	}

	for ( let i = 0; i < aParts.length; i++ ) {
		const aPart = Number( aParts[ i ] );
		const bPart = Number( bParts[ i ] );
		if ( aPart < bPart ) {
			return -1;
		}
		if ( aPart > bPart ) {
			return 1;
		}
	}
}

function sortBrowsers( a, b ) {
	if ( a.browser < b.browser ) {
		return -1;
	}
	if ( a.browser > b.browser ) {
		return 1;
	}
	const browserComparison = compareVersionNumbers(
		a.browser_version,
		b.browser_version
	);
	if ( browserComparison ) {
		return browserComparison;
	}
	if ( a.os < b.os ) {
		return -1;
	}
	if ( a.os > b.os ) {
		return 1;
	}
	const osComparison = compareVersionNumbers( a.os_version, b.os_version );
	if ( osComparison ) {
		return osComparison;
	}
	const deviceComparison = compareVersionNumbers( a.device, b.device );
	if ( deviceComparison ) {
		return deviceComparison;
	}
	return 0;
}

export async function getBrowsers( { flat = false } = {} ) {
	const query = new URLSearchParams();
	if ( flat ) {
		query.append( "flat", true );
	}
	const browsers = await fetchAPI( `/browsers?${ query }` );
	return browsers.sort( sortBrowsers );
}

function matchVersion( browserVersion, version ) {
	if ( !version ) {
		return false;
	}
	const regex = new RegExp(
		`^${ version.replace( /\\/g, "\\\\" ).replace( /\./g, "\\." ) }\\b`,
		"i"
	);
	return regex.test( browserVersion );
}

export async function filterBrowsers( filter ) {
	const browsers = await getBrowsers( { flat: true } );
	if ( !filter ) {
		return browsers;
	}
	const filterBrowser = ( filter.browser ?? "" ).toLowerCase();
	const filterVersion = ( filter.browser_version ?? "" ).toLowerCase();
	const filterOs = ( filter.os ?? "" ).toLowerCase();
	const filterOsVersion = ( filter.os_version ?? "" ).toLowerCase();
	const filterDevice = ( filter.device ?? "" ).toLowerCase();

	return browsers.filter( ( browser ) => {
		return (
			( !filterBrowser || filterBrowser === browser.browser.toLowerCase() ) &&
			( !filterVersion ||
				matchVersion( browser.browser_version, filterVersion ) ) &&
			( !filterOs || filterOs === browser.os.toLowerCase() ) &&
			( !filterOsVersion ||
				filterOsVersion === browser.os_version.toLowerCase() ) &&
			( !filterDevice || filterDevice === ( browser.device || "" ).toLowerCase() )
		);
	} );
}

export async function listBrowsers( filter ) {
	const browsers = await filterBrowsers( filter );
	console.log( "Available browsers:" );
	for ( const browser of browsers ) {
		let message = `    ${ browser.browser }_`;
		if ( browser.device ) {
			message += `:${ browser.device }_`;
		} else {
			message += `${ browser.browser_version }_`;
		}
		message += `${ browser.os }_${ browser.os_version }`;
		console.log( message );
	}
}

export async function getLatestBrowser( filter ) {
	const browsers = await filterBrowsers( filter );

	// The list is sorted in ascending order,
	// so the last item is the latest.
	return browsers.findLast( ( browser ) =>
		rfinalVersion.test( browser.browser_version )
	);
}

/**
 * =============================
 * Workers API
 * =============================
 */

/**
 * A browser object may only have one of `browser` or `device` set;
 * which property is set will depend on `os`.
 *
 * `options`: is an object with the following properties:
 *   `os`: The operating system.
 *   `os_version`: The operating system version.
 *   `browser`: The browser name.
 *   `browser_version`: The browser version.
 *   `device`: The device name.
 *   `url` (optional): Which URL to navigate to upon creation.
 *   `timeout` (optional): Maximum life of the worker (in seconds). Maximum value of `1800`. Specifying `0` will use the default of `300`.
 *   `name` (optional): Provide a name for the worker.
 *   `build` (optional): Group workers into a build.
 *   `project` (optional): Provide the project the worker belongs to.
 *   `resolution` (optional): Specify the screen resolution (e.g. "1024x768").
 *   `browserstack.local` (optional): Set to `true` to mark as local testing.
 *   `browserstack.video` (optional): Set to `false` to disable video recording.
 *   `browserstack.localIdentifier` (optional): ID of the local tunnel.
 */
export function createWorker( options ) {
	return fetchAPI( "/worker", {
		method: "POST",
		body: JSON.stringify( options )
	} );
}

/**
 * Returns a worker object, if one exists, with the following properties:
 *   `id`: The worker id.
 *   `status`: A string representing the current status of the worker.
 *     Possible statuses: `"running"`, `"queue"`.
 */
export function getWorker( id ) {
	return fetchAPI( `/worker/${ id }` );
}

export async function deleteWorker( id, verbose ) {
	await fetchAPI( `/worker/${ id }`, { method: "DELETE" } );
	if ( verbose ) {
		console.log( `\nWorker ${ id } stopped.` );
	}
}

export function getWorkers() {
	return fetchAPI( "/workers" );
}

/**
 * Change the URL of a worker,
 * or refresh if it's the same URL.
 */
export function changeUrl( id, url ) {
	return fetchAPI( `/worker/${ id }/url.json`, {
		method: "PUT",
		body: JSON.stringify( {
			timeout: 20,
			url: encodeURI( url )
		} )
	} );
}

/**
 * Stop all workers
 */
export async function stopWorkers() {
	const workers = await getWorkers();

	// Run each request on its own
	// to avoid connect timeout errors.
	for ( const worker of workers ) {
		try {
			await deleteWorker( worker.id, true );
		} catch ( error ) {

			// Log the error, but continue trying to remove workers.
			console.error( error );
		}
	}
}

/**
 * =============================
 * Plan API
 * =============================
 */

export function getPlan() {
	return fetchAPI( "/automate/plan.json", {}, false );
}

export async function getAvailableSessions() {
	const [ plan, workers ] = await Promise.all( [ getPlan(), getWorkers() ] );
	return plan.parallel_sessions_max_allowed - workers.length;
}