browserstack-cypress-cli 1.23.0 → 1.24.1

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.
Files changed (40) hide show
  1. package/.github/workflows/Semgrep.yml +48 -0
  2. package/CODEOWNERS +1 -0
  3. package/bin/commands/runs.js +74 -38
  4. package/bin/helpers/constants.js +4 -1
  5. package/bin/helpers/timezone.json +1714 -0
  6. package/bin/helpers/utils.js +55 -3
  7. package/bin/testObservability/crashReporter/index.js +139 -0
  8. package/bin/testObservability/cypress/index.js +158 -0
  9. package/bin/testObservability/helper/constants.js +30 -0
  10. package/bin/testObservability/helper/helper.js +996 -0
  11. package/bin/testObservability/helper/requestQueueHandler.js +88 -0
  12. package/bin/testObservability/plugin/index.js +40 -0
  13. package/bin/testObservability/plugin/ipcClient.js +16 -0
  14. package/bin/testObservability/plugin/ipcServer.js +34 -0
  15. package/bin/testObservability/reporter/index.js +699 -0
  16. package/package.json +8 -2
  17. package/.nyc_output/2807648c-3b13-4cd1-b949-11ce1b846277.json +0 -1
  18. package/.nyc_output/48e04c5a-5723-4547-b9d6-20074786acab.json +0 -1
  19. package/.nyc_output/51e8de95-1005-492b-8e2f-d7c6fc9148e4.json +0 -1
  20. package/.nyc_output/577e3334-ad22-4b05-ac7f-e0038582bb25.json +0 -1
  21. package/.nyc_output/59cc8cf4-849a-4cb5-bc52-0133091e0584.json +0 -1
  22. package/.nyc_output/5fc28c76-8c92-44e9-9bae-ec2e85892509.json +0 -1
  23. package/.nyc_output/5fffbcf8-4572-45c7-948f-38aeb3421a3e.json +0 -1
  24. package/.nyc_output/6b02b68b-ad99-40ff-b34f-218d98a9c773.json +0 -1
  25. package/.nyc_output/6ec27c2e-3529-412c-a82b-d1b8970a52a5.json +0 -1
  26. package/.nyc_output/7540c691-20e7-4eb9-a21e-75f1b22fe6eb.json +0 -1
  27. package/.nyc_output/79dc2aeb-d682-45b3-8430-eea8b886e5ae.json +0 -1
  28. package/.nyc_output/processinfo/2807648c-3b13-4cd1-b949-11ce1b846277.json +0 -1
  29. package/.nyc_output/processinfo/48e04c5a-5723-4547-b9d6-20074786acab.json +0 -1
  30. package/.nyc_output/processinfo/51e8de95-1005-492b-8e2f-d7c6fc9148e4.json +0 -1
  31. package/.nyc_output/processinfo/577e3334-ad22-4b05-ac7f-e0038582bb25.json +0 -1
  32. package/.nyc_output/processinfo/59cc8cf4-849a-4cb5-bc52-0133091e0584.json +0 -1
  33. package/.nyc_output/processinfo/5fc28c76-8c92-44e9-9bae-ec2e85892509.json +0 -1
  34. package/.nyc_output/processinfo/5fffbcf8-4572-45c7-948f-38aeb3421a3e.json +0 -1
  35. package/.nyc_output/processinfo/6b02b68b-ad99-40ff-b34f-218d98a9c773.json +0 -1
  36. package/.nyc_output/processinfo/6ec27c2e-3529-412c-a82b-d1b8970a52a5.json +0 -1
  37. package/.nyc_output/processinfo/7540c691-20e7-4eb9-a21e-75f1b22fe6eb.json +0 -1
  38. package/.nyc_output/processinfo/79dc2aeb-d682-45b3-8430-eea8b886e5ae.json +0 -1
  39. package/.nyc_output/processinfo/index.json +0 -1
  40. package/log/usage.log +0 -15
@@ -11,6 +11,7 @@ const util = require('util');
11
11
  const { promisify } = require('util');
12
12
  const readdir = promisify(fs.readdir);
13
13
  const stat = promisify(fs.stat);
14
+ const TIMEZONE = require("../helpers/timezone.json");
14
15
 
15
16
  const usageReporting = require("./usageReporting"),
16
17
  logger = require("./logger").winstonLogger,
@@ -20,7 +21,9 @@ const usageReporting = require("./usageReporting"),
20
21
  fileHelpers = require("./fileHelpers"),
21
22
  config = require("../helpers/config"),
22
23
  pkg = require('../../package.json'),
23
- transports = require('./logger').transports;
24
+ transports = require('./logger').transports,
25
+ { findGitConfig, printBuildLink, isTestObservabilitySession, isBrowserstackInfra, shouldReRunObservabilityTests } = require('../testObservability/helper/helper'),
26
+ { OBSERVABILITY_ENV_VARS, TEST_OBSERVABILITY_REPORTER } = require('../testObservability/helper/constants');
24
27
 
25
28
  const request = require('request');
26
29
 
@@ -225,7 +228,7 @@ exports.setDefaults = (bsConfig, args) => {
225
228
  }
226
229
 
227
230
  // setting cache_dependencies to true if not present
228
- if (this.isUndefined(bsConfig.run_settings.cache_dependencies)) {
231
+ if (bsConfig.run_settings && this.isUndefined(bsConfig.run_settings.cache_dependencies)) {
229
232
  bsConfig.run_settings.cache_dependencies = true;
230
233
  }
231
234
 
@@ -389,6 +392,24 @@ exports.setSpecTimeout = (bsConfig, args) => {
389
392
  logger.debug(`Setting spec timeout = ${specTimeout}`);
390
393
  }
391
394
 
395
+ exports.isValidTimezone = (timezone) => this.isNotUndefined(timezone) && this.isNotUndefined(TIMEZONE[timezone])
396
+
397
+ exports.setTimezone = (bsConfig, args) => {
398
+ let timezone = args.timezone || bsConfig.run_settings.timezone;
399
+ let newTimezone;
400
+ if(this.isNotUndefined(timezone)) {
401
+ if(this.isValidTimezone(timezone)){
402
+ newTimezone = timezone;
403
+ } else {
404
+ logger.error(`Invalid timezone = ${timezone}`);
405
+ syncCliLogger.info(chalk.red(Constants.userMessages.INVALID_TIMEZONE));
406
+ process.exit(1);
407
+ }
408
+ }
409
+ bsConfig.run_settings.timezone = newTimezone;
410
+ logger.debug(`Setting timezone = ${newTimezone}`);
411
+ }
412
+
392
413
  exports.setRecordFlag = (bsConfig, args) => {
393
414
  if(!this.isUndefined(args["record"])) {
394
415
  return true;
@@ -459,6 +480,11 @@ exports.setNodeVersion = (bsConfig, args) => {
459
480
  // specs can be passed via command line args as a string
460
481
  // command line args takes precedence over config
461
482
  exports.setUserSpecs = (bsConfig, args) => {
483
+ if(isBrowserstackInfra() && isTestObservabilitySession() && shouldReRunObservabilityTests()) {
484
+ bsConfig.run_settings.specs = process.env.BROWSERSTACK_RERUN_TESTS;
485
+ return;
486
+ }
487
+
462
488
  let bsConfigSpecs = bsConfig.run_settings.specs;
463
489
 
464
490
  if (!this.isUndefined(args.specs)) {
@@ -532,6 +558,19 @@ exports.setSystemEnvs = (bsConfig) => {
532
558
  });
533
559
  }
534
560
 
561
+ try {
562
+ OBSERVABILITY_ENV_VARS.forEach(key => {
563
+ envKeys[key] = process.env[key];
564
+ });
565
+
566
+ let gitConfigPath = findGitConfig(process.cwd());
567
+ if(!isBrowserstackInfra()) process.env.OBSERVABILITY_GIT_CONFIG_PATH_LOCAL = gitConfigPath;
568
+ if(gitConfigPath) {
569
+ const relativePathFromGitConfig = path.relative(gitConfigPath, process.cwd());
570
+ envKeys["OBSERVABILITY_GIT_CONFIG_PATH"] = relativePathFromGitConfig ? relativePathFromGitConfig : 'DEFAULT';
571
+ }
572
+ } catch(e){}
573
+
535
574
  if (Object.keys(envKeys).length === 0) {
536
575
  bsConfig.run_settings.system_env_vars = null;
537
576
  } else {
@@ -554,6 +593,8 @@ exports.fixCommaSeparatedString = (string) => {
554
593
 
555
594
  exports.isUndefined = value => (value === undefined || value === null);
556
595
 
596
+ exports.isNotUndefined = value => !this.isUndefined(value);
597
+
557
598
  exports.isPositiveInteger = (str) => {
558
599
  if (typeof str !== 'string') {
559
600
  return false;
@@ -1102,7 +1143,11 @@ exports.handleSyncExit = (exitCode, dashboard_url) => {
1102
1143
  syncCliLogger.info(Constants.userMessages.BUILD_REPORT_MESSAGE);
1103
1144
  syncCliLogger.info(dashboard_url);
1104
1145
  }
1105
- process.exit(exitCode);
1146
+ if(isTestObservabilitySession()) {
1147
+ printBuildLink(true, exitCode);
1148
+ } else {
1149
+ process.exit(exitCode);
1150
+ }
1106
1151
  }
1107
1152
 
1108
1153
  exports.getNetworkErrorMessage = (dashboard_url) => {
@@ -1202,6 +1247,12 @@ exports.setConfig = (bsConfig, args) => {
1202
1247
 
1203
1248
  // blindly send other passed configs with run_settings and handle at backend
1204
1249
  exports.setOtherConfigs = (bsConfig, args) => {
1250
+ if(isTestObservabilitySession() && process.env.BS_TESTOPS_JWT) {
1251
+ bsConfig["run_settings"]["reporter"] = TEST_OBSERVABILITY_REPORTER;
1252
+ return;
1253
+ }
1254
+
1255
+ /* Non Observability use-case */
1205
1256
  if (!this.isUndefined(args.reporter)) {
1206
1257
  bsConfig["run_settings"]["reporter"] = args.reporter;
1207
1258
  logger.debug(`reporter set to ${args.reporter}`);
@@ -1361,6 +1412,7 @@ async function processExitHandler(exitData){
1361
1412
  logger.warn(Constants.userMessages.PROCESS_KILL_MESSAGE);
1362
1413
  await this.stopBrowserStackBuild(exitData.bsConfig, exitData.args, exitData.buildId, null, exitData.buildReportData);
1363
1414
  await this.stopLocalBinary(exitData.bsConfig, exitData.bsLocalInstance, exitData.args, null, exitData.buildReportData);
1415
+ await printBuildLink(true);
1364
1416
  process.exit(0);
1365
1417
  }
1366
1418
 
@@ -0,0 +1,139 @@
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+ const request = require('request');
4
+ const http = require('http');
5
+ const https = require('https');
6
+
7
+ const logger = require("../../helpers/logger").winstonLogger;
8
+
9
+ const { API_URL, consoleHolder } = require('../helper/constants');
10
+
11
+ /* Below global methods are added here to remove cyclic dependency with helper.js, refactor later */
12
+ const httpsKeepAliveAgent = new https.Agent({
13
+ keepAlive: true,
14
+ timeout: 60000,
15
+ maxSockets: 2,
16
+ maxTotalSockets: 2
17
+ });
18
+
19
+ const debug = (text) => {
20
+ if (process.env.BROWSERSTACK_OBSERVABILITY_DEBUG === "true" || process.env.BROWSERSTACK_OBSERVABILITY_DEBUG === "1") {
21
+ logger.info(`[ OBSERVABILITY ] ${text}`);
22
+ }
23
+ }
24
+
25
+ let packages = {};
26
+
27
+ exports.requireModule = (module, internal = false) => {
28
+ let local_path = "";
29
+ if(process.env["browserStackCwd"]){
30
+ local_path = path.join(process.env["browserStackCwd"], 'node_modules', module);
31
+ } else if(internal) {
32
+ local_path = path.join(process.cwd(), 'node_modules', 'browserstack-cypress-cli', 'node_modules', module);
33
+ } else {
34
+ local_path = path.join(process.cwd(), 'node_modules', module);
35
+ }
36
+ if(!fs.existsSync(local_path)) {
37
+ let global_path;
38
+ if(['jest-runner', 'jest-runtime'].includes(module))
39
+ global_path = path.join(GLOBAL_MODULE_PATH, 'jest', 'node_modules', module);
40
+ else
41
+ global_path = path.join(GLOBAL_MODULE_PATH, module);
42
+ if(!fs.existsSync(global_path)) {
43
+ throw new Error(`${module} doesn't exist.`);
44
+ }
45
+ return require(global_path);
46
+ }
47
+ return require(local_path);
48
+ }
49
+
50
+ getPackageVersion = (package_) => {
51
+ if(packages[package_]) return packages[package_];
52
+ return packages[package_] = this.requireModule(`${package_}/package.json`).version;
53
+ }
54
+
55
+ getAgentVersion = () => {
56
+ let _path = path.join(__dirname, '../../../package.json');
57
+ if(fs.existsSync(_path))
58
+ return require(_path).version;
59
+ }
60
+
61
+ class CrashReporter {
62
+ static instance;
63
+
64
+ constructor() {
65
+ }
66
+
67
+ static getInstance() {
68
+ if (!CrashReporter.instance) {
69
+ CrashReporter.instance = new CrashReporter();
70
+ }
71
+ return CrashReporter.instance;
72
+ }
73
+
74
+ setCredentialsForCrashReportUpload(credentialsStr) {
75
+ /* User credentials used for reporting crashes */
76
+ this.credentialsForCrashReportUpload = JSON.parse(credentialsStr);
77
+ }
78
+
79
+ setConfigDetails(credentialsStr, browserstackConfigFile, cypressConfigFile) {
80
+ /* User test config for build run */
81
+ this.userConfigForReporting = {
82
+ framework: 'Cypress',
83
+ browserstackConfigFile: browserstackConfigFile,
84
+ cypressConfigFile: cypressConfigFile
85
+ };
86
+ this.setCredentialsForCrashReportUpload(credentialsStr);
87
+ }
88
+
89
+ uploadCrashReport(exception, stacktrace) {
90
+ try {
91
+ if (!this.credentialsForCrashReportUpload.username || !this.credentialsForCrashReportUpload.password) {
92
+ return debug('[Crash_Report_Upload] Failed to parse user credentials while reporting crash')
93
+ }
94
+
95
+ const data = {
96
+ hashed_id: process.env.BS_TESTOPS_BUILD_HASHED_ID,
97
+ observability_version: {
98
+ frameworkName: 'Cypress',
99
+ frameworkVersion: getPackageVersion('cypress'),
100
+ sdkVersion: getAgentVersion()
101
+ },
102
+ exception: {
103
+ error: exception.toString(),
104
+ stackTrace: stacktrace
105
+ },
106
+ config: this.userConfigForReporting
107
+ }
108
+
109
+ const options = {
110
+ auth: {
111
+ ...this.credentialsForCrashReportUpload
112
+ },
113
+ headers: {
114
+ 'Content-Type': 'application/json',
115
+ 'X-BSTACK-TESTOPS': 'true'
116
+ },
117
+ method: 'POST',
118
+ url: `${API_URL}/api/v1/analytics`,
119
+ body: data,
120
+ json: true,
121
+ agent: httpsKeepAliveAgent
122
+ };
123
+
124
+ request(options, function callback(error, response, body) {
125
+ if(error) {
126
+ debug(`[Crash_Report_Upload] Failed due to ${error}`);
127
+ } else if(response.statusCode != 200) {
128
+ debug(`[Crash_Report_Upload] Failed due to ${response && response.body ? response.body : `Received response from BrowserStack Server with status : ${response.statusCode}`}`);
129
+ } else {
130
+ debug(`[Crash_Report_Upload] Success response: ${JSON.stringify({status: response.status, body: response.body})}`)
131
+ }
132
+ });
133
+ } catch(e) {
134
+ debug(`[Crash_Report_Upload] Processing failed due to ${e && e.stack}`);
135
+ }
136
+ }
137
+ }
138
+
139
+ module.exports = CrashReporter;
@@ -0,0 +1,158 @@
1
+ /* Event listeners + custom commands for Cypress */
2
+
3
+ /* Used to detect Gherkin steps */
4
+ Cypress.on('log:added', (log) => {
5
+ cy.now('task', 'test_observability_step', {
6
+ log
7
+ }, {log: false}).then((res) => {
8
+ }).catch((err) => {
9
+ });
10
+ });
11
+
12
+ Cypress.on('command:start', (command) => {
13
+ if(!command || !command.attributes) return;
14
+ if(command.attributes.name == 'log' || (command.attributes.name == 'task' && (command.attributes.args.includes('test_observability_command') || command.attributes.args.includes('test_observability_log')))) {
15
+ return;
16
+ }
17
+ /* Send command details */
18
+ cy.now('task', 'test_observability_command', {
19
+ type: 'COMMAND_START',
20
+ command: {
21
+ attributes: {
22
+ id: command.attributes.id,
23
+ name: command.attributes.name,
24
+ args: command.attributes.args
25
+ },
26
+ state: 'pending'
27
+ }
28
+ }, {log: false}).then((res) => {
29
+ }).catch((err) => {
30
+ });
31
+
32
+ /* Send platform details */
33
+ cy.now('task', 'test_observability_platform_details', {
34
+ testTitle: Cypress.currentTest.title,
35
+ browser: Cypress.browser,
36
+ platform: Cypress.platform,
37
+ cypressVersion: Cypress.version
38
+ }, {log: false}).then((res) => {
39
+ }).catch((err) => {
40
+ });
41
+ });
42
+
43
+ Cypress.on('command:retry', (command) => {
44
+ if(!command || !command.attributes) return;
45
+ if(command.attributes.name == 'log' || (command.attributes.name == 'task' && (command.attributes.args.includes('test_observability_command') || command.attributes.args.includes('test_observability_log')))) {
46
+ return;
47
+ }
48
+ cy.now('task', 'test_observability_command', {
49
+ type: 'COMMAND_RETRY',
50
+ command: {
51
+ _log: command._log,
52
+ error: {
53
+ message: command && command.error ? command.error.message : null,
54
+ isDefaultAssertionErr: command && command.error ? command.error.isDefaultAssertionErr : null
55
+ }
56
+ }
57
+ }, {log: false}).then((res) => {
58
+ }).catch((err) => {
59
+ });
60
+ });
61
+
62
+ Cypress.on('command:end', (command) => {
63
+ if(!command || !command.attributes) return;
64
+ if(command.attributes.name == 'log' || (command.attributes.name == 'task' && (command.attributes.args.includes('test_observability_command') || command.attributes.args.includes('test_observability_log')))) {
65
+ return;
66
+ }
67
+ cy.now('task', 'test_observability_command', {
68
+ 'type': 'COMMAND_END',
69
+ 'command': {
70
+ 'attributes': {
71
+ 'id': command.attributes.id,
72
+ 'name': command.attributes.name,
73
+ 'args': command.attributes.args
74
+ },
75
+ 'state': command.state
76
+ }
77
+ }, {log: false}).then((res) => {
78
+ }).catch((err) => {
79
+ });
80
+ });
81
+
82
+ Cypress.Commands.overwrite('log', (originalFn, ...args) => {
83
+ if(args.includes('test_observability_log') || args.includes('test_observability_command')) return;
84
+ const message = args.reduce((result, logItem) => {
85
+ if (typeof logItem === 'object') {
86
+ return [result, JSON.stringify(logItem)].join(' ');
87
+ }
88
+
89
+ return [result, logItem ? logItem.toString() : ''].join(' ');
90
+ }, '');
91
+ cy.now('task', 'test_observability_log', {
92
+ 'level': 'info',
93
+ message,
94
+ }, {log: false}).then((res) => {
95
+ }).catch((err) => {
96
+ });
97
+ originalFn(...args);
98
+ });
99
+
100
+ Cypress.Commands.add('trace', (message, file) => {
101
+ cy.now('task', 'test_observability_log', {
102
+ level: 'trace',
103
+ message,
104
+ file,
105
+ }).then((res) => {
106
+ }).catch((err) => {
107
+ });
108
+ });
109
+
110
+ Cypress.Commands.add('logDebug', (message, file) => {
111
+ cy.now('task', 'test_observability_log', {
112
+ level: 'debug',
113
+ message,
114
+ file,
115
+ }).then((res) => {
116
+ }).catch((err) => {
117
+ });
118
+ });
119
+
120
+ Cypress.Commands.add('info', (message, file) => {
121
+ cy.now('task', 'test_observability_log', {
122
+ level: 'info',
123
+ message,
124
+ file,
125
+ }).then((res) => {
126
+ }).catch((err) => {
127
+ });
128
+ });
129
+
130
+ Cypress.Commands.add('warn', (message, file) => {
131
+ cy.now('task', 'test_observability_log', {
132
+ level: 'warn',
133
+ message,
134
+ file,
135
+ }).then((res) => {
136
+ }).catch((err) => {
137
+ });
138
+ });
139
+
140
+ Cypress.Commands.add('error', (message, file) => {
141
+ cy.now('task', 'test_observability_log', {
142
+ level: 'error',
143
+ message,
144
+ file,
145
+ }).then((res) => {
146
+ }).catch((err) => {
147
+ });
148
+ });
149
+
150
+ Cypress.Commands.add('fatal', (message, file) => {
151
+ cy.now('task', 'test_observability_log', {
152
+ level: 'fatal',
153
+ message,
154
+ file,
155
+ }).then((res) => {
156
+ }).catch((err) => {
157
+ });
158
+ });
@@ -0,0 +1,30 @@
1
+ exports.consoleHolder = Object.assign({},console);
2
+ exports.BATCH_SIZE = 1000;
3
+ exports.BATCH_INTERVAL = 2000;
4
+ exports.API_URL = 'https://collector-observability.browserstack.com';
5
+
6
+ exports.IPC_EVENTS = {
7
+ LOG: 'testObservability:cypressLog',
8
+ CONFIG: 'testObservability:cypressConfig',
9
+ SCREENSHOT: 'testObservability:cypressScreenshot',
10
+ COMMAND: 'testObservability:cypressCommand',
11
+ CUCUMBER: 'testObservability:cypressCucumberStep',
12
+ PLATFORM_DETAILS: 'testObservability:cypressPlatformDetails'
13
+ };
14
+
15
+ exports.OBSERVABILITY_ENV_VARS = [
16
+ "BROWSERSTACK_TEST_OBSERVABILITY",
17
+ "BROWSERSTACK_AUTOMATION",
18
+ "BS_TESTOPS_BUILD_COMPLETED",
19
+ "BS_TESTOPS_JWT",
20
+ "BS_TESTOPS_BUILD_HASHED_ID",
21
+ "BS_TESTOPS_ALLOW_SCREENSHOTS",
22
+ "OBSERVABILITY_LAUNCH_SDK_VERSION",
23
+ "BROWSERSTACK_OBSERVABILITY_DEBUG",
24
+ "OBS_CRASH_REPORTING_USERNAME",
25
+ "OBS_CRASH_REPORTING_ACCESS_KEY",
26
+ "OBS_CRASH_REPORTING_BS_CONFIG_PATH",
27
+ "OBS_CRASH_REPORTING_CYPRESS_CONFIG_PATH"
28
+ ];
29
+
30
+ exports.TEST_OBSERVABILITY_REPORTER = 'browserstack-cypress-cli/bin/testObservability/reporter';