cypress 15.1.0 → 15.2.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/lib/cli.js CHANGED
@@ -1,38 +1,46 @@
1
1
  "use strict";
2
-
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
3
6
  // @ts-check
4
- const _ = require('lodash');
5
- const commander = require('commander');
6
- const {
7
- stripIndent
8
- } = require('common-tags');
9
- const logSymbols = require('log-symbols');
10
- const debug = require('debug')('cypress:cli:cli');
11
- const util = require('./util');
12
- const logger = require('./logger');
13
- const errors = require('./errors');
14
- const cache = require('./tasks/cache');
15
-
7
+ const lodash_1 = __importDefault(require("lodash"));
8
+ const commander_1 = __importDefault(require("commander"));
9
+ const common_tags_1 = require("common-tags");
10
+ const log_symbols_1 = __importDefault(require("log-symbols"));
11
+ const debug_1 = __importDefault(require("debug"));
12
+ const util_1 = __importDefault(require("./util"));
13
+ const logger_1 = __importDefault(require("./logger"));
14
+ const errors_1 = require("./errors");
15
+ const cache_1 = __importDefault(require("./tasks/cache"));
16
+ const open_1 = __importDefault(require("./exec/open"));
17
+ const run_1 = __importDefault(require("./exec/run"));
18
+ const verify_1 = __importDefault(require("./tasks/verify"));
19
+ const install_1 = __importDefault(require("./tasks/install"));
20
+ const versions_1 = __importDefault(require("./exec/versions"));
21
+ const info_1 = __importDefault(require("./exec/info"));
22
+ const debug = (0, debug_1.default)('cypress:cli:cli');
16
23
  // patch "commander" method called when a user passed an unknown option
17
24
  // we want to print help for the current command and exit with an error
18
25
  function unknownOption(flag, type = 'option') {
19
- if (this._allowUnknownOption) return;
20
- logger.error();
21
- logger.error(` error: unknown ${type}:`, flag);
22
- logger.error();
23
- this.outputHelp();
24
- util.exit(1);
26
+ if (this._allowUnknownOption)
27
+ return;
28
+ logger_1.default.error();
29
+ logger_1.default.error(` error: unknown ${type}:`, flag);
30
+ logger_1.default.error();
31
+ this.outputHelp();
32
+ util_1.default.exit(1);
25
33
  }
26
- commander.Command.prototype.unknownOption = unknownOption;
27
- const coerceFalse = arg => {
28
- return arg !== 'false';
34
+ commander_1.default.Command.prototype.unknownOption = unknownOption;
35
+ const coerceFalse = (arg) => {
36
+ return arg !== 'false';
29
37
  };
30
- const coerceAnyStringToInt = arg => {
31
- return typeof arg === 'string' ? parseInt(arg) : arg;
38
+ const coerceAnyStringToInt = (arg) => {
39
+ return typeof arg === 'string' ? parseInt(arg) : arg;
32
40
  };
33
41
  const spaceDelimitedArgsMsg = (flag, args) => {
34
- let msg = `
35
- ${logSymbols.warning} Warning: It looks like you're passing --${flag} a space-separated list of arguments:
42
+ let msg = `
43
+ ${log_symbols_1.default.warning} Warning: It looks like you're passing --${flag} a space-separated list of arguments:
36
44
 
37
45
  "${args.join(' ')}"
38
46
 
@@ -41,157 +49,216 @@ const spaceDelimitedArgsMsg = (flag, args) => {
41
49
  If you are trying to pass multiple arguments, separate them with commas instead:
42
50
  cypress run --${flag} arg1,arg2,arg3
43
51
  `;
44
- if (flag === 'spec') {
45
- msg += `
52
+ if (flag === 'spec') {
53
+ msg += `
46
54
  The most common cause of this warning is using an unescaped glob pattern. If you are
47
55
  trying to pass a glob pattern, escape it using quotes:
48
56
  cypress run --spec "**/*.spec.js"
49
57
  `;
50
- }
51
- logger.log();
52
- logger.warn(stripIndent(msg));
53
- logger.log();
58
+ }
59
+ logger_1.default.log();
60
+ logger_1.default.warn((0, common_tags_1.stripIndent)(msg));
61
+ logger_1.default.log();
54
62
  };
55
63
  const parseVariableOpts = (fnArgs, args) => {
56
- const [opts, unknownArgs] = fnArgs;
57
- if (unknownArgs && unknownArgs.length && (opts.spec || opts.tag)) {
58
- // this will capture space-delimited args after
59
- // flags that could have possible multiple args
60
- // but before the next option
61
- // --spec spec1 spec2 or --tag foo bar
62
-
63
- const multiArgFlags = _.compact([opts.spec ? 'spec' : opts.spec, opts.tag ? 'tag' : opts.tag]);
64
- _.forEach(multiArgFlags, flag => {
65
- const argIndex = _.indexOf(args, `--${flag}`) + 2;
66
- const nextOptOffset = _.findIndex(_.slice(args, argIndex), arg => {
67
- return _.startsWith(arg, '--');
68
- });
69
- const endIndex = nextOptOffset !== -1 ? argIndex + nextOptOffset : args.length;
70
- const maybeArgs = _.slice(args, argIndex, endIndex);
71
- const extraArgs = _.intersection(maybeArgs, unknownArgs);
72
- if (extraArgs.length) {
73
- opts[flag] = [opts[flag]].concat(extraArgs);
74
- spaceDelimitedArgsMsg(flag, opts[flag]);
75
- opts[flag] = opts[flag].join(',');
76
- }
77
- });
78
- }
79
- debug('variable-length opts parsed %o', {
80
- args,
81
- opts
82
- });
83
- return util.parseOpts(opts);
64
+ const [opts, unknownArgs] = fnArgs;
65
+ if ((unknownArgs && unknownArgs.length) && (opts.spec || opts.tag)) {
66
+ // this will capture space-delimited args after
67
+ // flags that could have possible multiple args
68
+ // but before the next option
69
+ // --spec spec1 spec2 or --tag foo bar
70
+ const multiArgFlags = lodash_1.default.compact([
71
+ opts.spec ? 'spec' : opts.spec,
72
+ opts.tag ? 'tag' : opts.tag,
73
+ ]);
74
+ lodash_1.default.forEach(multiArgFlags, (flag) => {
75
+ const argIndex = lodash_1.default.indexOf(args, `--${flag}`) + 2;
76
+ const nextOptOffset = lodash_1.default.findIndex(lodash_1.default.slice(args, argIndex), (arg) => {
77
+ return lodash_1.default.startsWith(arg, '--');
78
+ });
79
+ const endIndex = nextOptOffset !== -1 ? argIndex + nextOptOffset : args.length;
80
+ const maybeArgs = lodash_1.default.slice(args, argIndex, endIndex);
81
+ const extraArgs = lodash_1.default.intersection(maybeArgs, unknownArgs);
82
+ if (extraArgs.length) {
83
+ opts[flag] = [opts[flag]].concat(extraArgs);
84
+ spaceDelimitedArgsMsg(flag, opts[flag]);
85
+ opts[flag] = opts[flag].join(',');
86
+ }
87
+ });
88
+ }
89
+ debug('variable-length opts parsed %o', { args, opts });
90
+ return util_1.default.parseOpts(opts);
84
91
  };
85
92
  const descriptions = {
86
- autoCancelAfterFailures: 'overrides the project-level Cloud configuration to set the failed test threshold for auto cancellation or to disable auto cancellation when recording to the Cloud',
87
- browser: 'runs Cypress in the browser with the given name. if a filesystem path is supplied, Cypress will attempt to use the browser at that path.',
88
- cacheClear: 'delete all cached binaries',
89
- cachePrune: 'deletes all cached binaries except for the version currently in use',
90
- cacheList: 'list cached binary versions',
91
- cachePath: 'print the path to the binary cache',
92
- cacheSize: 'Used with the list command to show the sizes of the cached folders',
93
- ciBuildId: 'the unique identifier for a run on your CI provider. typically a "BUILD_ID" env var. this value is automatically detected for most CI providers',
94
- component: 'runs component tests',
95
- config: 'sets configuration values. separate multiple values with a comma. overrides any value in cypress.config.{js,ts,mjs,cjs}.',
96
- configFile: 'path to script file where configuration values are set. defaults to "cypress.config.{js,ts,mjs,cjs}".',
97
- detached: 'runs Cypress application in detached mode',
98
- dev: 'runs cypress in development and bypasses binary check',
99
- e2e: 'runs end to end tests',
100
- env: 'sets environment variables. separate multiple values with a comma. overrides any value in cypress.config.{js,ts,mjs,cjs} or cypress.env.json',
101
- exit: 'keep the browser open after tests finish',
102
- forceInstall: 'force install the Cypress binary',
103
- global: 'force Cypress into global mode as if it were globally installed',
104
- group: 'a named group for recorded runs in Cypress Cloud',
105
- headed: 'displays the browser instead of running headlessly',
106
- headless: 'hide the browser instead of running headed (default for cypress run)',
107
- key: 'your secret Record Key. you can omit this if you set a CYPRESS_RECORD_KEY environment variable.',
108
- parallel: 'enables concurrent runs and automatic load balancing of specs across multiple machines or processes',
109
- port: 'runs Cypress on a specific port. overrides any value in cypress.config.{js,ts,mjs,cjs}.',
110
- project: 'path to the project',
111
- quiet: 'run quietly, using only the configured reporter',
112
- record: 'records the run. sends test results, screenshots and videos to Cypress Cloud.',
113
- reporter: 'runs a specific mocha reporter. pass a path to use a custom reporter. defaults to "spec"',
114
- reporterOptions: 'options for the mocha reporter. defaults to "null"',
115
- runnerUi: 'displays the Cypress Runner UI',
116
- noRunnerUi: 'hides the Cypress Runner UI',
117
- spec: 'runs specific spec file(s). defaults to "all"',
118
- tag: 'named tag(s) for recorded runs in Cypress Cloud',
119
- version: 'prints Cypress version'
93
+ autoCancelAfterFailures: 'overrides the project-level Cloud configuration to set the failed test threshold for auto cancellation or to disable auto cancellation when recording to the Cloud',
94
+ browser: 'runs Cypress in the browser with the given name. if a filesystem path is supplied, Cypress will attempt to use the browser at that path.',
95
+ cacheClear: 'delete all cached binaries',
96
+ cachePrune: 'deletes all cached binaries except for the version currently in use',
97
+ cacheList: 'list cached binary versions',
98
+ cachePath: 'print the path to the binary cache',
99
+ cacheSize: 'Used with the list command to show the sizes of the cached folders',
100
+ ciBuildId: 'the unique identifier for a run on your CI provider. typically a "BUILD_ID" env var. this value is automatically detected for most CI providers',
101
+ component: 'runs component tests',
102
+ config: 'sets configuration values. separate multiple values with a comma. overrides any value in cypress.config.{js,ts,mjs,cjs}.',
103
+ configFile: 'path to script file where configuration values are set. defaults to "cypress.config.{js,ts,mjs,cjs}".',
104
+ detached: 'runs Cypress application in detached mode',
105
+ dev: 'runs cypress in development and bypasses binary check',
106
+ e2e: 'runs end to end tests',
107
+ env: 'sets environment variables. separate multiple values with a comma. overrides any value in cypress.config.{js,ts,mjs,cjs} or cypress.env.json',
108
+ exit: 'keep the browser open after tests finish',
109
+ forceInstall: 'force install the Cypress binary',
110
+ global: 'force Cypress into global mode as if it were globally installed',
111
+ group: 'a named group for recorded runs in Cypress Cloud',
112
+ headed: 'displays the browser instead of running headlessly',
113
+ headless: 'hide the browser instead of running headed (default for cypress run)',
114
+ key: 'your secret Record Key. you can omit this if you set a CYPRESS_RECORD_KEY environment variable.',
115
+ parallel: 'enables concurrent runs and automatic load balancing of specs across multiple machines or processes',
116
+ port: 'runs Cypress on a specific port. overrides any value in cypress.config.{js,ts,mjs,cjs}.',
117
+ project: 'path to the project',
118
+ quiet: 'run quietly, using only the configured reporter',
119
+ record: 'records the run. sends test results, screenshots and videos to Cypress Cloud.',
120
+ reporter: 'runs a specific mocha reporter. pass a path to use a custom reporter. defaults to "spec"',
121
+ reporterOptions: 'options for the mocha reporter. defaults to "null"',
122
+ runnerUi: 'displays the Cypress Runner UI',
123
+ noRunnerUi: 'hides the Cypress Runner UI',
124
+ spec: 'runs specific spec file(s). defaults to "all"',
125
+ tag: 'named tag(s) for recorded runs in Cypress Cloud',
126
+ version: 'prints Cypress version',
120
127
  };
121
- const knownCommands = ['cache', 'help', '-h', '--help', 'install', 'open', 'run', 'verify', '-v', '--version', 'version', 'info'];
122
- const text = description => {
123
- if (!descriptions[description]) {
124
- throw new Error(`Could not find description for: ${description}`);
125
- }
126
- return descriptions[description];
128
+ const knownCommands = [
129
+ 'cache',
130
+ 'help',
131
+ '-h',
132
+ '--help',
133
+ 'install',
134
+ 'open',
135
+ 'run',
136
+ 'verify',
137
+ '-v',
138
+ '--version',
139
+ 'version',
140
+ 'info',
141
+ ];
142
+ const text = (description) => {
143
+ if (!descriptions[description]) {
144
+ throw new Error(`Could not find description for: ${description}`);
145
+ }
146
+ return descriptions[description];
127
147
  };
128
148
  function includesVersion(args) {
129
- return _.includes(args, '--version') || _.includes(args, '-v');
149
+ return (lodash_1.default.includes(args, '--version') ||
150
+ lodash_1.default.includes(args, '-v'));
130
151
  }
131
152
  function showVersions(opts) {
132
- debug('printing Cypress version');
133
- debug('additional arguments %o', opts);
134
- debug('parsed version arguments %o', opts);
135
- const reportAllVersions = versions => {
136
- logger.always('Cypress package version:', versions.package);
137
- logger.always('Cypress binary version:', versions.binary);
138
- logger.always('Electron version:', versions.electronVersion);
139
- logger.always('Bundled Node version:', versions.electronNodeVersion);
140
- };
141
- const reportComponentVersion = (componentName, versions) => {
142
- const names = {
143
- package: 'package',
144
- binary: 'binary',
145
- electron: 'electronVersion',
146
- node: 'electronNodeVersion'
153
+ debug('printing Cypress version');
154
+ debug('additional arguments %o', opts);
155
+ debug('parsed version arguments %o', opts);
156
+ const reportAllVersions = (versions) => {
157
+ logger_1.default.always('Cypress package version:', versions.package);
158
+ logger_1.default.always('Cypress binary version:', versions.binary);
159
+ logger_1.default.always('Electron version:', versions.electronVersion);
160
+ logger_1.default.always('Bundled Node version:', versions.electronNodeVersion);
147
161
  };
148
- if (!names[componentName]) {
149
- throw new Error(`Unknown component name "${componentName}"`);
150
- }
151
- const name = names[componentName];
152
- if (!versions[name]) {
153
- throw new Error(`Cannot find version for component "${componentName}" under property "${name}"`);
154
- }
155
- const version = versions[name];
156
- logger.always(version);
157
- };
158
- const defaultVersions = {
159
- package: undefined,
160
- binary: undefined,
161
- electronVersion: undefined,
162
- electronNodeVersion: undefined
163
- };
164
- return require('./exec/versions').getVersions().then((versions = defaultVersions) => {
165
- if (opts !== null && opts !== void 0 && opts.component) {
166
- reportComponentVersion(opts.component, versions);
167
- } else {
168
- reportAllVersions(versions);
169
- }
170
- process.exit(0);
171
- }).catch(util.logErrorExit1);
162
+ const reportComponentVersion = (componentName, versions) => {
163
+ const names = {
164
+ package: 'package',
165
+ binary: 'binary',
166
+ electron: 'electronVersion',
167
+ node: 'electronNodeVersion',
168
+ };
169
+ if (!names[componentName]) {
170
+ throw new Error(`Unknown component name "${componentName}"`);
171
+ }
172
+ const name = names[componentName];
173
+ if (!versions[name]) {
174
+ throw new Error(`Cannot find version for component "${componentName}" under property "${name}"`);
175
+ }
176
+ const version = versions[name];
177
+ logger_1.default.always(version);
178
+ };
179
+ const defaultVersions = {
180
+ package: undefined,
181
+ binary: undefined,
182
+ electronVersion: undefined,
183
+ electronNodeVersion: undefined,
184
+ };
185
+ return versions_1.default
186
+ .getVersions()
187
+ .then((versions = defaultVersions) => {
188
+ if (opts === null || opts === void 0 ? void 0 : opts.component) {
189
+ reportComponentVersion(opts.component, versions);
190
+ }
191
+ else {
192
+ reportAllVersions(versions);
193
+ }
194
+ process.exit(0);
195
+ })
196
+ .catch(util_1.default.logErrorExit1);
172
197
  }
173
198
  const createProgram = () => {
174
- const program = new commander.Command();
175
-
176
- // bug in commander not printing name
177
- // in usage help docs
178
- program._name = 'cypress';
179
- program.usage('<command> [options]');
180
- return program;
199
+ const program = new commander_1.default.Command();
200
+ // bug in commander not printing name
201
+ // in usage help docs
202
+ program._name = 'cypress';
203
+ program.usage('<command> [options]');
204
+ return program;
181
205
  };
182
- const addCypressRunCommand = program => {
183
- return program.command('run').usage('[options]').description('Runs Cypress tests from the CLI without the GUI').option('--auto-cancel-after-failures <test-failure-count || false>', text('autoCancelAfterFailures')).option('-b, --browser <browser-name-or-path>', text('browser')).option('--ci-build-id <id>', text('ciBuildId')).option('--component', text('component')).option('-c, --config <config>', text('config')).option('-C, --config-file <config-file>', text('configFile')).option('--e2e', text('e2e')).option('-e, --env <env>', text('env')).option('--group <name>', text('group')).option('-k, --key <record-key>', text('key')).option('--headed', text('headed')).option('--headless', text('headless')).option('--no-exit', text('exit')).option('--parallel', text('parallel')).option('-p, --port <port>', text('port')).option('-P, --project <project-path>', text('project')).option('-q, --quiet', text('quiet')).option('--record [bool]', text('record'), coerceFalse).option('-r, --reporter <reporter>', text('reporter')).option('--runner-ui', text('runnerUi')).option('--no-runner-ui', text('noRunnerUi')).option('-o, --reporter-options <reporter-options>', text('reporterOptions')).option('-s, --spec <spec>', text('spec')).option('-t, --tag <tag>', text('tag')).option('--dev', text('dev'), coerceFalse);
206
+ const addCypressRunCommand = (program) => {
207
+ return program
208
+ .command('run')
209
+ .usage('[options]')
210
+ .description('Runs Cypress tests from the CLI without the GUI')
211
+ .option('--auto-cancel-after-failures <test-failure-count || false>', text('autoCancelAfterFailures'))
212
+ .option('-b, --browser <browser-name-or-path>', text('browser'))
213
+ .option('--ci-build-id <id>', text('ciBuildId'))
214
+ .option('--component', text('component'))
215
+ .option('-c, --config <config>', text('config'))
216
+ .option('-C, --config-file <config-file>', text('configFile'))
217
+ .option('--e2e', text('e2e'))
218
+ .option('-e, --env <env>', text('env'))
219
+ .option('--group <name>', text('group'))
220
+ .option('-k, --key <record-key>', text('key'))
221
+ .option('--headed', text('headed'))
222
+ .option('--headless', text('headless'))
223
+ .option('--no-exit', text('exit'))
224
+ .option('--parallel', text('parallel'))
225
+ .option('-p, --port <port>', text('port'))
226
+ .option('-P, --project <project-path>', text('project'))
227
+ .option('-q, --quiet', text('quiet'))
228
+ .option('--record [bool]', text('record'), coerceFalse)
229
+ .option('-r, --reporter <reporter>', text('reporter'))
230
+ .option('--runner-ui', text('runnerUi'))
231
+ .option('--no-runner-ui', text('noRunnerUi'))
232
+ .option('-o, --reporter-options <reporter-options>', text('reporterOptions'))
233
+ .option('-s, --spec <spec>', text('spec'))
234
+ .option('-t, --tag <tag>', text('tag'))
235
+ .option('--dev', text('dev'), coerceFalse);
184
236
  };
185
- const addCypressOpenCommand = program => {
186
- return program.command('open').usage('[options]').description('Opens Cypress in the interactive GUI.').option('-b, --browser <browser-path>', text('browser')).option('--component', text('component')).option('-c, --config <config>', text('config')).option('-C, --config-file <config-file>', text('configFile')).option('-d, --detached [bool]', text('detached'), coerceFalse).option('--e2e', text('e2e')).option('-e, --env <env>', text('env')).option('--global', text('global')).option('-p, --port <port>', text('port')).option('-P, --project <project-path>', text('project')).option('--dev', text('dev'), coerceFalse);
237
+ const addCypressOpenCommand = (program) => {
238
+ return program
239
+ .command('open')
240
+ .usage('[options]')
241
+ .description('Opens Cypress in the interactive GUI.')
242
+ .option('-b, --browser <browser-path>', text('browser'))
243
+ .option('--component', text('component'))
244
+ .option('-c, --config <config>', text('config'))
245
+ .option('-C, --config-file <config-file>', text('configFile'))
246
+ .option('-d, --detached [bool]', text('detached'), coerceFalse)
247
+ .option('--e2e', text('e2e'))
248
+ .option('-e, --env <env>', text('env'))
249
+ .option('--global', text('global'))
250
+ .option('-p, --port <port>', text('port'))
251
+ .option('-P, --project <project-path>', text('project'))
252
+ .option('--dev', text('dev'), coerceFalse);
187
253
  };
188
- const maybeAddInspectFlags = program => {
189
- if (process.argv.includes('--dev')) {
190
- return program.option('--inspect', 'Node option').option('--inspect-brk', 'Node option');
191
- }
192
- return program;
254
+ const maybeAddInspectFlags = (program) => {
255
+ if (process.argv.includes('--dev')) {
256
+ return program
257
+ .option('--inspect', 'Node option')
258
+ .option('--inspect-brk', 'Node option');
259
+ }
260
+ return program;
193
261
  };
194
-
195
262
  /**
196
263
  * Casts known command line options for "cypress run" to their intended type.
197
264
  * For example if the user passes "--port 5005" the ".port" property should be
@@ -199,213 +266,250 @@ const maybeAddInspectFlags = program => {
199
266
  *
200
267
  * Returns a clone of the original object.
201
268
  */
202
- const castCypressOptions = opts => {
203
- // only properties that have type "string | false" in our TS definition
204
- // require special handling, because CLI parsing takes care of purely
205
- // boolean arguments
206
- const castOpts = {
207
- ...opts
208
- };
209
- if (_.has(opts, 'port')) {
210
- castOpts.port = coerceAnyStringToInt(opts.port);
211
- }
212
- return castOpts;
213
- };
214
- module.exports = {
215
- /**
216
- * Parses `cypress run` command line option array into an object
217
- * with options that you can feed into a `cypress.run()` module API call.
218
- * @example
219
- * const options = parseRunCommand(['cypress', 'run', '--browser', 'chrome'])
220
- * // options is {browser: 'chrome'}
221
- */
222
- parseRunCommand(args) {
223
- return new Promise((resolve, reject) => {
224
- if (!Array.isArray(args)) {
225
- return reject(new Error('Expected array of arguments'));
226
- }
227
-
228
- // make a copy of the input arguments array
229
- // and add placeholders where "node ..." would usually be
230
- // also remove "cypress" keyword at the start if present
231
- const cliArgs = args[0] === 'cypress' ? [...args.slice(1)] : [...args];
232
- cliArgs.unshift(null, null);
233
- debug('creating program parser');
234
- const program = createProgram();
235
- maybeAddInspectFlags(addCypressRunCommand(program)).action((...fnArgs) => {
236
- debug('parsed Cypress run %o', fnArgs);
237
- const options = parseVariableOpts(fnArgs, cliArgs);
238
- debug('parsed options %o', options);
239
- const casted = castCypressOptions(options);
240
- debug('casted options %o', casted);
241
- resolve(casted);
242
- });
243
- debug('parsing args: %o', cliArgs);
244
- program.parse(cliArgs);
245
- });
246
- },
247
- /**
248
- * Parses `cypress open` command line option array into an object
249
- * with options that you can feed into cy.openModeSystemTest test calls
250
- * @example
251
- * const options = parseOpenCommand(['cypress', 'open', '--browser', 'chrome'])
252
- * // options is {browser: 'chrome'}
253
- */
254
- parseOpenCommand(args) {
255
- return new Promise((resolve, reject) => {
256
- if (!Array.isArray(args)) {
257
- return reject(new Error('Expected array of arguments'));
258
- }
259
-
260
- // make a copy of the input arguments array
261
- // and add placeholders where "node ..." would usually be
262
- // also remove "cypress" keyword at the start if present
263
- const cliArgs = args[0] === 'cypress' ? [...args.slice(1)] : [...args];
264
- cliArgs.unshift(null, null);
265
- debug('creating program parser');
266
- const program = createProgram();
267
- maybeAddInspectFlags(addCypressOpenCommand(program)).action((...fnArgs) => {
268
- debug('parsed Cypress open %o', fnArgs);
269
- const options = parseVariableOpts(fnArgs, cliArgs);
270
- debug('parsed options %o', options);
271
- const casted = castCypressOptions(options);
272
- debug('casted options %o', casted);
273
- resolve(casted);
274
- });
275
- debug('parsing args: %o', cliArgs);
276
- program.parse(cliArgs);
277
- });
278
- },
279
- /**
280
- * Parses the command line and kicks off Cypress process.
281
- */
282
- init(args) {
283
- if (!args) {
284
- args = process.argv;
269
+ const castCypressOptions = (opts) => {
270
+ // only properties that have type "string | false" in our TS definition
271
+ // require special handling, because CLI parsing takes care of purely
272
+ // boolean arguments
273
+ const castOpts = Object.assign({}, opts);
274
+ if (lodash_1.default.has(opts, 'port')) {
275
+ castOpts.port = coerceAnyStringToInt(opts.port);
285
276
  }
286
- const {
287
- CYPRESS_INTERNAL_ENV,
288
- CYPRESS_DOWNLOAD_USE_CA
289
- } = process.env;
290
- if (process.env.CYPRESS_DOWNLOAD_USE_CA) {
291
- let msg = `
292
- ${logSymbols.warning} Warning: It looks like you're setting CYPRESS_DOWNLOAD_USE_CA=${CYPRESS_DOWNLOAD_USE_CA}
277
+ return castOpts;
278
+ };
279
+ const cliModule = {
280
+ /**
281
+ * Parses `cypress run` command line option array into an object
282
+ * with options that you can feed into a `cypress.run()` module API call.
283
+ * @example
284
+ * const options = parseRunCommand(['cypress', 'run', '--browser', 'chrome'])
285
+ * // options is {browser: 'chrome'}
286
+ */
287
+ parseRunCommand(args) {
288
+ return new Promise((resolve, reject) => {
289
+ if (!Array.isArray(args)) {
290
+ return reject(new Error('Expected array of arguments'));
291
+ }
292
+ // make a copy of the input arguments array
293
+ // and add placeholders where "node ..." would usually be
294
+ // also remove "cypress" keyword at the start if present
295
+ const cliArgs = args[0] === 'cypress' ? [...args.slice(1)] : [...args];
296
+ cliArgs.unshift(null, null);
297
+ debug('creating program parser');
298
+ const program = createProgram();
299
+ maybeAddInspectFlags(addCypressRunCommand(program))
300
+ .action((...fnArgs) => {
301
+ debug('parsed Cypress run %o', fnArgs);
302
+ const options = parseVariableOpts(fnArgs, cliArgs);
303
+ debug('parsed options %o', options);
304
+ const casted = castCypressOptions(options);
305
+ debug('casted options %o', casted);
306
+ resolve(casted);
307
+ });
308
+ debug('parsing args: %o', cliArgs);
309
+ program.parse(cliArgs);
310
+ });
311
+ },
312
+ /**
313
+ * Parses `cypress open` command line option array into an object
314
+ * with options that you can feed into cy.openModeSystemTest test calls
315
+ * @example
316
+ * const options = parseOpenCommand(['cypress', 'open', '--browser', 'chrome'])
317
+ * // options is {browser: 'chrome'}
318
+ */
319
+ parseOpenCommand(args) {
320
+ return new Promise((resolve, reject) => {
321
+ if (!Array.isArray(args)) {
322
+ return reject(new Error('Expected array of arguments'));
323
+ }
324
+ // make a copy of the input arguments array
325
+ // and add placeholders where "node ..." would usually be
326
+ // also remove "cypress" keyword at the start if present
327
+ const cliArgs = args[0] === 'cypress' ? [...args.slice(1)] : [...args];
328
+ cliArgs.unshift(null, null);
329
+ debug('creating program parser');
330
+ const program = createProgram();
331
+ maybeAddInspectFlags(addCypressOpenCommand(program))
332
+ .action((...fnArgs) => {
333
+ debug('parsed Cypress open %o', fnArgs);
334
+ const options = parseVariableOpts(fnArgs, cliArgs);
335
+ debug('parsed options %o', options);
336
+ const casted = castCypressOptions(options);
337
+ debug('casted options %o', casted);
338
+ resolve(casted);
339
+ });
340
+ debug('parsing args: %o', cliArgs);
341
+ program.parse(cliArgs);
342
+ });
343
+ },
344
+ /**
345
+ * Parses the command line and kicks off Cypress process.
346
+ */
347
+ init(args) {
348
+ if (!args) {
349
+ args = process.argv;
350
+ }
351
+ const { CYPRESS_INTERNAL_ENV, CYPRESS_DOWNLOAD_USE_CA } = process.env;
352
+ if (process.env.CYPRESS_DOWNLOAD_USE_CA) {
353
+ let msg = `
354
+ ${log_symbols_1.default.warning} Warning: It looks like you're setting CYPRESS_DOWNLOAD_USE_CA=${CYPRESS_DOWNLOAD_USE_CA}
293
355
 
294
356
  The environment variable "CYPRESS_DOWNLOAD_USE_CA" is no longer required to be set.
295
357
 
296
358
  You can safely unset this environment variable.
297
359
  `;
298
- logger.log();
299
- logger.warn(stripIndent(msg));
300
- logger.log();
301
- }
302
- if (!util.isValidCypressInternalEnvValue(CYPRESS_INTERNAL_ENV)) {
303
- debug('invalid CYPRESS_INTERNAL_ENV value', CYPRESS_INTERNAL_ENV);
304
- return errors.exitWithError(errors.errors.invalidCypressEnv)(`CYPRESS_INTERNAL_ENV=${CYPRESS_INTERNAL_ENV}`);
305
- }
306
- if (util.isNonProductionCypressInternalEnvValue(CYPRESS_INTERNAL_ENV)) {
307
- debug('non-production CYPRESS_INTERNAL_ENV value', CYPRESS_INTERNAL_ENV);
308
- let msg = `
309
- ${logSymbols.warning} Warning: It looks like you're passing CYPRESS_INTERNAL_ENV=${CYPRESS_INTERNAL_ENV}
360
+ logger_1.default.log();
361
+ logger_1.default.warn((0, common_tags_1.stripIndent)(msg));
362
+ logger_1.default.log();
363
+ }
364
+ if (!util_1.default.isValidCypressInternalEnvValue(CYPRESS_INTERNAL_ENV)) {
365
+ debug('invalid CYPRESS_INTERNAL_ENV value', CYPRESS_INTERNAL_ENV);
366
+ return (0, errors_1.exitWithError)(errors_1.errors.invalidCypressEnv)(`CYPRESS_INTERNAL_ENV=${CYPRESS_INTERNAL_ENV}`);
367
+ }
368
+ if (util_1.default.isNonProductionCypressInternalEnvValue(CYPRESS_INTERNAL_ENV)) {
369
+ debug('non-production CYPRESS_INTERNAL_ENV value', CYPRESS_INTERNAL_ENV);
370
+ let msg = `
371
+ ${log_symbols_1.default.warning} Warning: It looks like you're passing CYPRESS_INTERNAL_ENV=${CYPRESS_INTERNAL_ENV}
310
372
 
311
373
  The environment variable "CYPRESS_INTERNAL_ENV" is reserved and should only be used internally.
312
374
 
313
375
  Unset the "CYPRESS_INTERNAL_ENV" environment variable and run Cypress again.
314
376
  `;
315
- logger.log();
316
- logger.warn(stripIndent(msg));
317
- logger.log();
318
- }
319
- const program = createProgram();
320
- program.command('help').description('Shows CLI help and exits').action(() => {
321
- program.help();
322
- });
323
- const handleVersion = cmd => {
324
- return cmd.option('--component <package|binary|electron|node>', 'component to report version for').action((opts, ...other) => {
325
- showVersions(util.parseOpts(opts));
326
- });
327
- };
328
- handleVersion(program.storeOptionsAsProperties().option('-v, --version', text('version')).command('version').description(text('version')));
329
- maybeAddInspectFlags(addCypressOpenCommand(program)).action(opts => {
330
- debug('opening Cypress');
331
- require('./exec/open').start(util.parseOpts(opts)).then(util.exit).catch(util.logErrorExit1);
332
- });
333
- maybeAddInspectFlags(addCypressRunCommand(program)).action((...fnArgs) => {
334
- debug('running Cypress with args %o', fnArgs);
335
- require('./exec/run').start(parseVariableOpts(fnArgs, args)).then(util.exit).catch(util.logErrorExit1);
336
- });
337
- program.command('install').usage('[options]').description('Installs the Cypress executable matching this package\'s version').option('-f, --force', text('forceInstall')).action(opts => {
338
- require('./tasks/install').start(util.parseOpts(opts)).catch(util.logErrorExit1);
339
- });
340
- program.command('verify').usage('[options]').description('Verifies that Cypress is installed correctly and executable').option('--dev', text('dev'), coerceFalse).action(opts => {
341
- const defaultOpts = {
342
- force: true,
343
- welcomeMessage: false
344
- };
345
- const parsedOpts = util.parseOpts(opts);
346
- const options = _.extend(parsedOpts, defaultOpts);
347
- require('./tasks/verify').start(options).catch(util.logErrorExit1);
348
- });
349
- program.command('cache').usage('[command]').description('Manages the Cypress binary cache').option('list', text('cacheList')).option('path', text('cachePath')).option('clear', text('cacheClear')).option('prune', text('cachePrune')).option('--size', text('cacheSize')).action(function (opts, args) {
350
- if (!args || !args.length) {
351
- this.outputHelp();
352
- util.exit(1);
353
- }
354
- const [command] = args;
355
- if (!_.includes(['list', 'path', 'clear', 'prune'], command)) {
356
- unknownOption.call(this, `cache ${command}`, 'command');
357
- }
358
- if (command === 'list') {
359
- debug('cache command %o', {
360
- command,
361
- size: opts.size
377
+ logger_1.default.log();
378
+ logger_1.default.warn((0, common_tags_1.stripIndent)(msg));
379
+ logger_1.default.log();
380
+ }
381
+ const program = createProgram();
382
+ program
383
+ .command('help')
384
+ .description('Shows CLI help and exits')
385
+ .action(() => {
386
+ program.help();
362
387
  });
363
- return cache.list(opts.size).catch({
364
- code: 'ENOENT'
365
- }, () => {
366
- logger.always('No cached binary versions were found.');
367
- process.exit(0);
368
- }).catch(e => {
369
- debug('cache list command failed with "%s"', e.message);
370
- util.logErrorExit1(e);
388
+ const handleVersion = (cmd) => {
389
+ return cmd
390
+ .option('--component <package|binary|electron|node>', 'component to report version for')
391
+ .action((opts, ...other) => {
392
+ showVersions(util_1.default.parseOpts(opts));
393
+ });
394
+ };
395
+ handleVersion(program
396
+ .storeOptionsAsProperties()
397
+ .option('-v, --version', text('version'))
398
+ .command('version')
399
+ .description(text('version')));
400
+ maybeAddInspectFlags(addCypressOpenCommand(program))
401
+ .action((opts) => {
402
+ debug('opening Cypress');
403
+ open_1.default.start(util_1.default.parseOpts(opts))
404
+ .then(util_1.default.exit)
405
+ .catch(util_1.default.logErrorExit1);
371
406
  });
372
- }
373
- cache[command]();
374
- });
375
- program.command('info').usage('[command]').description('Prints Cypress and system information').option('--dev', text('dev'), coerceFalse).action(opts => {
376
- require('./exec/info').start(opts).then(util.exit).catch(util.logErrorExit1);
377
- });
378
- debug('cli starts with arguments %j', args);
379
- util.printNodeOptions();
380
-
381
- // if there are no arguments
382
- if (args.length <= 2) {
383
- debug('printing help');
384
- program.help();
385
- // exits
386
- }
387
- const firstCommand = args[2];
388
- if (!_.includes(knownCommands, firstCommand)) {
389
- debug('unknown command %s', firstCommand);
390
- logger.error('Unknown command', `"${firstCommand}"`);
391
- program.outputHelp();
392
- return util.exit(1);
393
- }
394
- if (includesVersion(args)) {
395
- // commander 2.11.0 changes behavior
396
- // and now does not understand top level options
397
- // .option('-v, --version').command('version')
398
- // so we have to manually catch '-v, --version'
399
- handleVersion(program);
400
- }
401
- debug('program parsing arguments');
402
- return program.parse(args);
403
- }
407
+ maybeAddInspectFlags(addCypressRunCommand(program))
408
+ .action((...fnArgs) => {
409
+ debug('running Cypress with args %o', fnArgs);
410
+ run_1.default.start(parseVariableOpts(fnArgs, args))
411
+ .then(util_1.default.exit)
412
+ .catch(util_1.default.logErrorExit1);
413
+ });
414
+ program
415
+ .command('install')
416
+ .usage('[options]')
417
+ .description('Installs the Cypress executable matching this package\'s version')
418
+ .option('-f, --force', text('forceInstall'))
419
+ .action((opts) => {
420
+ install_1.default
421
+ .start(util_1.default.parseOpts(opts))
422
+ .catch(util_1.default.logErrorExit1);
423
+ });
424
+ program
425
+ .command('verify')
426
+ .usage('[options]')
427
+ .description('Verifies that Cypress is installed correctly and executable')
428
+ .option('--dev', text('dev'), coerceFalse)
429
+ .action((opts) => {
430
+ const defaultOpts = { force: true, welcomeMessage: false };
431
+ const parsedOpts = util_1.default.parseOpts(opts);
432
+ const options = lodash_1.default.extend(parsedOpts, defaultOpts);
433
+ verify_1.default
434
+ .start(options)
435
+ .catch(util_1.default.logErrorExit1);
436
+ });
437
+ program
438
+ .command('cache')
439
+ .usage('[command]')
440
+ .description('Manages the Cypress binary cache')
441
+ .option('list', text('cacheList'))
442
+ .option('path', text('cachePath'))
443
+ .option('clear', text('cacheClear'))
444
+ .option('prune', text('cachePrune'))
445
+ .option('--size', text('cacheSize'))
446
+ .action(function (opts, args) {
447
+ if (!args || !args.length) {
448
+ this.outputHelp();
449
+ util_1.default.exit(1);
450
+ }
451
+ const [command] = args;
452
+ if (!lodash_1.default.includes(['list', 'path', 'clear', 'prune'], command)) {
453
+ unknownOption.call(this, `cache ${command}`, 'command');
454
+ }
455
+ if (command === 'list') {
456
+ debug('cache command %o', {
457
+ command,
458
+ size: opts.size,
459
+ });
460
+ return cache_1.default.list(opts.size)
461
+ .catch({ code: 'ENOENT' }, () => {
462
+ logger_1.default.always('No cached binary versions were found.');
463
+ process.exit(0);
464
+ })
465
+ .catch((e) => {
466
+ debug('cache list command failed with "%s"', e.message);
467
+ util_1.default.logErrorExit1(e);
468
+ });
469
+ }
470
+ cache_1.default[command]();
471
+ });
472
+ program
473
+ .command('info')
474
+ .usage('[command]')
475
+ .description('Prints Cypress and system information')
476
+ .option('--dev', text('dev'), coerceFalse)
477
+ .action((opts) => {
478
+ info_1.default
479
+ .start(opts)
480
+ .then(util_1.default.exit)
481
+ .catch(util_1.default.logErrorExit1);
482
+ });
483
+ debug('cli starts with arguments %j', args);
484
+ util_1.default.printNodeOptions();
485
+ // if there are no arguments
486
+ if (args.length <= 2) {
487
+ debug('printing help');
488
+ program.help();
489
+ // exits
490
+ }
491
+ const firstCommand = args[2];
492
+ if (!lodash_1.default.includes(knownCommands, firstCommand)) {
493
+ debug('unknown command %s', firstCommand);
494
+ logger_1.default.error('Unknown command', `"${firstCommand}"`);
495
+ program.outputHelp();
496
+ return util_1.default.exit(1);
497
+ }
498
+ if (includesVersion(args)) {
499
+ // commander 2.11.0 changes behavior
500
+ // and now does not understand top level options
501
+ // .option('-v, --version').command('version')
502
+ // so we have to manually catch '-v, --version'
503
+ handleVersion(program);
504
+ }
505
+ debug('program parsing arguments');
506
+ return program.parse(args);
507
+ },
404
508
  };
405
-
509
+ exports.default = cliModule;
406
510
  // @ts-ignore
407
511
  if (!module.parent) {
408
- logger.error('This CLI module should be required from another Node module');
409
- logger.error('and not executed directly');
410
- process.exit(-1);
411
- }
512
+ logger_1.default.error('This CLI module should be required from another Node module');
513
+ logger_1.default.error('and not executed directly');
514
+ process.exit(-1);
515
+ }