webdriver-installer 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,227 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
203
+
204
+ -----
205
+
206
+ Contains code from https://github.com/mozilla/language-mapping-list
207
+
208
+ The MIT License (MIT)
209
+
210
+ Copyright (c) 2013 Ali Al Dallal
211
+
212
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
213
+ this software and associated documentation files (the "Software"), to deal in
214
+ the Software without restriction, including without limitation the rights to
215
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
216
+ the Software, and to permit persons to whom the Software is furnished to do so,
217
+ subject to the following conditions:
218
+
219
+ The above copyright notice and this permission notice shall be included in all
220
+ copies or substantial portions of the Software.
221
+
222
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
223
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
224
+ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
225
+ COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
226
+ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
227
+ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,39 @@
1
+ # WebDriver Installer for NodeJS
2
+
3
+ Install the right WebDriver version for your local browsers, automatically.
4
+
5
+ This tool will check the versions of your local browsers, determine the correct
6
+ version of each corresponding WebDriver binary, and download and install the
7
+ driver binaries automatically.
8
+
9
+ It can be run as a command-line tool, or as a Node module.
10
+
11
+
12
+ ## Installation
13
+
14
+ To install the tool globally for CLI usage:
15
+
16
+ ```sh
17
+ npm install -g webdriver-installer
18
+ ```
19
+
20
+
21
+ ## CLI Usage
22
+
23
+ Here's an example of CLI usage:
24
+
25
+ ```sh
26
+ webdriver-installer /path/to/webdriver-binaries/
27
+ ```
28
+
29
+
30
+ ## Module Usage
31
+
32
+ ```js
33
+ const {installWebDrivers} = require('webdriver-installer');
34
+
35
+ async function foo() {
36
+ const withLogging = true;
37
+ await installWebDrivers('/path/to/webdriver-binaries/', withLogging);
38
+ }
39
+ ```
package/base.js ADDED
@@ -0,0 +1,60 @@
1
+ /*! @license
2
+ * WebDriver Installer
3
+ * Copyright 2022 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ /**
8
+ * Throw an error if the subclass doesn't override an abstract method.
9
+ */
10
+ function unimplemented(object, callee) {
11
+ throw new Error(
12
+ `Unimplemented: ${callee.name} in ${object.constructor.name}`);
13
+ }
14
+
15
+ /**
16
+ * An abstract base class for WebDriver installers.
17
+ */
18
+ class WebDriverInstallerBase {
19
+ /** @return {string} */
20
+ getBrowserName() {
21
+ unimplemented(this, arguments.callee);
22
+ }
23
+
24
+ /** @return {string} */
25
+ getDriverName() {
26
+ unimplemented(this, arguments.callee);
27
+ }
28
+
29
+ /** @return {!Promise<?string>} */
30
+ async getInstalledBrowserVersion() {
31
+ unimplemented(this, arguments.callee);
32
+ }
33
+
34
+ /**
35
+ * @param {string} outputDirectory
36
+ * @return {!Promise<?string>}
37
+ */
38
+ async getInstalledDriverVersion(outputDirectory) {
39
+ unimplemented(this, arguments.callee);
40
+ }
41
+
42
+ /**
43
+ * @param {string} browserVersion
44
+ * @return {!Promise<string>}
45
+ */
46
+ async getBestDriverVersion(browserVersion) {
47
+ unimplemented(this, arguments.callee);
48
+ }
49
+
50
+ /**
51
+ * @param {string} driverVersion
52
+ * @param {string} outputDirectory
53
+ * @return {!Promise}
54
+ */
55
+ async install(driverVersion, outputDirectory) {
56
+ unimplemented(this, arguments.callee);
57
+ }
58
+ }
59
+
60
+ module.exports = {WebDriverInstallerBase};
@@ -0,0 +1,30 @@
1
+ /*! @license
2
+ * WebDriver Installer
3
+ * Copyright 2022 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ const {ChromeWebDriverInstaller} = require('./chrome.js');
8
+ const {InstallerUtils} = require('./utils.js');
9
+
10
+ /**
11
+ * An installer for chromedriver for Chrome on Android.
12
+ */
13
+ class ChromeAndroidWebDriverInstaller extends ChromeWebDriverInstaller {
14
+ /** @return {string} */
15
+ getBrowserName() {
16
+ return 'Chrome on Android';
17
+ }
18
+
19
+ /** @return {string} */
20
+ getDriverName() {
21
+ return 'chromedriver-android';
22
+ }
23
+
24
+ /** @return {!Promise<?string>} */
25
+ async getInstalledBrowserVersion() {
26
+ return await InstallerUtils.getAndroidAppVersion('com.android.chrome');
27
+ }
28
+ }
29
+
30
+ module.exports = {ChromeAndroidWebDriverInstaller};
package/chrome.js ADDED
@@ -0,0 +1,111 @@
1
+ /*! @license
2
+ * WebDriver Installer
3
+ * Copyright 2022 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ const {WebDriverInstallerBase} = require('./base.js');
8
+ const {InstallerUtils} = require('./utils.js');
9
+
10
+ const os = require('os');
11
+ const path = require('path');
12
+
13
+ const CDN_URL = 'https://chromedriver.storage.googleapis.com';
14
+
15
+ /**
16
+ * An installer for chromedriver for desktop Chrome.
17
+ */
18
+ class ChromeWebDriverInstaller extends WebDriverInstallerBase {
19
+ /** @return {string} */
20
+ getBrowserName() {
21
+ return 'Chrome';
22
+ }
23
+
24
+ /** @return {string} */
25
+ getDriverName() {
26
+ return 'chromedriver';
27
+ }
28
+
29
+ /** @return {!Promise<?string>} */
30
+ async getInstalledBrowserVersion() {
31
+ if (os.platform() == 'linux') {
32
+ const output = await InstallerUtils.getCommandOutputOrNullIfMissing(
33
+ ['google-chrome', '--version']);
34
+ // Output is a string like "Google Chrome 96.0.4664.110\n"
35
+ return output ? output.trim().split(' ')[2] : null;
36
+ } else if (os.platform() == 'darwin') {
37
+ return await InstallerUtils.getMacAppVersion('Google Chrome');
38
+ } else if (os.platform() == 'win32') {
39
+ return await InstallerUtils.getWindowsRegistryVersion(
40
+ 'HKEY_CURRENT_USER\\Software\\Google\\Chrome\\BLBeacon',
41
+ 'version');
42
+ } else {
43
+ throw new Error(`Unrecognized platform: ${os.platform()}`);
44
+ }
45
+ }
46
+
47
+ /**
48
+ * @param {string} outputDirectory
49
+ * @return {!Promise<?string>}
50
+ */
51
+ async getInstalledDriverVersion(outputDirectory) {
52
+ // NOTE: Using path.join here would also normalize the path, which would
53
+ // turn something like "./chromedriver" into "chromedriver", which would
54
+ // fail to execute.
55
+ const outputPath = outputDirectory + path.sep + this.getDriverName();
56
+
57
+ const output = await InstallerUtils.getCommandOutputOrNullIfMissing(
58
+ [outputPath, '--version']);
59
+ // Output is a string like "ChromeDriver 98.0.4758.48 (gitref)\n"
60
+ return output ? output.trim().split(' ')[1] : null;
61
+ }
62
+
63
+ /**
64
+ * @param {string} browserVersion
65
+ * @return {!Promise<string>}
66
+ */
67
+ async getBestDriverVersion(browserVersion) {
68
+ const majorVersion = browserVersion.split('.')[0];
69
+ const versionUrl = `${CDN_URL}/LATEST_RELEASE_${majorVersion}`;
70
+ return await InstallerUtils.fetchVersionUrl(versionUrl);
71
+ }
72
+
73
+ /**
74
+ * @param {string} driverVersion
75
+ * @param {string} outputDirectory
76
+ * @param {string=} outputName
77
+ * @return {!Promise}
78
+ */
79
+ async install(driverVersion, outputDirectory) {
80
+ let platform;
81
+
82
+ if (os.platform() == 'linux') {
83
+ platform = 'linux64';
84
+ } else if (os.platform() == 'darwin') {
85
+ platform = 'mac64';
86
+ } else if (os.platform() == 'win32') {
87
+ platform = 'win32';
88
+ } else {
89
+ throw new Error(`Unrecognized platform: ${os.platform()}`);
90
+ }
91
+
92
+ const archiveUrl =
93
+ `${CDN_URL}/${driverVersion}/chromedriver_${platform}.zip`;
94
+
95
+ let binaryName = 'chromedriver';
96
+ if (os.platform() == 'win32') {
97
+ binaryName += '.exe';
98
+ }
99
+
100
+ let outputName = this.getDriverName();
101
+ if (os.platform() == 'win32') {
102
+ outputName += '.exe';
103
+ }
104
+
105
+ return await InstallerUtils.installBinary(
106
+ archiveUrl, binaryName, outputName,
107
+ outputDirectory, /* isZip= */ true);
108
+ }
109
+ }
110
+
111
+ module.exports = {ChromeWebDriverInstaller};
package/edge.js ADDED
@@ -0,0 +1,77 @@
1
+ /*! @license
2
+ * WebDriver Installer
3
+ * Copyright 2022 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ const {WebDriverInstallerBase} = require('./base.js');
8
+ const {InstallerUtils} = require('./utils.js');
9
+
10
+ const os = require('os');
11
+ const path = require('path');
12
+
13
+ const CDN_URL = 'https://msedgedriver.azureedge.net/';
14
+
15
+ /**
16
+ * An installer for msedgedriver for desktop Edge.
17
+ */
18
+ class EdgeWebDriverInstaller extends WebDriverInstallerBase {
19
+ /** @return {string} */
20
+ getBrowserName() {
21
+ return 'Edge';
22
+ }
23
+
24
+ /** @return {string} */
25
+ getDriverName() {
26
+ return 'msedgedriver';
27
+ }
28
+
29
+ /** @return {!Promise<?string>} */
30
+ async getInstalledBrowserVersion() {
31
+ return await InstallerUtils.getWindowsExeVersion(
32
+ 'C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe');
33
+ }
34
+
35
+ /**
36
+ * @param {string} outputDirectory
37
+ * @return {!Promise<?string>}
38
+ */
39
+ async getInstalledDriverVersion(outputDirectory) {
40
+ // NOTE: Using path.join here would also normalize the path, which would
41
+ // turn something like "./msedgedriver" into "msedgedriver", which would
42
+ // fail to execute.
43
+ const outputPath = outputDirectory + path.sep + this.getDriverName();
44
+
45
+ const output = await InstallerUtils.getCommandOutputOrNullIfMissing(
46
+ [outputPath, '--version']);
47
+ // Output is a string like "MSEdgeDriver 96.0.1054.62 (sha1)\n"
48
+ return output ? output.trim().split(' ')[1] : null;
49
+ }
50
+
51
+ /**
52
+ * @param {string} browserVersion
53
+ * @return {!Promise<string>}
54
+ */
55
+ async getBestDriverVersion(browserVersion) {
56
+ const majorVersion = browserVersion.split('.')[0];
57
+ const versionUrl = `${CDN_URL}/LATEST_RELEASE_${majorVersion}`;
58
+ return await InstallerUtils.fetchVersionUrl(versionUrl, 'UTF-16LE');
59
+ }
60
+
61
+ /**
62
+ * @param {string} driverVersion
63
+ * @param {string} outputDirectory
64
+ * @param {string=} outputName
65
+ * @return {!Promise}
66
+ */
67
+ async install(driverVersion, outputDirectory) {
68
+ const archiveUrl = `${CDN_URL}/${driverVersion}/edgedriver_win64.zip`;
69
+ const binaryName = 'msedgedriver.exe';
70
+ const outputName = this.getDriverName() + '.exe';
71
+ return await InstallerUtils.installBinary(
72
+ archiveUrl, binaryName, outputName,
73
+ outputDirectory, /* isZip= */ true);
74
+ }
75
+ }
76
+
77
+ module.exports = {EdgeWebDriverInstaller};
package/firefox.js ADDED
@@ -0,0 +1,124 @@
1
+ /*! @license
2
+ * WebDriver Installer
3
+ * Copyright 2022 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ const {WebDriverInstallerBase} = require('./base.js');
8
+ const {InstallerUtils} = require('./utils.js');
9
+
10
+ const os = require('os');
11
+ const path = require('path');
12
+
13
+ /**
14
+ * An installer for chromedriver for desktop Firefox.
15
+ */
16
+ class FirefoxWebDriverInstaller extends WebDriverInstallerBase {
17
+ /** @return {string} */
18
+ getBrowserName() {
19
+ return 'Firefox';
20
+ }
21
+
22
+ /** @return {string} */
23
+ getDriverName() {
24
+ return 'geckodriver';
25
+ }
26
+
27
+ /** @return {!Promise<?string>} */
28
+ async getInstalledBrowserVersion() {
29
+ if (os.platform() == 'linux') {
30
+ const output = await InstallerUtils.getCommandOutputOrNullIfMissing(
31
+ ['firefox', '-v']);
32
+ // Output is a string like "Mozilla Firefox 96.0"
33
+ return output ? output.trim().split(' ')[2] : null;
34
+ } else if (os.platform() == 'darwin') {
35
+ return await InstallerUtils.getMacAppVersion('Firefox');
36
+ } else if (os.platform() == 'win32') {
37
+ return await InstallerUtils.getWindowsRegistryVersion(
38
+ 'HKLM\\SOFTWARE\\Mozilla\\Mozilla Firefox',
39
+ 'CurrentVersion')
40
+ } else {
41
+ throw new Error(`Unrecognized platform: ${os.platform()}`);
42
+ }
43
+ }
44
+
45
+ /**
46
+ * @param {string} outputDirectory
47
+ * @return {!Promise<?string>}
48
+ */
49
+ async getInstalledDriverVersion(outputDirectory) {
50
+ // NOTE: Using path.join here would also normalize the path, which would
51
+ // turn something like "./geckodriver" into "geckodriver", which would
52
+ // fail to execute.
53
+ const outputPath = outputDirectory + path.sep + this.getDriverName();
54
+
55
+ const output = await InstallerUtils.getCommandOutputOrNullIfMissing(
56
+ [outputPath, '--version']);
57
+ // Output is a string like "geckodriver 0.30.0 (sha1 date)\n"
58
+ return output ? output.trim().split(' ')[1] : null;
59
+ }
60
+
61
+ /**
62
+ * @param {string} browserVersion
63
+ * @return {!Promise<string>}
64
+ */
65
+ async getBestDriverVersion(browserVersion) {
66
+ // NOTE: geckodriver is currently independent of Firefox versions.
67
+ const tag =
68
+ await InstallerUtils.fetchLatestGitHubTag('mozilla/geckodriver');
69
+ // NOTE: tags start with "v", but the version number reported by the binary
70
+ // does not. So that they can be directly compared, strip the "v" from the
71
+ // tag.
72
+ console.assert(tag[0] == 'v');
73
+ return tag.substr(1);
74
+ }
75
+
76
+ /**
77
+ * @param {string} driverVersion
78
+ * @param {string} outputDirectory
79
+ * @param {string=} outputName
80
+ * @return {!Promise}
81
+ */
82
+ async install(driverVersion, outputDirectory) {
83
+ let platform;
84
+ let extension;
85
+ let isZip;
86
+
87
+ if (os.platform() == 'linux') {
88
+ platform = 'linux64';
89
+ extension = 'tar.gz';
90
+ isZip = false;
91
+ } else if (os.platform() == 'darwin') {
92
+ platform = 'macos';
93
+ extension = 'tar.gz';
94
+ isZip = false;
95
+ } else if (os.platform() == 'win32') {
96
+ platform = 'win64';
97
+ extension = 'zip';
98
+ isZip = true;
99
+ } else {
100
+ throw new Error(`Unrecognized platform: ${os.platform()}`);
101
+ }
102
+
103
+ const archiveUrl =
104
+ 'https://github.com/mozilla/geckodriver/releases/download' +
105
+ `/v${driverVersion}` +
106
+ `/geckodriver-v${driverVersion}-${platform}.${extension}`;
107
+
108
+ let binaryName = 'geckodriver';
109
+ if (os.platform() == 'win32') {
110
+ binaryName += '.exe';
111
+ }
112
+
113
+ let outputName = this.getDriverName();
114
+ if (os.platform() == 'win32') {
115
+ outputName += '.exe';
116
+ }
117
+
118
+ return await InstallerUtils.installBinary(
119
+ archiveUrl, binaryName, outputName,
120
+ outputDirectory, isZip);
121
+ }
122
+ }
123
+
124
+ module.exports = {FirefoxWebDriverInstaller};
package/main.js ADDED
@@ -0,0 +1,79 @@
1
+ #!/usr/bin/env node
2
+ /*! @license
3
+ * WebDriver Installer
4
+ * Copyright 2022 Google LLC
5
+ * SPDX-License-Identifier: Apache-2.0
6
+ */
7
+
8
+ const {ChromeWebDriverInstaller} = require('./chrome.js');
9
+ const {ChromeAndroidWebDriverInstaller} = require('./chrome-android.js');
10
+ const {FirefoxWebDriverInstaller} = require('./firefox.js');
11
+ const {EdgeWebDriverInstaller} = require('./edge.js');
12
+
13
+ const INSTALLER_CLASSES = [
14
+ ChromeWebDriverInstaller,
15
+ ChromeAndroidWebDriverInstaller,
16
+ FirefoxWebDriverInstaller,
17
+ EdgeWebDriverInstaller,
18
+ ];
19
+
20
+ /**
21
+ * Install drivers to match all detected browsers.
22
+ *
23
+ * @param {string=} outputDirectory Defaults to ./
24
+ * @param {boolean=} logging
25
+ * @return {!Promise}
26
+ */
27
+ async function main(outputDirectory='.', logging=true) {
28
+ if (logging) {
29
+ console.log(`Installing binaries to ${outputDirectory}`);
30
+ }
31
+
32
+ for (const InstallerClass of INSTALLER_CLASSES) {
33
+ const installer = new InstallerClass();
34
+ const browserName = installer.getBrowserName();
35
+ const driverName = installer.getDriverName();
36
+ const browserVersion = await installer.getInstalledBrowserVersion();
37
+
38
+ if (browserVersion == null) {
39
+ if (logging) {
40
+ console.log(`${browserName} not found.`);
41
+ }
42
+ } else {
43
+ const installedDriverVersion =
44
+ await installer.getInstalledDriverVersion(outputDirectory);
45
+ const bestDriverVersion =
46
+ await installer.getBestDriverVersion(browserVersion);
47
+
48
+ if (installedDriverVersion == bestDriverVersion) {
49
+ if (logging) {
50
+ console.log(
51
+ `Version ${installedDriverVersion} of ${driverName} already` +
52
+ ` installed for ${browserName} version ${browserVersion}`);
53
+ }
54
+ } else {
55
+ await installer.install(bestDriverVersion, outputDirectory);
56
+ if (logging) {
57
+ console.log(
58
+ `Installed version ${bestDriverVersion} of ${driverName}` +
59
+ ` for ${browserName} version ${browserVersion}`);
60
+ }
61
+ }
62
+ }
63
+ }
64
+ }
65
+
66
+ if (require.main == module) {
67
+ // Skip argv[0], which is node, and argv[1], which is this script name.
68
+ const args = process.argv.slice(2);
69
+
70
+ const HELP_ARGS = ['--help', '-h', '-?'];
71
+ if (args.length > 1 || HELP_ARGS.includes(args[0])) {
72
+ process.stderr.write(`Usage: ${process.argv[1]} [OUTPUT_DIR]\n`);
73
+ process.exit(1);
74
+ }
75
+
76
+ main(args[0]);
77
+ } else {
78
+ module.exports = {installWebDrivers: main};
79
+ }
package/package.json ADDED
@@ -0,0 +1,23 @@
1
+ {
2
+ "name": "webdriver-installer",
3
+ "version": "1.0.0",
4
+ "description": "Install the right WebDriver version for your local browsers, automatically.",
5
+ "main": "main.js",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "https://github.com/joeyparrish/webdriver-installer"
9
+ },
10
+ "keywords": [
11
+ "webdriver",
12
+ "chrome",
13
+ "firefox",
14
+ "edge"
15
+ ],
16
+ "author": "Joey Parrish <joeyparrish@google.com>",
17
+ "dependencies": {
18
+ "node-fetch": "^2.6.7",
19
+ "tar-stream": "^2.2.0",
20
+ "yauzl": "^2.10.0"
21
+ },
22
+ "license": "Apache-2.0"
23
+ }
package/utils.js ADDED
@@ -0,0 +1,360 @@
1
+ /*! @license
2
+ * WebDriver Installer
3
+ * Copyright 2022 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ const childProcess = require('child_process');
8
+ const fetch = require('node-fetch');
9
+ const fs = require('fs');
10
+ const fsPromises = require('fs/promises');
11
+ const os = require('os');
12
+ const path = require('path');
13
+ const stream = require('stream');
14
+ const tar = require('tar-stream');
15
+ const util = require('util');
16
+ const yauzl = require('yauzl');
17
+ const zlib = require('zlib');
18
+
19
+ const execFile = util.promisify(childProcess.execFile);
20
+ const pipeline = util.promisify(stream.pipeline);
21
+ const zipFromBuffer = util.promisify(yauzl.fromBuffer);
22
+
23
+ /**
24
+ * A static utility class for driver installers to use for common operations.
25
+ */
26
+ class InstallerUtils {
27
+ /**
28
+ * Execute an external command to get a result containing .stdout and .stderr.
29
+ * All output is interpretted as UTF-8.
30
+ *
31
+ * Throws if the command fails. If the command does not exist, the thrown
32
+ * error has .code == 'ENOENT'.
33
+ *
34
+ * @param {!Array<string>} args
35
+ * @return {!Promise<!Object>} as returned by child_process.spawn
36
+ */
37
+ static async runCommand(args) {
38
+ return await execFile(args[0], args.slice(1), {encoding: 'utf8'});
39
+ }
40
+
41
+ /**
42
+ * Execute a command and return its stdout. If the command is missing,
43
+ * returns null. If the command fails, throws.
44
+ *
45
+ * @param {!Array<string>} args
46
+ * @return {!Promise<?string>}
47
+ */
48
+ static async getCommandOutputOrNullIfMissing(args) {
49
+ try {
50
+ const result = await InstallerUtils.runCommand(args);
51
+ // Success. Return command's stdout.
52
+ return result.stdout;
53
+ } catch (error) {
54
+ if (error.code == 'ENOENT') {
55
+ // Command does not exist.
56
+ return null;
57
+ } else {
58
+ // Command exists, but failed.
59
+ throw error;
60
+ }
61
+ }
62
+ }
63
+
64
+ /**
65
+ * Fetch a URL, throwing if the HTTP status code is not 2XX.
66
+ *
67
+ * @param {string} url
68
+ * @return {!Promise<!Response>}
69
+ */
70
+ static async fetchUrl(url) {
71
+ const response = await fetch(url);
72
+ if (!response.ok) {
73
+ throw new Error(
74
+ `Failed to fetch ${url}: ${response.status} ${response.statusText}`);
75
+ }
76
+ return response;
77
+ }
78
+
79
+ /**
80
+ * Get a version number from the Windows registry.
81
+ *
82
+ * @param {string} path
83
+ * @param {string} key
84
+ * @return {!Promise<?string>}
85
+ */
86
+ static async getWindowsRegistryVersion(path, key) {
87
+ if (os.platform() != 'win32') {
88
+ return null;
89
+ }
90
+
91
+ const result = await InstallerUtils.runCommand([
92
+ 'reg', 'query', path, '/v', key,
93
+ ]);
94
+
95
+ // Find the line with the key in it. For "version", it would look something
96
+ // like this:
97
+ // version REG_SZ 94.0.4606.61
98
+ for (const line of result.stdout.split('\n')) {
99
+ if (line[0] == ' ' && line.includes(key)) {
100
+ // Find the section that starts with a number.
101
+ for (const section of line.split(' ')) {
102
+ if (section[0] >= '0' && section[0] <= '9') {
103
+ return section;
104
+ }
105
+ }
106
+ }
107
+ }
108
+
109
+ // Not found.
110
+ return null;
111
+ }
112
+
113
+ /**
114
+ * Test if a file exists.
115
+ *
116
+ * @param {path}
117
+ * @return {!Promise<boolean}
118
+ */
119
+ static async fileExists(path) {
120
+ try {
121
+ await fsPromises.stat(path);
122
+ return true;
123
+ } catch (error) {
124
+ return false;
125
+ }
126
+ }
127
+
128
+ /**
129
+ * Get a version number from the metadata of a Windows executable.
130
+ *
131
+ * @param {string} path
132
+ * @return {!Promise<?string>}
133
+ */
134
+ static async getWindowsExeVersion(path) {
135
+ if (os.platform() != 'win32') {
136
+ return null;
137
+ }
138
+
139
+ if (!(await InstallerUtils.fileExists(path))) {
140
+ // No such file. Avoid the need to parse "not found" errors from
141
+ // powershell output.
142
+ return null;
143
+ }
144
+
145
+ const result = await InstallerUtils.runCommand([
146
+ 'powershell',
147
+ `(Get-Item "${path}").VersionInfo.ProductVersion`,
148
+ ]);
149
+
150
+ const output = result.stdout.trim();
151
+ if (output == '') {
152
+ // No such metadata found by powershell.
153
+ return null;
154
+ }
155
+
156
+ return output;
157
+ }
158
+
159
+ /**
160
+ * Get the version of an installed app on macOS.
161
+ *
162
+ * @param {string} appName
163
+ * @return {!Promise<?string>}
164
+ */
165
+ static async getMacAppVersion(appName) {
166
+ if (os.platform() != 'darwin') {
167
+ return null;
168
+ }
169
+
170
+ try {
171
+ const result = await InstallerUtils.runCommand([
172
+ 'osascript', '-e',
173
+ `tell application "${appName}" to get version`,
174
+ ]);
175
+ return result.stdout.trim();
176
+ } catch (error) {
177
+ return null;
178
+ }
179
+ }
180
+
181
+ /**
182
+ * Get the version of an installed Android app on a connected device.
183
+ *
184
+ * @param {string} appReverseDomainName
185
+ * @return {!Promise<?string>}
186
+ */
187
+ static async getAndroidAppVersion(appReverseDomainName) {
188
+ let result;
189
+
190
+ try {
191
+ result = await InstallerUtils.runCommand([
192
+ 'adb', 'shell', 'dumpsys', `package ${appReverseDomainName}`,
193
+ ]);
194
+ } catch (error) {
195
+ if (error.code == 'ENOENT') {
196
+ // No adb, so no Android connection.
197
+ return null;
198
+ } else if (error.code != 0) {
199
+ if (error.stderr.includes('no devices')) {
200
+ // No devices attached.
201
+ return null;
202
+ }
203
+
204
+ // Otherwise, print the error output and raise an error.
205
+ process.stderr.write(error.stderr);
206
+ throw new Error(`Failed to communicate with adb!`);
207
+ }
208
+ }
209
+
210
+ for (const line of result.stdout.split('\n')) {
211
+ // Something like:
212
+ // versionName=1.2.3
213
+ if (line.includes('versionName')) {
214
+ return line.split('=')[1];
215
+ }
216
+ }
217
+
218
+ return null;
219
+ }
220
+
221
+ /**
222
+ * Fetch a version number from a URL. Both Chrome and Edge use this.
223
+ *
224
+ * @param {string} url
225
+ * @param {string=} encoding
226
+ * @return {!Promise<?string>}
227
+ */
228
+ static async fetchVersionUrl(url, encoding='utf8') {
229
+ const response = await InstallerUtils.fetchUrl(url);
230
+ const data = Buffer.from(await response.arrayBuffer());
231
+ // Decode the string, then remove any newlines.
232
+ return data.toString(encoding).trim();
233
+ }
234
+
235
+ /**
236
+ * Fetch the latest tag from a GitHub repo.
237
+ *
238
+ * @param {string} repo
239
+ * @return {?string}
240
+ */
241
+ static async fetchLatestGitHubTag(repo) {
242
+ const url = `https://api.github.com/repos/${repo}/releases/latest`;
243
+ const response = await InstallerUtils.fetchUrl(url);
244
+ const releaseMetadata = await response.json();
245
+ return releaseMetadata['tag_name'];
246
+ }
247
+
248
+ /**
249
+ * Find a specific entry in a zip file.
250
+ *
251
+ * @param {!YauzlZipFile} zipfile
252
+ * @param {string} nameInArchive
253
+ * @return {!Promise<!YauzlZipEntry>}
254
+ */
255
+ static findZipEntry(zipfile, nameInArchive) {
256
+ return new Promise((resolve, reject) => {
257
+ zipfile.on('entry', (entry) => {
258
+ if (entry.fileName == nameInArchive) {
259
+ // Found it!
260
+ resolve(entry);
261
+ } else {
262
+ // Read the next one.
263
+ zipfile.readEntry();
264
+ }
265
+ });
266
+ zipfile.on('end', () => {
267
+ // Reached the end without finding our target.
268
+ reject(new Error(`Failed to find ${nameInArchive} in zip file!`));
269
+ });
270
+ // Kick-start the reading process.
271
+ zipfile.readEntry();
272
+ });
273
+ }
274
+
275
+ /**
276
+ * Find a specific entry in a tar file.
277
+ *
278
+ * @param {!Buffer} buffer
279
+ * @param {string} nameInArchive
280
+ * @return {!Promise<!Stream>}
281
+ */
282
+ static findTarEntry(buffer, nameInArchive) {
283
+ return new Promise((resolve, reject) => {
284
+ const extract = tar.extract();
285
+
286
+ extract.on('entry', (entry, stream, next) => {
287
+ if (entry.name == nameInArchive) {
288
+ // Found it!
289
+ resolve(stream);
290
+ } else {
291
+ // Drain the stream so that tar parsing can continue.
292
+ stream.on('end', next);
293
+ stream.resume();
294
+ }
295
+ });
296
+
297
+ extract.on('finish', () => {
298
+ // Reached the end without finding our target.
299
+ reject(new Error(`Failed to find ${nameInArchive} in tar file!`));
300
+ });
301
+
302
+ // Push the buffer through the decompression and extraction pipeline.
303
+ const gunzip = zlib.createGunzip();
304
+ gunzip.pipe(extract);
305
+ gunzip.end(buffer);
306
+ });
307
+ }
308
+
309
+ /**
310
+ * Extract a file from an archive by URL.
311
+ *
312
+ * @param {string} url
313
+ * @param {string} nameInArchive
314
+ * @param {string} outputPath
315
+ * @param {boolean} isZip
316
+ */
317
+ static async extractFromNetworkArchive(
318
+ url, nameInArchive, outputPath, isZip) {
319
+ const response = await InstallerUtils.fetchUrl(url);
320
+ const buffer = Buffer.from(await response.arrayBuffer());
321
+
322
+ // If the output file already exists, remove it before overwriting it.
323
+ // This is important if it's a running executable. Otherwise, we might get
324
+ // permission errors overwriting it. Unlinking it first will ensure the
325
+ // newly-written file is a fresh filesystem inode that doesn't conflict
326
+ // with what's running.
327
+ if (await InstallerUtils.fileExists(path)) {
328
+ await fsPromises.unlink(outputPath);
329
+ }
330
+
331
+ if (isZip) {
332
+ const zipfile = await zipFromBuffer(buffer, {
333
+ lazyEntries: true,
334
+ });
335
+ const entry = await InstallerUtils.findZipEntry(zipfile, nameInArchive);
336
+ const openReadStream = util.promisify(
337
+ zipfile.openReadStream.bind(zipfile));
338
+ await pipeline(
339
+ await openReadStream(entry),
340
+ fs.createWriteStream(outputPath),
341
+ );
342
+ } else {
343
+ const stream = await InstallerUtils.findTarEntry(buffer, nameInArchive);
344
+ await pipeline(
345
+ stream,
346
+ fs.createWriteStream(outputPath),
347
+ );
348
+ }
349
+ }
350
+
351
+ static async installBinary(
352
+ url, nameInArchive, outputName, outputDirectory, isZip) {
353
+ const outputPath = path.join(outputDirectory, outputName);
354
+ await InstallerUtils.extractFromNetworkArchive(
355
+ url, nameInArchive, outputPath, isZip);
356
+ await fsPromises.chmod(outputPath, 0o755);
357
+ }
358
+ }
359
+
360
+ module.exports = {InstallerUtils};