browserstack-cypress-cli 1.10.1 → 1.12.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.
@@ -8,6 +8,8 @@ const cp = require("child_process"),
8
8
  const config = require('./config'),
9
9
  fileLogger = require('./logger').fileLogger,
10
10
  utils = require('./utils');
11
+
12
+ const { AUTH_REGEX, REDACTED_AUTH } = require("./constants");
11
13
 
12
14
  function get_version(package_name) {
13
15
  try {
@@ -173,19 +175,43 @@ function isUsageReportingEnabled() {
173
175
  function send(args) {
174
176
  if (isUsageReportingEnabled() === "true") return;
175
177
 
176
- let bsConfig = args.bstack_config;
178
+ let bsConfig = JSON.parse(JSON.stringify(args.bstack_config));
179
+ let runSettings = "";
180
+ let sanitizedbsConfig = "";
177
181
  let cli_details = cli_version_and_path(bsConfig);
178
182
  let data = utils.isUndefined(args.data) ? {} : args.data;
179
183
 
180
184
  if (bsConfig && bsConfig.run_settings) {
181
- data.cypress_version = bsConfig.run_settings.cypress_version
185
+ runSettings = bsConfig.run_settings;
186
+ data.cypress_version = bsConfig.run_settings.cypress_version;
182
187
  }
183
188
 
189
+ sanitizedbsConfig = `${(typeof bsConfig === 'string') ? bsConfig :
190
+ JSON.stringify(bsConfig)}`.replace(AUTH_REGEX, REDACTED_AUTH);
191
+
184
192
  delete args.bstack_config;
185
193
 
194
+ let zipUploadDetails = {
195
+ test_suite_zip_upload: data.test_suite_zip_upload,
196
+ package_zip_upload: data.package_zip_upload,
197
+ test_suite_zip_size: data.test_suite_zip_size,
198
+ test_suite_zip_upload_avg_speed: data.test_suite_zip_upload_avg_speed,
199
+ npm_package_zip_size: data.npm_package_zip_size,
200
+ npm_package_zip_upload_avg_speed: data.npm_package_zip_upload_avg_speed,
201
+ }
202
+
203
+ Object.keys(zipUploadDetails).forEach((key) => {
204
+ delete data[key];
205
+ })
206
+
186
207
  const payload = {
187
208
  event_type: "cypress_cli_stats",
188
209
  data: {
210
+ build_hashed_id: data.build_id,
211
+ user_id: data.user_id,
212
+ parallels: data.parallels,
213
+ bstack_json: sanitizedbsConfig,
214
+ run_settings: runSettings,
189
215
  os: _os(),
190
216
  os_version: os_version(),
191
217
  bstack_json_found_in_pwd: bstack_json_found_in_pwd(),
@@ -197,6 +223,8 @@ function send(args) {
197
223
  ci_environment: ci_environment(),
198
224
  event_timestamp: new Date().toLocaleString(),
199
225
  data: JSON.stringify(data),
226
+ raw_args: JSON.stringify(args.raw_args),
227
+ ...zipUploadDetails,
200
228
  ...args,
201
229
  },
202
230
  };
@@ -13,7 +13,9 @@ const usageReporting = require("./usageReporting"),
13
13
  Constants = require("./constants"),
14
14
  chalk = require('chalk'),
15
15
  syncCliLogger = require("../helpers/logger").syncCliLogger,
16
- config = require("../helpers/config");
16
+ fileHelpers = require("./fileHelpers"),
17
+ config = require("../helpers/config"),
18
+ pkg = require('../../package.json');
17
19
 
18
20
  const request = require('request');
19
21
 
@@ -80,6 +82,24 @@ exports.getErrorCodeFromMsg = (errMsg) => {
80
82
  case Constants.validationMessages.INVALID_CYPRESS_CONFIG_FILE:
81
83
  errorCode = 'invalid_cypress_config_file';
82
84
  break;
85
+ case Constants.validationMessages.INVALID_LOCAL_ASYNC_ARGS:
86
+ errorCode = 'invalid_local_async_args';
87
+ break;
88
+ case Constants.validationMessages.INVALID_GEO_LOCATION:
89
+ errorCode = 'invalid_geo_location';
90
+ break;
91
+ case Constants.validationMessages.NOT_ALLOWED_GEO_LOCATION_AND_LOCAL_MODE:
92
+ errorCode = 'not_allowed_geo_location_and_local_mode';
93
+ break;
94
+ case Constants.validationMessages.HOME_DIRECTORY_NOT_FOUND:
95
+ errorCode = 'home_directory_not_found';
96
+ break;
97
+ case Constants.validationMessages.HOME_DIRECTORY_NOT_A_DIRECTORY:
98
+ errorCode = 'home_directory_not_a_directory';
99
+ break;
100
+ case Constants.validationMessages.CYPRESS_CONFIG_FILE_NOT_PART_OF_HOME_DIRECTORY:
101
+ errorCode = 'cypress_config_file_not_part_of_home_directory';
102
+ break;
83
103
  }
84
104
  if (
85
105
  errMsg.includes("Please use --config-file <path to browserstack.json>.")
@@ -109,7 +129,8 @@ exports.sendUsageReport = (
109
129
  message,
110
130
  message_type,
111
131
  error_code,
112
- data
132
+ data,
133
+ rawArgs
113
134
  ) => {
114
135
  usageReporting.send({
115
136
  cli_args: args,
@@ -118,6 +139,7 @@ exports.sendUsageReport = (
118
139
  error_code: error_code,
119
140
  bstack_config: bsConfig,
120
141
  data,
142
+ raw_args: rawArgs
121
143
  });
122
144
  };
123
145
 
@@ -133,6 +155,10 @@ exports.setUsageReportingFlag = (bsConfig, disableUsageReporting) => {
133
155
  }
134
156
  };
135
157
 
158
+ exports.getParallels = (bsConfig, args) => {
159
+ return args.parallels || bsConfig['run_settings']['parallels'];
160
+ }
161
+
136
162
  exports.setParallels = (bsConfig, args, numOfSpecs) => {
137
163
  if (!this.isUndefined(args.parallels)) {
138
164
  bsConfig["run_settings"]["parallels"] = args.parallels;
@@ -153,7 +179,7 @@ exports.setParallels = (bsConfig, args, numOfSpecs) => {
153
179
  }
154
180
  };
155
181
 
156
- exports.warnSpecLimit = (bsConfig, args, specFiles) => {
182
+ exports.warnSpecLimit = (bsConfig, args, specFiles, rawArgs) => {
157
183
  let expectedCharLength = specFiles.join("").length + Constants.METADATA_CHAR_BUFFER_PER_SPEC * specFiles.length;
158
184
  let parallels = bsConfig.run_settings.parallels;
159
185
  let combinations = this.getBrowserCombinations(bsConfig).length;
@@ -166,7 +192,9 @@ exports.warnSpecLimit = (bsConfig, args, specFiles) => {
166
192
  args,
167
193
  Constants.userMessages.SPEC_LIMIT_WARNING,
168
194
  Constants.messageTypes.WARNING,
169
- null
195
+ null,
196
+ null,
197
+ rawArgs
170
198
  );
171
199
  }
172
200
  }
@@ -187,6 +215,11 @@ exports.setDefaults = (bsConfig, args) => {
187
215
  bsConfig.connection_settings = {};
188
216
  }
189
217
 
218
+ // setting cache_dependencies to true if not present
219
+ if (this.isUndefined(bsConfig.run_settings.cache_dependencies)) {
220
+ bsConfig.run_settings.cache_dependencies = true;
221
+ }
222
+
190
223
  }
191
224
 
192
225
  exports.setUsername = (bsConfig, args) => {
@@ -254,6 +287,28 @@ exports.setCypressConfigFilename = (bsConfig, args) => {
254
287
  }
255
288
  }
256
289
 
290
+ exports.verifyGeolocationOption = () => {
291
+ let glOptionsSet = (this.searchForOption('-gl') || this.searchForOption('--gl'));
292
+ let geoHyphenLocationOptionsSet = (this.searchForOption('-geo-location') || this.searchForOption('--geo-location'));
293
+ let geoLocationOptionsSet = (this.searchForOption('-geolocation') || this.searchForOption('--geolocation'));
294
+ return (glOptionsSet || geoHyphenLocationOptionsSet || geoLocationOptionsSet);
295
+ }
296
+
297
+ exports.setGeolocation = (bsConfig, args) => {
298
+ let userProvidedGeolocation = this.verifyGeolocationOption();
299
+ bsConfig.run_settings.userProvidedGeolocation = (userProvidedGeolocation || (!this.isUndefined(bsConfig.run_settings.geolocation)));
300
+
301
+ if (userProvidedGeolocation && !this.isUndefined(args.geolocation)) {
302
+ bsConfig.run_settings.geolocation = args.geolocation;
303
+ }
304
+
305
+ if (this.isUndefined(bsConfig.run_settings.geolocation)){
306
+ bsConfig.run_settings.geolocation = null;
307
+ } else {
308
+ bsConfig.run_settings.geolocation = bsConfig.run_settings.geolocation.toUpperCase();
309
+ }
310
+ }
311
+
257
312
  // specs can be passed from bstack configuration file
258
313
  // specs can be passed via command line args as a string
259
314
  // command line args takes precedence over config
@@ -334,6 +389,8 @@ exports.fixCommaSeparatedString = (string) => {
334
389
 
335
390
  exports.isUndefined = value => (value === undefined || value === null);
336
391
 
392
+ exports.isTrueString = value => (!this.isUndefined(value) && value.toString().toLowerCase() === 'true');
393
+
337
394
  exports.isFloat = (value) => Number(value) && Number(value) % 1 !== 0;
338
395
 
339
396
  exports.nonEmptyArray = (value) => {
@@ -348,7 +405,7 @@ exports.isParallelValid = (value) => {
348
405
  }
349
406
 
350
407
  exports.getUserAgent = () => {
351
- return `BStack-Cypress-CLI/1.10.0 (${os.arch()}/${os.platform()}/${os.release()})`;
408
+ return `BStack-Cypress-CLI/${pkg.version} (${os.arch()}/${os.platform()}/${os.release()})`;
352
409
  };
353
410
 
354
411
  exports.isAbsolute = (configPath) => {
@@ -404,6 +461,82 @@ exports.isCypressProjDirValid = (cypressProjDir, integrationFoldDir) => {
404
461
  return parentTokens.every((t, i) => childTokens[i] === t);
405
462
  };
406
463
 
464
+ exports.generateUploadParams = (bsConfig, filePath, md5data, fileDetails) => {
465
+ let options = {
466
+ url: config.uploadUrl,
467
+ auth: {
468
+ user: bsConfig.auth.username,
469
+ password: bsConfig.auth.access_key
470
+ },
471
+ formData: {
472
+ file: fs.createReadStream(filePath),
473
+ filetype: fileDetails.filetype,
474
+ filename: fileDetails.filename,
475
+ zipMd5sum: md5data ? md5data : '',
476
+ },
477
+ headers: {
478
+ "User-Agent": exports.getUserAgent(),
479
+ }
480
+ }
481
+ return options
482
+ }
483
+
484
+ exports.sortJsonKeys = (unordered) => {
485
+ const ordered = Object.keys(unordered).sort().reduce(
486
+ (obj, key) => {
487
+ obj[key] = unordered[key];
488
+ return obj;
489
+ },
490
+ {}
491
+ );
492
+ return ordered
493
+ }
494
+
495
+ exports.generateUploadOptions = (type, md5data, packageData) => {
496
+ let options = {};
497
+ switch (type) {
498
+ case 'zip':
499
+ options = {
500
+ archivePresent: true,
501
+ md5ReturnKey: "zip_url",
502
+ urlPresent: md5data.zipUrlPresent,
503
+ md5Data: md5data.zip_md5sum,
504
+ url: md5data.zipUrl,
505
+ propogateError: true,
506
+ fileDetails: {
507
+ filetype: "zip",
508
+ filename: "tests"
509
+ },
510
+ messages: {
511
+ uploading: Constants.userMessages.UPLOADING_TESTS,
512
+ uploadingSuccess: Constants.userMessages.UPLOADING_TESTS_SUCCESS
513
+ },
514
+ cleanupMethod: fileHelpers.deleteZip,
515
+ }
516
+ break;
517
+ case 'npm':
518
+ options = {
519
+ archivePresent: packageData.packageArchieveCreated,
520
+ md5ReturnKey: "npm_package_url",
521
+ urlPresent: md5data.packageUrlPresent,
522
+ md5Data: md5data.npm_package_md5sum,
523
+ url: md5data.npmPackageUrl,
524
+ propogateError: false,
525
+ fileDetails: {
526
+ filetype: "tar.gz",
527
+ filename: "bstackPackages"
528
+ },
529
+ messages: {
530
+ uploading: Constants.userMessages.UPLOADING_NPM_PACKAGES,
531
+ uploadingSuccess: Constants.userMessages.UPLOADING_NPM_PACKAGES_SUCCESS
532
+ },
533
+ cleanupMethod: fileHelpers.deletePackageArchieve,
534
+ }
535
+ break;
536
+ }
537
+ return options;
538
+ };
539
+
407
540
  exports.getLocalFlag = (connectionSettings) => {
408
541
  return (
409
542
  !this.isUndefined(connectionSettings) &&
@@ -501,7 +634,7 @@ exports.setLocalMode = (bsConfig, args) => {
501
634
  }
502
635
  };
503
636
 
504
- exports.setupLocalTesting = (bsConfig, args) => {
637
+ exports.setupLocalTesting = (bsConfig, args, rawArgs) => {
505
638
  return new Promise(async (resolve, reject) => {
506
639
  if( bsConfig['connection_settings'] && bsConfig['connection_settings']['local'] && String(bsConfig['connection_settings']['local']) === "true" ){
507
640
  let localIdentifierRunning = await this.checkLocalIdentifierRunning(
@@ -524,7 +657,9 @@ exports.setupLocalTesting = (bsConfig, args) => {
524
657
  args,
525
658
  message,
526
659
  Constants.messageTypes.ERROR,
527
- errorCode
660
+ errorCode,
661
+ null,
662
+ rawArgs
528
663
  );
529
664
  reject(Constants.userMessages.LOCAL_START_FAILED);
530
665
  }
@@ -538,7 +673,7 @@ exports.setupLocalTesting = (bsConfig, args) => {
538
673
  });
539
674
  };
540
675
 
541
- exports.stopLocalBinary = (bsConfig, bs_local, args) => {
676
+ exports.stopLocalBinary = (bsConfig, bs_local, args, rawArgs) => {
542
677
  return new Promise(async (resolve, reject) => {
543
678
  if(bsConfig['connection_settings'] && bsConfig['connection_settings']['local']){
544
679
  let localIdentifierRunning = await this.checkLocalIdentifierRunning(bsConfig,bsConfig["connection_settings"]["local_identifier"]);
@@ -550,7 +685,9 @@ exports.stopLocalBinary = (bsConfig, bs_local, args) => {
550
685
  args,
551
686
  message,
552
687
  Constants.messageTypes.ERROR,
553
- errorCode
688
+ errorCode,
689
+ null,
690
+ rawArgs
554
691
  );
555
692
  }
556
693
  }
@@ -567,7 +704,9 @@ exports.stopLocalBinary = (bsConfig, bs_local, args) => {
567
704
  args,
568
705
  message,
569
706
  Constants.messageTypes.ERROR,
570
- errorCode
707
+ errorCode,
708
+ null,
709
+ rawArgs
571
710
  );
572
711
  resolve(Constants.userMessages.LOCAL_STOP_FAILED);
573
712
  }
@@ -733,18 +872,27 @@ exports.getNetworkErrorMessage = (dashboard_url) => {
733
872
  return chalk.red(message)
734
873
  }
735
874
 
736
- exports.versionChangedMessage = (preferredVersion, actualVersion) => {
875
+ exports.versionChangedMessage = (preferredVersion, actualVersion, frameworkUpgradeMessage = '') => {
737
876
  let message = Constants.userMessages.CYPRESS_VERSION_CHANGED.replace("<preferredVersion>", preferredVersion);
738
877
  message = message.replace("<actualVersion>", actualVersion);
878
+ frameworkUpgradeMessage = frameworkUpgradeMessage.replace('.latest', "");
879
+ message = message.replace('<frameworkUpgradeMessage>', frameworkUpgradeMessage);
739
880
  return message
740
881
  }
741
882
 
742
- exports.latestSyntaxToActualVersionMessage = (latestSyntaxVersion, actualVersion) => {
883
+ exports.latestSyntaxToActualVersionMessage = (latestSyntaxVersion, actualVersion, frameworkUpgradeMessage = '') => {
743
884
  let message = Constants.userMessages.LATEST_SYNTAX_TO_ACTUAL_VERSION_MESSAGE.replace("<latestSyntaxVersion>", latestSyntaxVersion);
744
885
  message = message.replace("<actualVersion>", actualVersion);
886
+ message = message.replace('<frameworkUpgradeMessage>', frameworkUpgradeMessage)
745
887
  return message
746
888
  }
747
889
 
890
+ exports.checkError = (data) => {
891
+ if (!this.isUndefined(data.error)) {
892
+ return data.error
893
+ }
894
+ }
895
+
748
896
  exports.isJSONInvalid = (err, args) => {
749
897
  let invalid = true
750
898
 
@@ -760,6 +908,10 @@ exports.isJSONInvalid = (err, args) => {
760
908
  return false
761
909
  }
762
910
 
911
+ if( err === Constants.validationMessages.INVALID_LOCAL_ASYNC_ARGS && !this.isUndefined(args.async)) {
912
+ return false
913
+ }
914
+
763
915
  return invalid
764
916
  }
765
917
 
@@ -776,7 +928,7 @@ exports.setBrowsers = async (bsConfig, args) => {
776
928
  browsersList.forEach((browser)=>{
777
929
  let browserHash = {}
778
930
  let osBrowserDetails = browser.split(':')
779
- browserHash['os'] = osBrowserDetails[1].trim()
931
+ if (!this.isUndefined(osBrowserDetails[1])) browserHash['os'] = osBrowserDetails[1].trim()
780
932
  let browserDetails = osBrowserDetails[0].split('@')
781
933
  browserHash['browser'] = browserDetails[0].trim()
782
934
  browserHash['versions'] = []
@@ -807,6 +959,15 @@ exports.setOtherConfigs = (bsConfig, args) => {
807
959
  }
808
960
  }
809
961
 
962
+ exports.readBsConfigJSON = (bsConfigPath) => {
963
+ try {
964
+ fs.accessSync(bsConfigPath, fs.constants.R_OK);
965
+ return fs.readFileSync(bsConfigPath, 'utf-8');
966
+ } catch (err) {
967
+ return null;
968
+ }
969
+ }
970
+
810
971
  exports.getCypressJSON = (bsConfig) => {
811
972
  let cypressJSON = undefined;
812
973
  if (bsConfig.run_settings.cypress_config_file && bsConfig.run_settings.cypress_config_filename !== 'false') {
@@ -820,3 +981,123 @@ exports.getCypressJSON = (bsConfig) => {
820
981
  }
821
982
  return cypressJSON;
822
983
  }
984
+
985
+ exports.setCLIMode = (bsConfig, args) => {
986
+ args.sync = true;
987
+ if(!this.isUndefined(args.async) && args.async){
988
+ args.sync = false;
989
+ }
990
+ }
991
+
992
+ exports.stopBrowserStackBuild = async (bsConfig, args, buildId, rawArgs) => {
993
+ let that = this;
994
+ return new Promise(function (resolve, reject) {
995
+ let url = config.buildStopUrl + buildId;
996
+ let options = {
997
+ url: url,
998
+ auth: {
999
+ username: bsConfig["auth"]["username"],
1000
+ password: bsConfig["auth"]["access_key"],
1001
+ },
1002
+ headers: {
1003
+ 'User-Agent': that.getUserAgent(),
1004
+ },
1005
+ };
1006
+ let message = null;
1007
+ let messageType = null;
1008
+ let errorCode = null;
1009
+ let build = null;
1010
+ request.post(options, function(err, resp, data) {
1011
+ if(err) {
1012
+ message = Constants.userMessages.BUILD_STOP_FAILED;
1013
+ messageType = Constants.messageTypes.ERROR;
1014
+ errorCode = 'api_failed_build_stop';
1015
+ logger.info(message);
1016
+ } else {
1017
+ try {
1018
+ build = JSON.parse(data);
1019
+ if (resp.statusCode == 299) {
1020
+ messageType = Constants.messageTypes.INFO;
1021
+ errorCode = 'api_deprecated';
1022
+
1023
+ if (build) {
1024
+ message = build.message;
1025
+ logger.info(message);
1026
+ } else {
1027
+ message = Constants.userMessages.API_DEPRECATED;
1028
+ logger.info(message);
1029
+ }
1030
+ } else if (resp.statusCode != 200) {
1031
+ messageType = Constants.messageTypes.ERROR;
1032
+ errorCode = 'api_failed_build_stop';
1033
+
1034
+ if (build) {
1035
+ message = `${
1036
+ Constants.userMessages.BUILD_STOP_FAILED
1037
+ } with error: \n${JSON.stringify(build, null, 2)}`;
1038
+ logger.error(message);
1039
+ if (build.message === 'Unauthorized') errorCode = 'api_auth_failed';
1040
+ } else {
1041
+ message = Constants.userMessages.BUILD_STOP_FAILED;
1042
+ logger.error(message);
1043
+ }
1044
+ } else {
1045
+ messageType = Constants.messageTypes.SUCCESS;
1046
+ message = `${JSON.stringify(build, null, 2)}`;
1047
+ logger.info(message);
1048
+ }
1049
+ } catch(err) {
1050
+ console.log(err);
1051
+ message = Constants.userMessages.BUILD_STOP_FAILED;
1052
+ messageType = Constants.messageTypes.ERROR;
1053
+ errorCode = 'api_failed_build_stop';
1054
+ logger.info(message);
1055
+ } finally {
1056
+ that.sendUsageReport(bsConfig, args, message, messageType, errorCode, null, rawArgs);
1057
+ }
1058
+ }
1059
+ resolve();
1060
+ });
1061
+ });
1062
+ }
1063
+
1064
+ exports.setProcessHooks = (buildId, bsConfig, bsLocal, args) => {
1065
+ let bindData = {
1066
+ buildId: buildId,
1067
+ bsConfig: bsConfig,
1068
+ bsLocalInstance: bsLocal,
1069
+ args: args
1070
+ }
1071
+ process.on('SIGINT', processExitHandler.bind(this, bindData));
1072
+ process.on('SIGTERM', processExitHandler.bind(this, bindData));
1073
+ process.on('SIGBREAK', processExitHandler.bind(this, bindData));
1074
+ process.on('uncaughtException', processExitHandler.bind(this, bindData));
1075
+ }
1076
+
1077
+ async function processExitHandler(exitData){
1078
+ logger.warn(Constants.userMessages.PROCESS_KILL_MESSAGE);
1079
+ await this.stopBrowserStackBuild(exitData.bsConfig, exitData.args, exitData.buildId);
1080
+ await this.stopLocalBinary(exitData.bsConfig, exitData.bsLocalInstance, exitData.args);
1081
+ process.exit(0);
1082
+ }
1083
+
1084
+ exports.fetchZipSize = (fileName) => {
1085
+ try {
1086
+ let stats = fs.statSync(fileName)
1087
+ return stats.size; // in bytes
1088
+ }
1089
+ catch(err) {
1090
+ return 0;
1091
+ }
1092
+ }
1093
+
1094
+ exports.getVideoConfig = (cypressJson) => {
1095
+ let conf = {
1096
+ video: true,
1097
+ videoUploadOnPasses: true
1098
+ }
1099
+ if (!this.isUndefined(cypressJson.video)) conf.video = cypressJson.video;
1100
+ if (!this.isUndefined(cypressJson.videoUploadOnPasses)) conf.videoUploadOnPasses = cypressJson.videoUploadOnPasses;
1101
+
1102
+ return conf;
1103
+ }