@pragmatic-divops/cli 1.7.186 → 1.8.0-alpha.11

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.
@@ -0,0 +1,2126 @@
1
+ #!/usr/bin/env node
2
+ import yargs from 'yargs';
3
+ import updateNotifier from 'update-notifier';
4
+ import { format, inspect } from 'util';
5
+ import { normalize, resolve, dirname, basename, extname, relative } from 'path';
6
+ import { readFileSync, statSync, readdirSync, writeFile } from 'fs';
7
+ import { notStrictEqual, strictEqual } from 'assert';
8
+ import { fileURLToPath } from 'url';
9
+ import { questionNames, scaffold as scaffold$8 } from '@form8ion/project';
10
+ import { scaffold as scaffold$7, predicate, lift as lift$2 } from '@form8ion/renovate-scaffolder';
11
+ import { scaffold, questionNames as questionNames$1, lift, test } from '@form8ion/javascript';
12
+ import { packageManagers } from '@form8ion/javascript-core';
13
+ import { prompt, scaffold as scaffold$6 } from '@travi/github-scaffolder';
14
+ import { scaffold as scaffold$1, test as test$1, lift as lift$3 } from '@form8ion/github-actions-node-ci';
15
+ import { scaffold as scaffold$5 } from '@form8ion/mocha-scaffolder';
16
+ import { scaffold as scaffold$4, extendEslintConfig } from '@form8ion/eslint-config-extender';
17
+ import { scaffold as scaffold$3 } from '@form8ion/gatsby';
18
+ import { scaffold as scaffold$2 } from '@travi/netlify-scaffolder';
19
+ import { lift as lift$1 } from '@form8ion/lift';
20
+ import { scaffold as scaffold$a } from '@form8ion/cucumber-scaffolder';
21
+ import { scaffold as scaffold$9 } from '@form8ion/codecov';
22
+
23
+ var name = "@pragmatic-divops/cli";
24
+ var description = "cli for various organization tools";
25
+ var license = "MIT";
26
+ var version = "1.8.0-alpha.11";
27
+ var type = "module";
28
+ var bin = {
29
+ "pragmatic-divops": "bin/pragmatic-divops.mjs"
30
+ };
31
+ var files = [
32
+ "bin/"
33
+ ];
34
+ var publishConfig = {
35
+ access: "public"
36
+ };
37
+ var repository = "pragmatic-divops/cli";
38
+ var bugs = "https://github.com/pragmatic-divops/cli/issues";
39
+ var homepage = "https://github.com/pragmatic-divops/cli#readme";
40
+ var author = "Matt Travi <npm@travi.org> (https://matt.travi.org/)";
41
+ var scripts = {
42
+ test: "npm-run-all --print-label --parallel lint:* --parallel test:*",
43
+ "lint:lockfile": "lockfile-lint --path package-lock.json --type npm --validate-https --allowed-hosts npm",
44
+ "lint:js": "eslint . --cache",
45
+ "lint:md": "remark . --frail",
46
+ "generate:md": "remark . --output",
47
+ "lint:sensitive": "ban",
48
+ clean: "rimraf ./bin",
49
+ prebuild: "run-s clean",
50
+ build: "npm-run-all --print-label --parallel build:*",
51
+ "build:js": "rollup --config",
52
+ watch: "run-s 'build:js -- --watch'",
53
+ prepack: "run-s build",
54
+ "test:unit": "cross-env NODE_ENV=test c8 run-s test:unit:base",
55
+ "test:unit:base": "DEBUG=any mocha --loader=testdouble 'src/**/*-test.js'",
56
+ "lint:peer": "npm ls >/dev/null",
57
+ "lint:gherkin": "gherkin-lint",
58
+ "test:integration": "run-s 'test:integration:base -- --profile noWip'",
59
+ "test:integration:base": "NODE_OPTIONS=\"--loader=testdouble\" DEBUG=any cucumber-js test/integration",
60
+ "test:integration:debug": "DEBUG=test run-s test:integration",
61
+ "test:integration:wip": "run-s 'test:integration:base -- --profile wip'",
62
+ "test:integration:wip:debug": "DEBUG=test run-s 'test:integration:wip'",
63
+ "test:integration:focus": "run-s 'test:integration:base -- --profile focus'",
64
+ prepare: "husky install"
65
+ };
66
+ var dependencies = {
67
+ "@form8ion/codecov": "3.0.1",
68
+ "@form8ion/cucumber-scaffolder": "2.0.1",
69
+ "@form8ion/eslint-config-extender": "4.0.0",
70
+ "@form8ion/gatsby": "1.0.1",
71
+ "@form8ion/github-actions-node-ci": "3.8.0",
72
+ "@form8ion/javascript": "7.2.1",
73
+ "@form8ion/javascript-core": "6.0.1",
74
+ "@form8ion/lift": "4.1.0",
75
+ "@form8ion/mocha-scaffolder": "2.0.2",
76
+ "@form8ion/project": "13.2.1",
77
+ "@form8ion/renovate-scaffolder": "1.7.0",
78
+ "@travi/github-scaffolder": "8.0.2",
79
+ "@travi/netlify-scaffolder": "1.6.0",
80
+ "update-notifier": "6.0.2",
81
+ yargs: "17.5.1"
82
+ };
83
+ var devDependencies = {
84
+ "@cucumber/cucumber": "8.5.0",
85
+ "@form8ion/core": "1.8.0",
86
+ "@pragmatic-divops/commitlint-config": "1.0.22",
87
+ "@pragmatic-divops/eslint-config": "1.0.46",
88
+ "@pragmatic-divops/eslint-config-cucumber": "1.0.1",
89
+ "@pragmatic-divops/eslint-config-mocha": "1.0.8",
90
+ "@pragmatic-divops/remark-preset": "3.0.0",
91
+ "@rollup/plugin-node-resolve": "13.3.0",
92
+ "@travi/any": "2.1.5",
93
+ "ban-sensitive-files": "1.9.18",
94
+ c8: "7.12.0",
95
+ chai: "4.3.6",
96
+ "cross-env": "7.0.3",
97
+ "cz-conventional-changelog": "3.3.0",
98
+ "gherkin-lint": "4.2.2",
99
+ "http-status-codes": "2.2.0",
100
+ husky: "8.0.1",
101
+ "lockfile-lint": "4.7.6",
102
+ mocha: "10.0.0",
103
+ "mock-fs": "5.1.2",
104
+ nock: "13.2.9",
105
+ "npm-run-all": "4.1.5",
106
+ "remark-cli": "11.0.0",
107
+ "remark-toc": "8.0.1",
108
+ rimraf: "3.0.2",
109
+ rollup: "2.77.0",
110
+ "rollup-plugin-auto-external": "2.0.0",
111
+ "rollup-plugin-executable": "1.6.3",
112
+ "rollup-plugin-json": "4.0.0",
113
+ sinon: "14.0.0",
114
+ testdouble: "3.16.6"
115
+ };
116
+ var pkg = {
117
+ name: name,
118
+ description: description,
119
+ license: license,
120
+ version: version,
121
+ type: type,
122
+ bin: bin,
123
+ files: files,
124
+ publishConfig: publishConfig,
125
+ repository: repository,
126
+ bugs: bugs,
127
+ homepage: homepage,
128
+ author: author,
129
+ scripts: scripts,
130
+ dependencies: dependencies,
131
+ devDependencies: devDependencies
132
+ };
133
+
134
+ class YError extends Error {
135
+ constructor(msg) {
136
+ super(msg || 'yargs error');
137
+ this.name = 'YError';
138
+ if (Error.captureStackTrace) {
139
+ Error.captureStackTrace(this, YError);
140
+ }
141
+ }
142
+ }
143
+
144
+ function getProcessArgvBinIndex() {
145
+ if (isBundledElectronApp())
146
+ return 0;
147
+ return 1;
148
+ }
149
+ function isBundledElectronApp() {
150
+ return isElectronApp() && !process.defaultApp;
151
+ }
152
+ function isElectronApp() {
153
+ return !!process.versions.electron;
154
+ }
155
+ function hideBin(argv) {
156
+ return argv.slice(getProcessArgvBinIndex() + 1);
157
+ }
158
+ function getProcessArgvBin() {
159
+ return process.argv[getProcessArgvBinIndex()];
160
+ }
161
+
162
+ /**
163
+ * @license
164
+ * Copyright (c) 2016, Contributors
165
+ * SPDX-License-Identifier: ISC
166
+ */
167
+ function camelCase(str) {
168
+ // Handle the case where an argument is provided as camel case, e.g., fooBar.
169
+ // by ensuring that the string isn't already mixed case:
170
+ const isCamelCase = str !== str.toLowerCase() && str !== str.toUpperCase();
171
+ if (!isCamelCase) {
172
+ str = str.toLowerCase();
173
+ }
174
+ if (str.indexOf('-') === -1 && str.indexOf('_') === -1) {
175
+ return str;
176
+ }
177
+ else {
178
+ let camelcase = '';
179
+ let nextChrUpper = false;
180
+ const leadingHyphens = str.match(/^-+/);
181
+ for (let i = leadingHyphens ? leadingHyphens[0].length : 0; i < str.length; i++) {
182
+ let chr = str.charAt(i);
183
+ if (nextChrUpper) {
184
+ nextChrUpper = false;
185
+ chr = chr.toUpperCase();
186
+ }
187
+ if (i !== 0 && (chr === '-' || chr === '_')) {
188
+ nextChrUpper = true;
189
+ }
190
+ else if (chr !== '-' && chr !== '_') {
191
+ camelcase += chr;
192
+ }
193
+ }
194
+ return camelcase;
195
+ }
196
+ }
197
+ function decamelize(str, joinString) {
198
+ const lowercase = str.toLowerCase();
199
+ joinString = joinString || '-';
200
+ let notCamelcase = '';
201
+ for (let i = 0; i < str.length; i++) {
202
+ const chrLower = lowercase.charAt(i);
203
+ const chrString = str.charAt(i);
204
+ if (chrLower !== chrString && i > 0) {
205
+ notCamelcase += `${joinString}${lowercase.charAt(i)}`;
206
+ }
207
+ else {
208
+ notCamelcase += chrString;
209
+ }
210
+ }
211
+ return notCamelcase;
212
+ }
213
+ function looksLikeNumber(x) {
214
+ if (x === null || x === undefined)
215
+ return false;
216
+ // if loaded from config, may already be a number.
217
+ if (typeof x === 'number')
218
+ return true;
219
+ // hexadecimal.
220
+ if (/^0x[0-9a-f]+$/i.test(x))
221
+ return true;
222
+ // don't treat 0123 as a number; as it drops the leading '0'.
223
+ if (/^0[^.]/.test(x))
224
+ return false;
225
+ return /^[-]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x);
226
+ }
227
+
228
+ /**
229
+ * @license
230
+ * Copyright (c) 2016, Contributors
231
+ * SPDX-License-Identifier: ISC
232
+ */
233
+ // take an un-split argv string and tokenize it.
234
+ function tokenizeArgString(argString) {
235
+ if (Array.isArray(argString)) {
236
+ return argString.map(e => typeof e !== 'string' ? e + '' : e);
237
+ }
238
+ argString = argString.trim();
239
+ let i = 0;
240
+ let prevC = null;
241
+ let c = null;
242
+ let opening = null;
243
+ const args = [];
244
+ for (let ii = 0; ii < argString.length; ii++) {
245
+ prevC = c;
246
+ c = argString.charAt(ii);
247
+ // split on spaces unless we're in quotes.
248
+ if (c === ' ' && !opening) {
249
+ if (!(prevC === ' ')) {
250
+ i++;
251
+ }
252
+ continue;
253
+ }
254
+ // don't split the string if we're in matching
255
+ // opening or closing single and double quotes.
256
+ if (c === opening) {
257
+ opening = null;
258
+ }
259
+ else if ((c === "'" || c === '"') && !opening) {
260
+ opening = c;
261
+ }
262
+ if (!args[i])
263
+ args[i] = '';
264
+ args[i] += c;
265
+ }
266
+ return args;
267
+ }
268
+
269
+ /**
270
+ * @license
271
+ * Copyright (c) 2016, Contributors
272
+ * SPDX-License-Identifier: ISC
273
+ */
274
+ var DefaultValuesForTypeKey;
275
+ (function (DefaultValuesForTypeKey) {
276
+ DefaultValuesForTypeKey["BOOLEAN"] = "boolean";
277
+ DefaultValuesForTypeKey["STRING"] = "string";
278
+ DefaultValuesForTypeKey["NUMBER"] = "number";
279
+ DefaultValuesForTypeKey["ARRAY"] = "array";
280
+ })(DefaultValuesForTypeKey || (DefaultValuesForTypeKey = {}));
281
+
282
+ /**
283
+ * @license
284
+ * Copyright (c) 2016, Contributors
285
+ * SPDX-License-Identifier: ISC
286
+ */
287
+ let mixin$1;
288
+ class YargsParser {
289
+ constructor(_mixin) {
290
+ mixin$1 = _mixin;
291
+ }
292
+ parse(argsInput, options) {
293
+ const opts = Object.assign({
294
+ alias: undefined,
295
+ array: undefined,
296
+ boolean: undefined,
297
+ config: undefined,
298
+ configObjects: undefined,
299
+ configuration: undefined,
300
+ coerce: undefined,
301
+ count: undefined,
302
+ default: undefined,
303
+ envPrefix: undefined,
304
+ narg: undefined,
305
+ normalize: undefined,
306
+ string: undefined,
307
+ number: undefined,
308
+ __: undefined,
309
+ key: undefined
310
+ }, options);
311
+ // allow a string argument to be passed in rather
312
+ // than an argv array.
313
+ const args = tokenizeArgString(argsInput);
314
+ // tokenizeArgString adds extra quotes to args if argsInput is a string
315
+ // only strip those extra quotes in processValue if argsInput is a string
316
+ const inputIsString = typeof argsInput === 'string';
317
+ // aliases might have transitive relationships, normalize this.
318
+ const aliases = combineAliases(Object.assign(Object.create(null), opts.alias));
319
+ const configuration = Object.assign({
320
+ 'boolean-negation': true,
321
+ 'camel-case-expansion': true,
322
+ 'combine-arrays': false,
323
+ 'dot-notation': true,
324
+ 'duplicate-arguments-array': true,
325
+ 'flatten-duplicate-arrays': true,
326
+ 'greedy-arrays': true,
327
+ 'halt-at-non-option': false,
328
+ 'nargs-eats-options': false,
329
+ 'negation-prefix': 'no-',
330
+ 'parse-numbers': true,
331
+ 'parse-positional-numbers': true,
332
+ 'populate--': false,
333
+ 'set-placeholder-key': false,
334
+ 'short-option-groups': true,
335
+ 'strip-aliased': false,
336
+ 'strip-dashed': false,
337
+ 'unknown-options-as-args': false
338
+ }, opts.configuration);
339
+ const defaults = Object.assign(Object.create(null), opts.default);
340
+ const configObjects = opts.configObjects || [];
341
+ const envPrefix = opts.envPrefix;
342
+ const notFlagsOption = configuration['populate--'];
343
+ const notFlagsArgv = notFlagsOption ? '--' : '_';
344
+ const newAliases = Object.create(null);
345
+ const defaulted = Object.create(null);
346
+ // allow a i18n handler to be passed in, default to a fake one (util.format).
347
+ const __ = opts.__ || mixin$1.format;
348
+ const flags = {
349
+ aliases: Object.create(null),
350
+ arrays: Object.create(null),
351
+ bools: Object.create(null),
352
+ strings: Object.create(null),
353
+ numbers: Object.create(null),
354
+ counts: Object.create(null),
355
+ normalize: Object.create(null),
356
+ configs: Object.create(null),
357
+ nargs: Object.create(null),
358
+ coercions: Object.create(null),
359
+ keys: []
360
+ };
361
+ const negative = /^-([0-9]+(\.[0-9]+)?|\.[0-9]+)$/;
362
+ const negatedBoolean = new RegExp('^--' + configuration['negation-prefix'] + '(.+)');
363
+ [].concat(opts.array || []).filter(Boolean).forEach(function (opt) {
364
+ const key = typeof opt === 'object' ? opt.key : opt;
365
+ // assign to flags[bools|strings|numbers]
366
+ const assignment = Object.keys(opt).map(function (key) {
367
+ const arrayFlagKeys = {
368
+ boolean: 'bools',
369
+ string: 'strings',
370
+ number: 'numbers'
371
+ };
372
+ return arrayFlagKeys[key];
373
+ }).filter(Boolean).pop();
374
+ // assign key to be coerced
375
+ if (assignment) {
376
+ flags[assignment][key] = true;
377
+ }
378
+ flags.arrays[key] = true;
379
+ flags.keys.push(key);
380
+ });
381
+ [].concat(opts.boolean || []).filter(Boolean).forEach(function (key) {
382
+ flags.bools[key] = true;
383
+ flags.keys.push(key);
384
+ });
385
+ [].concat(opts.string || []).filter(Boolean).forEach(function (key) {
386
+ flags.strings[key] = true;
387
+ flags.keys.push(key);
388
+ });
389
+ [].concat(opts.number || []).filter(Boolean).forEach(function (key) {
390
+ flags.numbers[key] = true;
391
+ flags.keys.push(key);
392
+ });
393
+ [].concat(opts.count || []).filter(Boolean).forEach(function (key) {
394
+ flags.counts[key] = true;
395
+ flags.keys.push(key);
396
+ });
397
+ [].concat(opts.normalize || []).filter(Boolean).forEach(function (key) {
398
+ flags.normalize[key] = true;
399
+ flags.keys.push(key);
400
+ });
401
+ if (typeof opts.narg === 'object') {
402
+ Object.entries(opts.narg).forEach(([key, value]) => {
403
+ if (typeof value === 'number') {
404
+ flags.nargs[key] = value;
405
+ flags.keys.push(key);
406
+ }
407
+ });
408
+ }
409
+ if (typeof opts.coerce === 'object') {
410
+ Object.entries(opts.coerce).forEach(([key, value]) => {
411
+ if (typeof value === 'function') {
412
+ flags.coercions[key] = value;
413
+ flags.keys.push(key);
414
+ }
415
+ });
416
+ }
417
+ if (typeof opts.config !== 'undefined') {
418
+ if (Array.isArray(opts.config) || typeof opts.config === 'string') {
419
+ [].concat(opts.config).filter(Boolean).forEach(function (key) {
420
+ flags.configs[key] = true;
421
+ });
422
+ }
423
+ else if (typeof opts.config === 'object') {
424
+ Object.entries(opts.config).forEach(([key, value]) => {
425
+ if (typeof value === 'boolean' || typeof value === 'function') {
426
+ flags.configs[key] = value;
427
+ }
428
+ });
429
+ }
430
+ }
431
+ // create a lookup table that takes into account all
432
+ // combinations of aliases: {f: ['foo'], foo: ['f']}
433
+ extendAliases(opts.key, aliases, opts.default, flags.arrays);
434
+ // apply default values to all aliases.
435
+ Object.keys(defaults).forEach(function (key) {
436
+ (flags.aliases[key] || []).forEach(function (alias) {
437
+ defaults[alias] = defaults[key];
438
+ });
439
+ });
440
+ let error = null;
441
+ checkConfiguration();
442
+ let notFlags = [];
443
+ const argv = Object.assign(Object.create(null), { _: [] });
444
+ // TODO(bcoe): for the first pass at removing object prototype we didn't
445
+ // remove all prototypes from objects returned by this API, we might want
446
+ // to gradually move towards doing so.
447
+ const argvReturn = {};
448
+ for (let i = 0; i < args.length; i++) {
449
+ const arg = args[i];
450
+ const truncatedArg = arg.replace(/^-{3,}/, '---');
451
+ let broken;
452
+ let key;
453
+ let letters;
454
+ let m;
455
+ let next;
456
+ let value;
457
+ // any unknown option (except for end-of-options, "--")
458
+ if (arg !== '--' && isUnknownOptionAsArg(arg)) {
459
+ pushPositional(arg);
460
+ // ---, ---=, ----, etc,
461
+ }
462
+ else if (truncatedArg.match(/---+(=|$)/)) {
463
+ // options without key name are invalid.
464
+ pushPositional(arg);
465
+ continue;
466
+ // -- separated by =
467
+ }
468
+ else if (arg.match(/^--.+=/) || (!configuration['short-option-groups'] && arg.match(/^-.+=/))) {
469
+ // Using [\s\S] instead of . because js doesn't support the
470
+ // 'dotall' regex modifier. See:
471
+ // http://stackoverflow.com/a/1068308/13216
472
+ m = arg.match(/^--?([^=]+)=([\s\S]*)$/);
473
+ // arrays format = '--f=a b c'
474
+ if (m !== null && Array.isArray(m) && m.length >= 3) {
475
+ if (checkAllAliases(m[1], flags.arrays)) {
476
+ i = eatArray(i, m[1], args, m[2]);
477
+ }
478
+ else if (checkAllAliases(m[1], flags.nargs) !== false) {
479
+ // nargs format = '--f=monkey washing cat'
480
+ i = eatNargs(i, m[1], args, m[2]);
481
+ }
482
+ else {
483
+ setArg(m[1], m[2], true);
484
+ }
485
+ }
486
+ }
487
+ else if (arg.match(negatedBoolean) && configuration['boolean-negation']) {
488
+ m = arg.match(negatedBoolean);
489
+ if (m !== null && Array.isArray(m) && m.length >= 2) {
490
+ key = m[1];
491
+ setArg(key, checkAllAliases(key, flags.arrays) ? [false] : false);
492
+ }
493
+ // -- separated by space.
494
+ }
495
+ else if (arg.match(/^--.+/) || (!configuration['short-option-groups'] && arg.match(/^-[^-]+/))) {
496
+ m = arg.match(/^--?(.+)/);
497
+ if (m !== null && Array.isArray(m) && m.length >= 2) {
498
+ key = m[1];
499
+ if (checkAllAliases(key, flags.arrays)) {
500
+ // array format = '--foo a b c'
501
+ i = eatArray(i, key, args);
502
+ }
503
+ else if (checkAllAliases(key, flags.nargs) !== false) {
504
+ // nargs format = '--foo a b c'
505
+ // should be truthy even if: flags.nargs[key] === 0
506
+ i = eatNargs(i, key, args);
507
+ }
508
+ else {
509
+ next = args[i + 1];
510
+ if (next !== undefined && (!next.match(/^-/) ||
511
+ next.match(negative)) &&
512
+ !checkAllAliases(key, flags.bools) &&
513
+ !checkAllAliases(key, flags.counts)) {
514
+ setArg(key, next);
515
+ i++;
516
+ }
517
+ else if (/^(true|false)$/.test(next)) {
518
+ setArg(key, next);
519
+ i++;
520
+ }
521
+ else {
522
+ setArg(key, defaultValue(key));
523
+ }
524
+ }
525
+ }
526
+ // dot-notation flag separated by '='.
527
+ }
528
+ else if (arg.match(/^-.\..+=/)) {
529
+ m = arg.match(/^-([^=]+)=([\s\S]*)$/);
530
+ if (m !== null && Array.isArray(m) && m.length >= 3) {
531
+ setArg(m[1], m[2]);
532
+ }
533
+ // dot-notation flag separated by space.
534
+ }
535
+ else if (arg.match(/^-.\..+/) && !arg.match(negative)) {
536
+ next = args[i + 1];
537
+ m = arg.match(/^-(.\..+)/);
538
+ if (m !== null && Array.isArray(m) && m.length >= 2) {
539
+ key = m[1];
540
+ if (next !== undefined && !next.match(/^-/) &&
541
+ !checkAllAliases(key, flags.bools) &&
542
+ !checkAllAliases(key, flags.counts)) {
543
+ setArg(key, next);
544
+ i++;
545
+ }
546
+ else {
547
+ setArg(key, defaultValue(key));
548
+ }
549
+ }
550
+ }
551
+ else if (arg.match(/^-[^-]+/) && !arg.match(negative)) {
552
+ letters = arg.slice(1, -1).split('');
553
+ broken = false;
554
+ for (let j = 0; j < letters.length; j++) {
555
+ next = arg.slice(j + 2);
556
+ if (letters[j + 1] && letters[j + 1] === '=') {
557
+ value = arg.slice(j + 3);
558
+ key = letters[j];
559
+ if (checkAllAliases(key, flags.arrays)) {
560
+ // array format = '-f=a b c'
561
+ i = eatArray(i, key, args, value);
562
+ }
563
+ else if (checkAllAliases(key, flags.nargs) !== false) {
564
+ // nargs format = '-f=monkey washing cat'
565
+ i = eatNargs(i, key, args, value);
566
+ }
567
+ else {
568
+ setArg(key, value);
569
+ }
570
+ broken = true;
571
+ break;
572
+ }
573
+ if (next === '-') {
574
+ setArg(letters[j], next);
575
+ continue;
576
+ }
577
+ // current letter is an alphabetic character and next value is a number
578
+ if (/[A-Za-z]/.test(letters[j]) &&
579
+ /^-?\d+(\.\d*)?(e-?\d+)?$/.test(next) &&
580
+ checkAllAliases(next, flags.bools) === false) {
581
+ setArg(letters[j], next);
582
+ broken = true;
583
+ break;
584
+ }
585
+ if (letters[j + 1] && letters[j + 1].match(/\W/)) {
586
+ setArg(letters[j], next);
587
+ broken = true;
588
+ break;
589
+ }
590
+ else {
591
+ setArg(letters[j], defaultValue(letters[j]));
592
+ }
593
+ }
594
+ key = arg.slice(-1)[0];
595
+ if (!broken && key !== '-') {
596
+ if (checkAllAliases(key, flags.arrays)) {
597
+ // array format = '-f a b c'
598
+ i = eatArray(i, key, args);
599
+ }
600
+ else if (checkAllAliases(key, flags.nargs) !== false) {
601
+ // nargs format = '-f a b c'
602
+ // should be truthy even if: flags.nargs[key] === 0
603
+ i = eatNargs(i, key, args);
604
+ }
605
+ else {
606
+ next = args[i + 1];
607
+ if (next !== undefined && (!/^(-|--)[^-]/.test(next) ||
608
+ next.match(negative)) &&
609
+ !checkAllAliases(key, flags.bools) &&
610
+ !checkAllAliases(key, flags.counts)) {
611
+ setArg(key, next);
612
+ i++;
613
+ }
614
+ else if (/^(true|false)$/.test(next)) {
615
+ setArg(key, next);
616
+ i++;
617
+ }
618
+ else {
619
+ setArg(key, defaultValue(key));
620
+ }
621
+ }
622
+ }
623
+ }
624
+ else if (arg.match(/^-[0-9]$/) &&
625
+ arg.match(negative) &&
626
+ checkAllAliases(arg.slice(1), flags.bools)) {
627
+ // single-digit boolean alias, e.g: xargs -0
628
+ key = arg.slice(1);
629
+ setArg(key, defaultValue(key));
630
+ }
631
+ else if (arg === '--') {
632
+ notFlags = args.slice(i + 1);
633
+ break;
634
+ }
635
+ else if (configuration['halt-at-non-option']) {
636
+ notFlags = args.slice(i);
637
+ break;
638
+ }
639
+ else {
640
+ pushPositional(arg);
641
+ }
642
+ }
643
+ // order of precedence:
644
+ // 1. command line arg
645
+ // 2. value from env var
646
+ // 3. value from config file
647
+ // 4. value from config objects
648
+ // 5. configured default value
649
+ applyEnvVars(argv, true); // special case: check env vars that point to config file
650
+ applyEnvVars(argv, false);
651
+ setConfig(argv);
652
+ setConfigObjects();
653
+ applyDefaultsAndAliases(argv, flags.aliases, defaults, true);
654
+ applyCoercions(argv);
655
+ if (configuration['set-placeholder-key'])
656
+ setPlaceholderKeys(argv);
657
+ // for any counts either not in args or without an explicit default, set to 0
658
+ Object.keys(flags.counts).forEach(function (key) {
659
+ if (!hasKey(argv, key.split('.')))
660
+ setArg(key, 0);
661
+ });
662
+ // '--' defaults to undefined.
663
+ if (notFlagsOption && notFlags.length)
664
+ argv[notFlagsArgv] = [];
665
+ notFlags.forEach(function (key) {
666
+ argv[notFlagsArgv].push(key);
667
+ });
668
+ if (configuration['camel-case-expansion'] && configuration['strip-dashed']) {
669
+ Object.keys(argv).filter(key => key !== '--' && key.includes('-')).forEach(key => {
670
+ delete argv[key];
671
+ });
672
+ }
673
+ if (configuration['strip-aliased']) {
674
+ [].concat(...Object.keys(aliases).map(k => aliases[k])).forEach(alias => {
675
+ if (configuration['camel-case-expansion'] && alias.includes('-')) {
676
+ delete argv[alias.split('.').map(prop => camelCase(prop)).join('.')];
677
+ }
678
+ delete argv[alias];
679
+ });
680
+ }
681
+ // Push argument into positional array, applying numeric coercion:
682
+ function pushPositional(arg) {
683
+ const maybeCoercedNumber = maybeCoerceNumber('_', arg);
684
+ if (typeof maybeCoercedNumber === 'string' || typeof maybeCoercedNumber === 'number') {
685
+ argv._.push(maybeCoercedNumber);
686
+ }
687
+ }
688
+ // how many arguments should we consume, based
689
+ // on the nargs option?
690
+ function eatNargs(i, key, args, argAfterEqualSign) {
691
+ let ii;
692
+ let toEat = checkAllAliases(key, flags.nargs);
693
+ // NaN has a special meaning for the array type, indicating that one or
694
+ // more values are expected.
695
+ toEat = typeof toEat !== 'number' || isNaN(toEat) ? 1 : toEat;
696
+ if (toEat === 0) {
697
+ if (!isUndefined(argAfterEqualSign)) {
698
+ error = Error(__('Argument unexpected for: %s', key));
699
+ }
700
+ setArg(key, defaultValue(key));
701
+ return i;
702
+ }
703
+ let available = isUndefined(argAfterEqualSign) ? 0 : 1;
704
+ if (configuration['nargs-eats-options']) {
705
+ // classic behavior, yargs eats positional and dash arguments.
706
+ if (args.length - (i + 1) + available < toEat) {
707
+ error = Error(__('Not enough arguments following: %s', key));
708
+ }
709
+ available = toEat;
710
+ }
711
+ else {
712
+ // nargs will not consume flag arguments, e.g., -abc, --foo,
713
+ // and terminates when one is observed.
714
+ for (ii = i + 1; ii < args.length; ii++) {
715
+ if (!args[ii].match(/^-[^0-9]/) || args[ii].match(negative) || isUnknownOptionAsArg(args[ii]))
716
+ available++;
717
+ else
718
+ break;
719
+ }
720
+ if (available < toEat)
721
+ error = Error(__('Not enough arguments following: %s', key));
722
+ }
723
+ let consumed = Math.min(available, toEat);
724
+ if (!isUndefined(argAfterEqualSign) && consumed > 0) {
725
+ setArg(key, argAfterEqualSign);
726
+ consumed--;
727
+ }
728
+ for (ii = i + 1; ii < (consumed + i + 1); ii++) {
729
+ setArg(key, args[ii]);
730
+ }
731
+ return (i + consumed);
732
+ }
733
+ // if an option is an array, eat all non-hyphenated arguments
734
+ // following it... YUM!
735
+ // e.g., --foo apple banana cat becomes ["apple", "banana", "cat"]
736
+ function eatArray(i, key, args, argAfterEqualSign) {
737
+ let argsToSet = [];
738
+ let next = argAfterEqualSign || args[i + 1];
739
+ // If both array and nargs are configured, enforce the nargs count:
740
+ const nargsCount = checkAllAliases(key, flags.nargs);
741
+ if (checkAllAliases(key, flags.bools) && !(/^(true|false)$/.test(next))) {
742
+ argsToSet.push(true);
743
+ }
744
+ else if (isUndefined(next) ||
745
+ (isUndefined(argAfterEqualSign) && /^-/.test(next) && !negative.test(next) && !isUnknownOptionAsArg(next))) {
746
+ // for keys without value ==> argsToSet remains an empty []
747
+ // set user default value, if available
748
+ if (defaults[key] !== undefined) {
749
+ const defVal = defaults[key];
750
+ argsToSet = Array.isArray(defVal) ? defVal : [defVal];
751
+ }
752
+ }
753
+ else {
754
+ // value in --option=value is eaten as is
755
+ if (!isUndefined(argAfterEqualSign)) {
756
+ argsToSet.push(processValue(key, argAfterEqualSign, true));
757
+ }
758
+ for (let ii = i + 1; ii < args.length; ii++) {
759
+ if ((!configuration['greedy-arrays'] && argsToSet.length > 0) ||
760
+ (nargsCount && typeof nargsCount === 'number' && argsToSet.length >= nargsCount))
761
+ break;
762
+ next = args[ii];
763
+ if (/^-/.test(next) && !negative.test(next) && !isUnknownOptionAsArg(next))
764
+ break;
765
+ i = ii;
766
+ argsToSet.push(processValue(key, next, inputIsString));
767
+ }
768
+ }
769
+ // If both array and nargs are configured, create an error if less than
770
+ // nargs positionals were found. NaN has special meaning, indicating
771
+ // that at least one value is required (more are okay).
772
+ if (typeof nargsCount === 'number' && ((nargsCount && argsToSet.length < nargsCount) ||
773
+ (isNaN(nargsCount) && argsToSet.length === 0))) {
774
+ error = Error(__('Not enough arguments following: %s', key));
775
+ }
776
+ setArg(key, argsToSet);
777
+ return i;
778
+ }
779
+ function setArg(key, val, shouldStripQuotes = inputIsString) {
780
+ if (/-/.test(key) && configuration['camel-case-expansion']) {
781
+ const alias = key.split('.').map(function (prop) {
782
+ return camelCase(prop);
783
+ }).join('.');
784
+ addNewAlias(key, alias);
785
+ }
786
+ const value = processValue(key, val, shouldStripQuotes);
787
+ const splitKey = key.split('.');
788
+ setKey(argv, splitKey, value);
789
+ // handle populating aliases of the full key
790
+ if (flags.aliases[key]) {
791
+ flags.aliases[key].forEach(function (x) {
792
+ const keyProperties = x.split('.');
793
+ setKey(argv, keyProperties, value);
794
+ });
795
+ }
796
+ // handle populating aliases of the first element of the dot-notation key
797
+ if (splitKey.length > 1 && configuration['dot-notation']) {
798
+ (flags.aliases[splitKey[0]] || []).forEach(function (x) {
799
+ let keyProperties = x.split('.');
800
+ // expand alias with nested objects in key
801
+ const a = [].concat(splitKey);
802
+ a.shift(); // nuke the old key.
803
+ keyProperties = keyProperties.concat(a);
804
+ // populate alias only if is not already an alias of the full key
805
+ // (already populated above)
806
+ if (!(flags.aliases[key] || []).includes(keyProperties.join('.'))) {
807
+ setKey(argv, keyProperties, value);
808
+ }
809
+ });
810
+ }
811
+ // Set normalize getter and setter when key is in 'normalize' but isn't an array
812
+ if (checkAllAliases(key, flags.normalize) && !checkAllAliases(key, flags.arrays)) {
813
+ const keys = [key].concat(flags.aliases[key] || []);
814
+ keys.forEach(function (key) {
815
+ Object.defineProperty(argvReturn, key, {
816
+ enumerable: true,
817
+ get() {
818
+ return val;
819
+ },
820
+ set(value) {
821
+ val = typeof value === 'string' ? mixin$1.normalize(value) : value;
822
+ }
823
+ });
824
+ });
825
+ }
826
+ }
827
+ function addNewAlias(key, alias) {
828
+ if (!(flags.aliases[key] && flags.aliases[key].length)) {
829
+ flags.aliases[key] = [alias];
830
+ newAliases[alias] = true;
831
+ }
832
+ if (!(flags.aliases[alias] && flags.aliases[alias].length)) {
833
+ addNewAlias(alias, key);
834
+ }
835
+ }
836
+ function processValue(key, val, shouldStripQuotes) {
837
+ // strings may be quoted, clean this up as we assign values.
838
+ if (shouldStripQuotes) {
839
+ val = stripQuotes(val);
840
+ }
841
+ // handle parsing boolean arguments --foo=true --bar false.
842
+ if (checkAllAliases(key, flags.bools) || checkAllAliases(key, flags.counts)) {
843
+ if (typeof val === 'string')
844
+ val = val === 'true';
845
+ }
846
+ let value = Array.isArray(val)
847
+ ? val.map(function (v) { return maybeCoerceNumber(key, v); })
848
+ : maybeCoerceNumber(key, val);
849
+ // increment a count given as arg (either no value or value parsed as boolean)
850
+ if (checkAllAliases(key, flags.counts) && (isUndefined(value) || typeof value === 'boolean')) {
851
+ value = increment();
852
+ }
853
+ // Set normalized value when key is in 'normalize' and in 'arrays'
854
+ if (checkAllAliases(key, flags.normalize) && checkAllAliases(key, flags.arrays)) {
855
+ if (Array.isArray(val))
856
+ value = val.map((val) => { return mixin$1.normalize(val); });
857
+ else
858
+ value = mixin$1.normalize(val);
859
+ }
860
+ return value;
861
+ }
862
+ function maybeCoerceNumber(key, value) {
863
+ if (!configuration['parse-positional-numbers'] && key === '_')
864
+ return value;
865
+ if (!checkAllAliases(key, flags.strings) && !checkAllAliases(key, flags.bools) && !Array.isArray(value)) {
866
+ const shouldCoerceNumber = looksLikeNumber(value) && configuration['parse-numbers'] && (Number.isSafeInteger(Math.floor(parseFloat(`${value}`))));
867
+ if (shouldCoerceNumber || (!isUndefined(value) && checkAllAliases(key, flags.numbers))) {
868
+ value = Number(value);
869
+ }
870
+ }
871
+ return value;
872
+ }
873
+ // set args from config.json file, this should be
874
+ // applied last so that defaults can be applied.
875
+ function setConfig(argv) {
876
+ const configLookup = Object.create(null);
877
+ // expand defaults/aliases, in-case any happen to reference
878
+ // the config.json file.
879
+ applyDefaultsAndAliases(configLookup, flags.aliases, defaults);
880
+ Object.keys(flags.configs).forEach(function (configKey) {
881
+ const configPath = argv[configKey] || configLookup[configKey];
882
+ if (configPath) {
883
+ try {
884
+ let config = null;
885
+ const resolvedConfigPath = mixin$1.resolve(mixin$1.cwd(), configPath);
886
+ const resolveConfig = flags.configs[configKey];
887
+ if (typeof resolveConfig === 'function') {
888
+ try {
889
+ config = resolveConfig(resolvedConfigPath);
890
+ }
891
+ catch (e) {
892
+ config = e;
893
+ }
894
+ if (config instanceof Error) {
895
+ error = config;
896
+ return;
897
+ }
898
+ }
899
+ else {
900
+ config = mixin$1.require(resolvedConfigPath);
901
+ }
902
+ setConfigObject(config);
903
+ }
904
+ catch (ex) {
905
+ // Deno will receive a PermissionDenied error if an attempt is
906
+ // made to load config without the --allow-read flag:
907
+ if (ex.name === 'PermissionDenied')
908
+ error = ex;
909
+ else if (argv[configKey])
910
+ error = Error(__('Invalid JSON config file: %s', configPath));
911
+ }
912
+ }
913
+ });
914
+ }
915
+ // set args from config object.
916
+ // it recursively checks nested objects.
917
+ function setConfigObject(config, prev) {
918
+ Object.keys(config).forEach(function (key) {
919
+ const value = config[key];
920
+ const fullKey = prev ? prev + '.' + key : key;
921
+ // if the value is an inner object and we have dot-notation
922
+ // enabled, treat inner objects in config the same as
923
+ // heavily nested dot notations (foo.bar.apple).
924
+ if (typeof value === 'object' && value !== null && !Array.isArray(value) && configuration['dot-notation']) {
925
+ // if the value is an object but not an array, check nested object
926
+ setConfigObject(value, fullKey);
927
+ }
928
+ else {
929
+ // setting arguments via CLI takes precedence over
930
+ // values within the config file.
931
+ if (!hasKey(argv, fullKey.split('.')) || (checkAllAliases(fullKey, flags.arrays) && configuration['combine-arrays'])) {
932
+ setArg(fullKey, value);
933
+ }
934
+ }
935
+ });
936
+ }
937
+ // set all config objects passed in opts
938
+ function setConfigObjects() {
939
+ if (typeof configObjects !== 'undefined') {
940
+ configObjects.forEach(function (configObject) {
941
+ setConfigObject(configObject);
942
+ });
943
+ }
944
+ }
945
+ function applyEnvVars(argv, configOnly) {
946
+ if (typeof envPrefix === 'undefined')
947
+ return;
948
+ const prefix = typeof envPrefix === 'string' ? envPrefix : '';
949
+ const env = mixin$1.env();
950
+ Object.keys(env).forEach(function (envVar) {
951
+ if (prefix === '' || envVar.lastIndexOf(prefix, 0) === 0) {
952
+ // get array of nested keys and convert them to camel case
953
+ const keys = envVar.split('__').map(function (key, i) {
954
+ if (i === 0) {
955
+ key = key.substring(prefix.length);
956
+ }
957
+ return camelCase(key);
958
+ });
959
+ if (((configOnly && flags.configs[keys.join('.')]) || !configOnly) && !hasKey(argv, keys)) {
960
+ setArg(keys.join('.'), env[envVar]);
961
+ }
962
+ }
963
+ });
964
+ }
965
+ function applyCoercions(argv) {
966
+ let coerce;
967
+ const applied = new Set();
968
+ Object.keys(argv).forEach(function (key) {
969
+ if (!applied.has(key)) { // If we haven't already coerced this option via one of its aliases
970
+ coerce = checkAllAliases(key, flags.coercions);
971
+ if (typeof coerce === 'function') {
972
+ try {
973
+ const value = maybeCoerceNumber(key, coerce(argv[key]));
974
+ ([].concat(flags.aliases[key] || [], key)).forEach(ali => {
975
+ applied.add(ali);
976
+ argv[ali] = value;
977
+ });
978
+ }
979
+ catch (err) {
980
+ error = err;
981
+ }
982
+ }
983
+ }
984
+ });
985
+ }
986
+ function setPlaceholderKeys(argv) {
987
+ flags.keys.forEach((key) => {
988
+ // don't set placeholder keys for dot notation options 'foo.bar'.
989
+ if (~key.indexOf('.'))
990
+ return;
991
+ if (typeof argv[key] === 'undefined')
992
+ argv[key] = undefined;
993
+ });
994
+ return argv;
995
+ }
996
+ function applyDefaultsAndAliases(obj, aliases, defaults, canLog = false) {
997
+ Object.keys(defaults).forEach(function (key) {
998
+ if (!hasKey(obj, key.split('.'))) {
999
+ setKey(obj, key.split('.'), defaults[key]);
1000
+ if (canLog)
1001
+ defaulted[key] = true;
1002
+ (aliases[key] || []).forEach(function (x) {
1003
+ if (hasKey(obj, x.split('.')))
1004
+ return;
1005
+ setKey(obj, x.split('.'), defaults[key]);
1006
+ });
1007
+ }
1008
+ });
1009
+ }
1010
+ function hasKey(obj, keys) {
1011
+ let o = obj;
1012
+ if (!configuration['dot-notation'])
1013
+ keys = [keys.join('.')];
1014
+ keys.slice(0, -1).forEach(function (key) {
1015
+ o = (o[key] || {});
1016
+ });
1017
+ const key = keys[keys.length - 1];
1018
+ if (typeof o !== 'object')
1019
+ return false;
1020
+ else
1021
+ return key in o;
1022
+ }
1023
+ function setKey(obj, keys, value) {
1024
+ let o = obj;
1025
+ if (!configuration['dot-notation'])
1026
+ keys = [keys.join('.')];
1027
+ keys.slice(0, -1).forEach(function (key) {
1028
+ // TODO(bcoe): in the next major version of yargs, switch to
1029
+ // Object.create(null) for dot notation:
1030
+ key = sanitizeKey(key);
1031
+ if (typeof o === 'object' && o[key] === undefined) {
1032
+ o[key] = {};
1033
+ }
1034
+ if (typeof o[key] !== 'object' || Array.isArray(o[key])) {
1035
+ // ensure that o[key] is an array, and that the last item is an empty object.
1036
+ if (Array.isArray(o[key])) {
1037
+ o[key].push({});
1038
+ }
1039
+ else {
1040
+ o[key] = [o[key], {}];
1041
+ }
1042
+ // we want to update the empty object at the end of the o[key] array, so set o to that object
1043
+ o = o[key][o[key].length - 1];
1044
+ }
1045
+ else {
1046
+ o = o[key];
1047
+ }
1048
+ });
1049
+ // TODO(bcoe): in the next major version of yargs, switch to
1050
+ // Object.create(null) for dot notation:
1051
+ const key = sanitizeKey(keys[keys.length - 1]);
1052
+ const isTypeArray = checkAllAliases(keys.join('.'), flags.arrays);
1053
+ const isValueArray = Array.isArray(value);
1054
+ let duplicate = configuration['duplicate-arguments-array'];
1055
+ // nargs has higher priority than duplicate
1056
+ if (!duplicate && checkAllAliases(key, flags.nargs)) {
1057
+ duplicate = true;
1058
+ if ((!isUndefined(o[key]) && flags.nargs[key] === 1) || (Array.isArray(o[key]) && o[key].length === flags.nargs[key])) {
1059
+ o[key] = undefined;
1060
+ }
1061
+ }
1062
+ if (value === increment()) {
1063
+ o[key] = increment(o[key]);
1064
+ }
1065
+ else if (Array.isArray(o[key])) {
1066
+ if (duplicate && isTypeArray && isValueArray) {
1067
+ o[key] = configuration['flatten-duplicate-arrays'] ? o[key].concat(value) : (Array.isArray(o[key][0]) ? o[key] : [o[key]]).concat([value]);
1068
+ }
1069
+ else if (!duplicate && Boolean(isTypeArray) === Boolean(isValueArray)) {
1070
+ o[key] = value;
1071
+ }
1072
+ else {
1073
+ o[key] = o[key].concat([value]);
1074
+ }
1075
+ }
1076
+ else if (o[key] === undefined && isTypeArray) {
1077
+ o[key] = isValueArray ? value : [value];
1078
+ }
1079
+ else if (duplicate && !(o[key] === undefined ||
1080
+ checkAllAliases(key, flags.counts) ||
1081
+ checkAllAliases(key, flags.bools))) {
1082
+ o[key] = [o[key], value];
1083
+ }
1084
+ else {
1085
+ o[key] = value;
1086
+ }
1087
+ }
1088
+ // extend the aliases list with inferred aliases.
1089
+ function extendAliases(...args) {
1090
+ args.forEach(function (obj) {
1091
+ Object.keys(obj || {}).forEach(function (key) {
1092
+ // short-circuit if we've already added a key
1093
+ // to the aliases array, for example it might
1094
+ // exist in both 'opts.default' and 'opts.key'.
1095
+ if (flags.aliases[key])
1096
+ return;
1097
+ flags.aliases[key] = [].concat(aliases[key] || []);
1098
+ // For "--option-name", also set argv.optionName
1099
+ flags.aliases[key].concat(key).forEach(function (x) {
1100
+ if (/-/.test(x) && configuration['camel-case-expansion']) {
1101
+ const c = camelCase(x);
1102
+ if (c !== key && flags.aliases[key].indexOf(c) === -1) {
1103
+ flags.aliases[key].push(c);
1104
+ newAliases[c] = true;
1105
+ }
1106
+ }
1107
+ });
1108
+ // For "--optionName", also set argv['option-name']
1109
+ flags.aliases[key].concat(key).forEach(function (x) {
1110
+ if (x.length > 1 && /[A-Z]/.test(x) && configuration['camel-case-expansion']) {
1111
+ const c = decamelize(x, '-');
1112
+ if (c !== key && flags.aliases[key].indexOf(c) === -1) {
1113
+ flags.aliases[key].push(c);
1114
+ newAliases[c] = true;
1115
+ }
1116
+ }
1117
+ });
1118
+ flags.aliases[key].forEach(function (x) {
1119
+ flags.aliases[x] = [key].concat(flags.aliases[key].filter(function (y) {
1120
+ return x !== y;
1121
+ }));
1122
+ });
1123
+ });
1124
+ });
1125
+ }
1126
+ function checkAllAliases(key, flag) {
1127
+ const toCheck = [].concat(flags.aliases[key] || [], key);
1128
+ const keys = Object.keys(flag);
1129
+ const setAlias = toCheck.find(key => keys.includes(key));
1130
+ return setAlias ? flag[setAlias] : false;
1131
+ }
1132
+ function hasAnyFlag(key) {
1133
+ const flagsKeys = Object.keys(flags);
1134
+ const toCheck = [].concat(flagsKeys.map(k => flags[k]));
1135
+ return toCheck.some(function (flag) {
1136
+ return Array.isArray(flag) ? flag.includes(key) : flag[key];
1137
+ });
1138
+ }
1139
+ function hasFlagsMatching(arg, ...patterns) {
1140
+ const toCheck = [].concat(...patterns);
1141
+ return toCheck.some(function (pattern) {
1142
+ const match = arg.match(pattern);
1143
+ return match && hasAnyFlag(match[1]);
1144
+ });
1145
+ }
1146
+ // based on a simplified version of the short flag group parsing logic
1147
+ function hasAllShortFlags(arg) {
1148
+ // if this is a negative number, or doesn't start with a single hyphen, it's not a short flag group
1149
+ if (arg.match(negative) || !arg.match(/^-[^-]+/)) {
1150
+ return false;
1151
+ }
1152
+ let hasAllFlags = true;
1153
+ let next;
1154
+ const letters = arg.slice(1).split('');
1155
+ for (let j = 0; j < letters.length; j++) {
1156
+ next = arg.slice(j + 2);
1157
+ if (!hasAnyFlag(letters[j])) {
1158
+ hasAllFlags = false;
1159
+ break;
1160
+ }
1161
+ if ((letters[j + 1] && letters[j + 1] === '=') ||
1162
+ next === '-' ||
1163
+ (/[A-Za-z]/.test(letters[j]) && /^-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) ||
1164
+ (letters[j + 1] && letters[j + 1].match(/\W/))) {
1165
+ break;
1166
+ }
1167
+ }
1168
+ return hasAllFlags;
1169
+ }
1170
+ function isUnknownOptionAsArg(arg) {
1171
+ return configuration['unknown-options-as-args'] && isUnknownOption(arg);
1172
+ }
1173
+ function isUnknownOption(arg) {
1174
+ arg = arg.replace(/^-{3,}/, '--');
1175
+ // ignore negative numbers
1176
+ if (arg.match(negative)) {
1177
+ return false;
1178
+ }
1179
+ // if this is a short option group and all of them are configured, it isn't unknown
1180
+ if (hasAllShortFlags(arg)) {
1181
+ return false;
1182
+ }
1183
+ // e.g. '--count=2'
1184
+ const flagWithEquals = /^-+([^=]+?)=[\s\S]*$/;
1185
+ // e.g. '-a' or '--arg'
1186
+ const normalFlag = /^-+([^=]+?)$/;
1187
+ // e.g. '-a-'
1188
+ const flagEndingInHyphen = /^-+([^=]+?)-$/;
1189
+ // e.g. '-abc123'
1190
+ const flagEndingInDigits = /^-+([^=]+?\d+)$/;
1191
+ // e.g. '-a/usr/local'
1192
+ const flagEndingInNonWordCharacters = /^-+([^=]+?)\W+.*$/;
1193
+ // check the different types of flag styles, including negatedBoolean, a pattern defined near the start of the parse method
1194
+ return !hasFlagsMatching(arg, flagWithEquals, negatedBoolean, normalFlag, flagEndingInHyphen, flagEndingInDigits, flagEndingInNonWordCharacters);
1195
+ }
1196
+ // make a best effort to pick a default value
1197
+ // for an option based on name and type.
1198
+ function defaultValue(key) {
1199
+ if (!checkAllAliases(key, flags.bools) &&
1200
+ !checkAllAliases(key, flags.counts) &&
1201
+ `${key}` in defaults) {
1202
+ return defaults[key];
1203
+ }
1204
+ else {
1205
+ return defaultForType(guessType(key));
1206
+ }
1207
+ }
1208
+ // return a default value, given the type of a flag.,
1209
+ function defaultForType(type) {
1210
+ const def = {
1211
+ [DefaultValuesForTypeKey.BOOLEAN]: true,
1212
+ [DefaultValuesForTypeKey.STRING]: '',
1213
+ [DefaultValuesForTypeKey.NUMBER]: undefined,
1214
+ [DefaultValuesForTypeKey.ARRAY]: []
1215
+ };
1216
+ return def[type];
1217
+ }
1218
+ // given a flag, enforce a default type.
1219
+ function guessType(key) {
1220
+ let type = DefaultValuesForTypeKey.BOOLEAN;
1221
+ if (checkAllAliases(key, flags.strings))
1222
+ type = DefaultValuesForTypeKey.STRING;
1223
+ else if (checkAllAliases(key, flags.numbers))
1224
+ type = DefaultValuesForTypeKey.NUMBER;
1225
+ else if (checkAllAliases(key, flags.bools))
1226
+ type = DefaultValuesForTypeKey.BOOLEAN;
1227
+ else if (checkAllAliases(key, flags.arrays))
1228
+ type = DefaultValuesForTypeKey.ARRAY;
1229
+ return type;
1230
+ }
1231
+ function isUndefined(num) {
1232
+ return num === undefined;
1233
+ }
1234
+ // check user configuration settings for inconsistencies
1235
+ function checkConfiguration() {
1236
+ // count keys should not be set as array/narg
1237
+ Object.keys(flags.counts).find(key => {
1238
+ if (checkAllAliases(key, flags.arrays)) {
1239
+ error = Error(__('Invalid configuration: %s, opts.count excludes opts.array.', key));
1240
+ return true;
1241
+ }
1242
+ else if (checkAllAliases(key, flags.nargs)) {
1243
+ error = Error(__('Invalid configuration: %s, opts.count excludes opts.narg.', key));
1244
+ return true;
1245
+ }
1246
+ return false;
1247
+ });
1248
+ }
1249
+ return {
1250
+ aliases: Object.assign({}, flags.aliases),
1251
+ argv: Object.assign(argvReturn, argv),
1252
+ configuration: configuration,
1253
+ defaulted: Object.assign({}, defaulted),
1254
+ error: error,
1255
+ newAliases: Object.assign({}, newAliases)
1256
+ };
1257
+ }
1258
+ }
1259
+ // if any aliases reference each other, we should
1260
+ // merge them together.
1261
+ function combineAliases(aliases) {
1262
+ const aliasArrays = [];
1263
+ const combined = Object.create(null);
1264
+ let change = true;
1265
+ // turn alias lookup hash {key: ['alias1', 'alias2']} into
1266
+ // a simple array ['key', 'alias1', 'alias2']
1267
+ Object.keys(aliases).forEach(function (key) {
1268
+ aliasArrays.push([].concat(aliases[key], key));
1269
+ });
1270
+ // combine arrays until zero changes are
1271
+ // made in an iteration.
1272
+ while (change) {
1273
+ change = false;
1274
+ for (let i = 0; i < aliasArrays.length; i++) {
1275
+ for (let ii = i + 1; ii < aliasArrays.length; ii++) {
1276
+ const intersect = aliasArrays[i].filter(function (v) {
1277
+ return aliasArrays[ii].indexOf(v) !== -1;
1278
+ });
1279
+ if (intersect.length) {
1280
+ aliasArrays[i] = aliasArrays[i].concat(aliasArrays[ii]);
1281
+ aliasArrays.splice(ii, 1);
1282
+ change = true;
1283
+ break;
1284
+ }
1285
+ }
1286
+ }
1287
+ }
1288
+ // map arrays back to the hash-lookup (de-dupe while
1289
+ // we're at it).
1290
+ aliasArrays.forEach(function (aliasArray) {
1291
+ aliasArray = aliasArray.filter(function (v, i, self) {
1292
+ return self.indexOf(v) === i;
1293
+ });
1294
+ const lastAlias = aliasArray.pop();
1295
+ if (lastAlias !== undefined && typeof lastAlias === 'string') {
1296
+ combined[lastAlias] = aliasArray;
1297
+ }
1298
+ });
1299
+ return combined;
1300
+ }
1301
+ // this function should only be called when a count is given as an arg
1302
+ // it is NOT called to set a default value
1303
+ // thus we can start the count at 1 instead of 0
1304
+ function increment(orig) {
1305
+ return orig !== undefined ? orig + 1 : 1;
1306
+ }
1307
+ // TODO(bcoe): in the next major version of yargs, switch to
1308
+ // Object.create(null) for dot notation:
1309
+ function sanitizeKey(key) {
1310
+ if (key === '__proto__')
1311
+ return '___proto___';
1312
+ return key;
1313
+ }
1314
+ function stripQuotes(val) {
1315
+ return (typeof val === 'string' &&
1316
+ (val[0] === "'" || val[0] === '"') &&
1317
+ val[val.length - 1] === val[0])
1318
+ ? val.substring(1, val.length - 1)
1319
+ : val;
1320
+ }
1321
+
1322
+ /**
1323
+ * @fileoverview Main entrypoint for libraries using yargs-parser in Node.js
1324
+ * CJS and ESM environments.
1325
+ *
1326
+ * @license
1327
+ * Copyright (c) 2016, Contributors
1328
+ * SPDX-License-Identifier: ISC
1329
+ */
1330
+ // See https://github.com/yargs/yargs-parser#supported-nodejs-versions for our
1331
+ // version support policy. The YARGS_MIN_NODE_VERSION is used for testing only.
1332
+ const minNodeVersion = (process && process.env && process.env.YARGS_MIN_NODE_VERSION)
1333
+ ? Number(process.env.YARGS_MIN_NODE_VERSION)
1334
+ : 12;
1335
+ if (process && process.version) {
1336
+ const major = Number(process.version.match(/v([^.]+)/)[1]);
1337
+ if (major < minNodeVersion) {
1338
+ throw Error(`yargs parser supports a minimum Node.js version of ${minNodeVersion}. Read our version support policy: https://github.com/yargs/yargs-parser#supported-nodejs-versions`);
1339
+ }
1340
+ }
1341
+ // Creates a yargs-parser instance using Node.js standard libraries:
1342
+ const env = process ? process.env : {};
1343
+ const parser = new YargsParser({
1344
+ cwd: process.cwd,
1345
+ env: () => {
1346
+ return env;
1347
+ },
1348
+ format,
1349
+ normalize,
1350
+ resolve,
1351
+ // TODO: figure out a way to combine ESM and CJS coverage, such that
1352
+ // we can exercise all the lines below:
1353
+ require: (path) => {
1354
+ if (typeof require !== 'undefined') {
1355
+ return require(path);
1356
+ }
1357
+ else if (path.match(/\.json$/)) {
1358
+ // Addresses: https://github.com/yargs/yargs/issues/2040
1359
+ return JSON.parse(readFileSync(path, 'utf8'));
1360
+ }
1361
+ else {
1362
+ throw Error('only .json config files are supported in ESM');
1363
+ }
1364
+ }
1365
+ });
1366
+ const yargsParser = function Parser(args, opts) {
1367
+ const result = parser.parse(args.slice(), opts);
1368
+ return result.argv;
1369
+ };
1370
+ yargsParser.detailed = function (args, opts) {
1371
+ return parser.parse(args.slice(), opts);
1372
+ };
1373
+ yargsParser.camelCase = camelCase;
1374
+ yargsParser.decamelize = decamelize;
1375
+ yargsParser.looksLikeNumber = looksLikeNumber;
1376
+
1377
+ const align = {
1378
+ right: alignRight,
1379
+ center: alignCenter
1380
+ };
1381
+ const top = 0;
1382
+ const right = 1;
1383
+ const bottom = 2;
1384
+ const left = 3;
1385
+ class UI {
1386
+ constructor(opts) {
1387
+ var _a;
1388
+ this.width = opts.width;
1389
+ this.wrap = (_a = opts.wrap) !== null && _a !== void 0 ? _a : true;
1390
+ this.rows = [];
1391
+ }
1392
+ span(...args) {
1393
+ const cols = this.div(...args);
1394
+ cols.span = true;
1395
+ }
1396
+ resetOutput() {
1397
+ this.rows = [];
1398
+ }
1399
+ div(...args) {
1400
+ if (args.length === 0) {
1401
+ this.div('');
1402
+ }
1403
+ if (this.wrap && this.shouldApplyLayoutDSL(...args) && typeof args[0] === 'string') {
1404
+ return this.applyLayoutDSL(args[0]);
1405
+ }
1406
+ const cols = args.map(arg => {
1407
+ if (typeof arg === 'string') {
1408
+ return this.colFromString(arg);
1409
+ }
1410
+ return arg;
1411
+ });
1412
+ this.rows.push(cols);
1413
+ return cols;
1414
+ }
1415
+ shouldApplyLayoutDSL(...args) {
1416
+ return args.length === 1 && typeof args[0] === 'string' &&
1417
+ /[\t\n]/.test(args[0]);
1418
+ }
1419
+ applyLayoutDSL(str) {
1420
+ const rows = str.split('\n').map(row => row.split('\t'));
1421
+ let leftColumnWidth = 0;
1422
+ // simple heuristic for layout, make sure the
1423
+ // second column lines up along the left-hand.
1424
+ // don't allow the first column to take up more
1425
+ // than 50% of the screen.
1426
+ rows.forEach(columns => {
1427
+ if (columns.length > 1 && mixin.stringWidth(columns[0]) > leftColumnWidth) {
1428
+ leftColumnWidth = Math.min(Math.floor(this.width * 0.5), mixin.stringWidth(columns[0]));
1429
+ }
1430
+ });
1431
+ // generate a table:
1432
+ // replacing ' ' with padding calculations.
1433
+ // using the algorithmically generated width.
1434
+ rows.forEach(columns => {
1435
+ this.div(...columns.map((r, i) => {
1436
+ return {
1437
+ text: r.trim(),
1438
+ padding: this.measurePadding(r),
1439
+ width: (i === 0 && columns.length > 1) ? leftColumnWidth : undefined
1440
+ };
1441
+ }));
1442
+ });
1443
+ return this.rows[this.rows.length - 1];
1444
+ }
1445
+ colFromString(text) {
1446
+ return {
1447
+ text,
1448
+ padding: this.measurePadding(text)
1449
+ };
1450
+ }
1451
+ measurePadding(str) {
1452
+ // measure padding without ansi escape codes
1453
+ const noAnsi = mixin.stripAnsi(str);
1454
+ return [0, noAnsi.match(/\s*$/)[0].length, 0, noAnsi.match(/^\s*/)[0].length];
1455
+ }
1456
+ toString() {
1457
+ const lines = [];
1458
+ this.rows.forEach(row => {
1459
+ this.rowToString(row, lines);
1460
+ });
1461
+ // don't display any lines with the
1462
+ // hidden flag set.
1463
+ return lines
1464
+ .filter(line => !line.hidden)
1465
+ .map(line => line.text)
1466
+ .join('\n');
1467
+ }
1468
+ rowToString(row, lines) {
1469
+ this.rasterize(row).forEach((rrow, r) => {
1470
+ let str = '';
1471
+ rrow.forEach((col, c) => {
1472
+ const { width } = row[c]; // the width with padding.
1473
+ const wrapWidth = this.negatePadding(row[c]); // the width without padding.
1474
+ let ts = col; // temporary string used during alignment/padding.
1475
+ if (wrapWidth > mixin.stringWidth(col)) {
1476
+ ts += ' '.repeat(wrapWidth - mixin.stringWidth(col));
1477
+ }
1478
+ // align the string within its column.
1479
+ if (row[c].align && row[c].align !== 'left' && this.wrap) {
1480
+ const fn = align[row[c].align];
1481
+ ts = fn(ts, wrapWidth);
1482
+ if (mixin.stringWidth(ts) < wrapWidth) {
1483
+ ts += ' '.repeat((width || 0) - mixin.stringWidth(ts) - 1);
1484
+ }
1485
+ }
1486
+ // apply border and padding to string.
1487
+ const padding = row[c].padding || [0, 0, 0, 0];
1488
+ if (padding[left]) {
1489
+ str += ' '.repeat(padding[left]);
1490
+ }
1491
+ str += addBorder(row[c], ts, '| ');
1492
+ str += ts;
1493
+ str += addBorder(row[c], ts, ' |');
1494
+ if (padding[right]) {
1495
+ str += ' '.repeat(padding[right]);
1496
+ }
1497
+ // if prior row is span, try to render the
1498
+ // current row on the prior line.
1499
+ if (r === 0 && lines.length > 0) {
1500
+ str = this.renderInline(str, lines[lines.length - 1]);
1501
+ }
1502
+ });
1503
+ // remove trailing whitespace.
1504
+ lines.push({
1505
+ text: str.replace(/ +$/, ''),
1506
+ span: row.span
1507
+ });
1508
+ });
1509
+ return lines;
1510
+ }
1511
+ // if the full 'source' can render in
1512
+ // the target line, do so.
1513
+ renderInline(source, previousLine) {
1514
+ const match = source.match(/^ */);
1515
+ const leadingWhitespace = match ? match[0].length : 0;
1516
+ const target = previousLine.text;
1517
+ const targetTextWidth = mixin.stringWidth(target.trimRight());
1518
+ if (!previousLine.span) {
1519
+ return source;
1520
+ }
1521
+ // if we're not applying wrapping logic,
1522
+ // just always append to the span.
1523
+ if (!this.wrap) {
1524
+ previousLine.hidden = true;
1525
+ return target + source;
1526
+ }
1527
+ if (leadingWhitespace < targetTextWidth) {
1528
+ return source;
1529
+ }
1530
+ previousLine.hidden = true;
1531
+ return target.trimRight() + ' '.repeat(leadingWhitespace - targetTextWidth) + source.trimLeft();
1532
+ }
1533
+ rasterize(row) {
1534
+ const rrows = [];
1535
+ const widths = this.columnWidths(row);
1536
+ let wrapped;
1537
+ // word wrap all columns, and create
1538
+ // a data-structure that is easy to rasterize.
1539
+ row.forEach((col, c) => {
1540
+ // leave room for left and right padding.
1541
+ col.width = widths[c];
1542
+ if (this.wrap) {
1543
+ wrapped = mixin.wrap(col.text, this.negatePadding(col), { hard: true }).split('\n');
1544
+ }
1545
+ else {
1546
+ wrapped = col.text.split('\n');
1547
+ }
1548
+ if (col.border) {
1549
+ wrapped.unshift('.' + '-'.repeat(this.negatePadding(col) + 2) + '.');
1550
+ wrapped.push("'" + '-'.repeat(this.negatePadding(col) + 2) + "'");
1551
+ }
1552
+ // add top and bottom padding.
1553
+ if (col.padding) {
1554
+ wrapped.unshift(...new Array(col.padding[top] || 0).fill(''));
1555
+ wrapped.push(...new Array(col.padding[bottom] || 0).fill(''));
1556
+ }
1557
+ wrapped.forEach((str, r) => {
1558
+ if (!rrows[r]) {
1559
+ rrows.push([]);
1560
+ }
1561
+ const rrow = rrows[r];
1562
+ for (let i = 0; i < c; i++) {
1563
+ if (rrow[i] === undefined) {
1564
+ rrow.push('');
1565
+ }
1566
+ }
1567
+ rrow.push(str);
1568
+ });
1569
+ });
1570
+ return rrows;
1571
+ }
1572
+ negatePadding(col) {
1573
+ let wrapWidth = col.width || 0;
1574
+ if (col.padding) {
1575
+ wrapWidth -= (col.padding[left] || 0) + (col.padding[right] || 0);
1576
+ }
1577
+ if (col.border) {
1578
+ wrapWidth -= 4;
1579
+ }
1580
+ return wrapWidth;
1581
+ }
1582
+ columnWidths(row) {
1583
+ if (!this.wrap) {
1584
+ return row.map(col => {
1585
+ return col.width || mixin.stringWidth(col.text);
1586
+ });
1587
+ }
1588
+ let unset = row.length;
1589
+ let remainingWidth = this.width;
1590
+ // column widths can be set in config.
1591
+ const widths = row.map(col => {
1592
+ if (col.width) {
1593
+ unset--;
1594
+ remainingWidth -= col.width;
1595
+ return col.width;
1596
+ }
1597
+ return undefined;
1598
+ });
1599
+ // any unset widths should be calculated.
1600
+ const unsetWidth = unset ? Math.floor(remainingWidth / unset) : 0;
1601
+ return widths.map((w, i) => {
1602
+ if (w === undefined) {
1603
+ return Math.max(unsetWidth, _minWidth(row[i]));
1604
+ }
1605
+ return w;
1606
+ });
1607
+ }
1608
+ }
1609
+ function addBorder(col, ts, style) {
1610
+ if (col.border) {
1611
+ if (/[.']-+[.']/.test(ts)) {
1612
+ return '';
1613
+ }
1614
+ if (ts.trim().length !== 0) {
1615
+ return style;
1616
+ }
1617
+ return ' ';
1618
+ }
1619
+ return '';
1620
+ }
1621
+ // calculates the minimum width of
1622
+ // a column, based on padding preferences.
1623
+ function _minWidth(col) {
1624
+ const padding = col.padding || [];
1625
+ const minWidth = 1 + (padding[left] || 0) + (padding[right] || 0);
1626
+ if (col.border) {
1627
+ return minWidth + 4;
1628
+ }
1629
+ return minWidth;
1630
+ }
1631
+ function getWindowWidth() {
1632
+ /* istanbul ignore next: depends on terminal */
1633
+ if (typeof process === 'object' && process.stdout && process.stdout.columns) {
1634
+ return process.stdout.columns;
1635
+ }
1636
+ return 80;
1637
+ }
1638
+ function alignRight(str, width) {
1639
+ str = str.trim();
1640
+ const strWidth = mixin.stringWidth(str);
1641
+ if (strWidth < width) {
1642
+ return ' '.repeat(width - strWidth) + str;
1643
+ }
1644
+ return str;
1645
+ }
1646
+ function alignCenter(str, width) {
1647
+ str = str.trim();
1648
+ const strWidth = mixin.stringWidth(str);
1649
+ /* istanbul ignore next */
1650
+ if (strWidth >= width) {
1651
+ return str;
1652
+ }
1653
+ return ' '.repeat((width - strWidth) >> 1) + str;
1654
+ }
1655
+ let mixin;
1656
+ function cliui(opts, _mixin) {
1657
+ mixin = _mixin;
1658
+ return new UI({
1659
+ width: (opts === null || opts === void 0 ? void 0 : opts.width) || getWindowWidth(),
1660
+ wrap: opts === null || opts === void 0 ? void 0 : opts.wrap
1661
+ });
1662
+ }
1663
+
1664
+ // Minimal replacement for ansi string helpers "wrap-ansi" and "strip-ansi".
1665
+ // to facilitate ESM and Deno modules.
1666
+ // TODO: look at porting https://www.npmjs.com/package/wrap-ansi to ESM.
1667
+ // The npm application
1668
+ // Copyright (c) npm, Inc. and Contributors
1669
+ // Licensed on the terms of The Artistic License 2.0
1670
+ // See: https://github.com/npm/cli/blob/4c65cd952bc8627811735bea76b9b110cc4fc80e/lib/utils/ansi-trim.js
1671
+ const ansi = new RegExp('\x1b(?:\\[(?:\\d+[ABCDEFGJKSTm]|\\d+;\\d+[Hfm]|' +
1672
+ '\\d+;\\d+;\\d+m|6n|s|u|\\?25[lh])|\\w)', 'g');
1673
+ function stripAnsi(str) {
1674
+ return str.replace(ansi, '');
1675
+ }
1676
+ function wrap(str, width) {
1677
+ const [start, end] = str.match(ansi) || ['', ''];
1678
+ str = stripAnsi(str);
1679
+ let wrapped = '';
1680
+ for (let i = 0; i < str.length; i++) {
1681
+ if (i !== 0 && (i % width) === 0) {
1682
+ wrapped += '\n';
1683
+ }
1684
+ wrapped += str.charAt(i);
1685
+ }
1686
+ if (start && end) {
1687
+ wrapped = `${start}${wrapped}${end}`;
1688
+ }
1689
+ return wrapped;
1690
+ }
1691
+
1692
+ // Bootstrap cliui with CommonJS dependencies:
1693
+
1694
+ function ui (opts) {
1695
+ return cliui(opts, {
1696
+ stringWidth: (str) => {
1697
+ return [...str].length
1698
+ },
1699
+ stripAnsi,
1700
+ wrap
1701
+ })
1702
+ }
1703
+
1704
+ function escalade (start, callback) {
1705
+ let dir = resolve('.', start);
1706
+ let tmp, stats = statSync(dir);
1707
+
1708
+ if (!stats.isDirectory()) {
1709
+ dir = dirname(dir);
1710
+ }
1711
+
1712
+ while (true) {
1713
+ tmp = callback(dir, readdirSync(dir));
1714
+ if (tmp) return resolve(dir, tmp);
1715
+ dir = dirname(tmp = dir);
1716
+ if (tmp === dir) break;
1717
+ }
1718
+ }
1719
+
1720
+ var shim$1 = {
1721
+ fs: {
1722
+ readFileSync,
1723
+ writeFile
1724
+ },
1725
+ format,
1726
+ resolve,
1727
+ exists: (file) => {
1728
+ try {
1729
+ return statSync(file).isFile();
1730
+ }
1731
+ catch (err) {
1732
+ return false;
1733
+ }
1734
+ }
1735
+ };
1736
+
1737
+ let shim;
1738
+ class Y18N {
1739
+ constructor(opts) {
1740
+ // configurable options.
1741
+ opts = opts || {};
1742
+ this.directory = opts.directory || './locales';
1743
+ this.updateFiles = typeof opts.updateFiles === 'boolean' ? opts.updateFiles : true;
1744
+ this.locale = opts.locale || 'en';
1745
+ this.fallbackToLanguage = typeof opts.fallbackToLanguage === 'boolean' ? opts.fallbackToLanguage : true;
1746
+ // internal stuff.
1747
+ this.cache = Object.create(null);
1748
+ this.writeQueue = [];
1749
+ }
1750
+ __(...args) {
1751
+ if (typeof arguments[0] !== 'string') {
1752
+ return this._taggedLiteral(arguments[0], ...arguments);
1753
+ }
1754
+ const str = args.shift();
1755
+ let cb = function () { }; // start with noop.
1756
+ if (typeof args[args.length - 1] === 'function')
1757
+ cb = args.pop();
1758
+ cb = cb || function () { }; // noop.
1759
+ if (!this.cache[this.locale])
1760
+ this._readLocaleFile();
1761
+ // we've observed a new string, update the language file.
1762
+ if (!this.cache[this.locale][str] && this.updateFiles) {
1763
+ this.cache[this.locale][str] = str;
1764
+ // include the current directory and locale,
1765
+ // since these values could change before the
1766
+ // write is performed.
1767
+ this._enqueueWrite({
1768
+ directory: this.directory,
1769
+ locale: this.locale,
1770
+ cb
1771
+ });
1772
+ }
1773
+ else {
1774
+ cb();
1775
+ }
1776
+ return shim.format.apply(shim.format, [this.cache[this.locale][str] || str].concat(args));
1777
+ }
1778
+ __n() {
1779
+ const args = Array.prototype.slice.call(arguments);
1780
+ const singular = args.shift();
1781
+ const plural = args.shift();
1782
+ const quantity = args.shift();
1783
+ let cb = function () { }; // start with noop.
1784
+ if (typeof args[args.length - 1] === 'function')
1785
+ cb = args.pop();
1786
+ if (!this.cache[this.locale])
1787
+ this._readLocaleFile();
1788
+ let str = quantity === 1 ? singular : plural;
1789
+ if (this.cache[this.locale][singular]) {
1790
+ const entry = this.cache[this.locale][singular];
1791
+ str = entry[quantity === 1 ? 'one' : 'other'];
1792
+ }
1793
+ // we've observed a new string, update the language file.
1794
+ if (!this.cache[this.locale][singular] && this.updateFiles) {
1795
+ this.cache[this.locale][singular] = {
1796
+ one: singular,
1797
+ other: plural
1798
+ };
1799
+ // include the current directory and locale,
1800
+ // since these values could change before the
1801
+ // write is performed.
1802
+ this._enqueueWrite({
1803
+ directory: this.directory,
1804
+ locale: this.locale,
1805
+ cb
1806
+ });
1807
+ }
1808
+ else {
1809
+ cb();
1810
+ }
1811
+ // if a %d placeholder is provided, add quantity
1812
+ // to the arguments expanded by util.format.
1813
+ const values = [str];
1814
+ if (~str.indexOf('%d'))
1815
+ values.push(quantity);
1816
+ return shim.format.apply(shim.format, values.concat(args));
1817
+ }
1818
+ setLocale(locale) {
1819
+ this.locale = locale;
1820
+ }
1821
+ getLocale() {
1822
+ return this.locale;
1823
+ }
1824
+ updateLocale(obj) {
1825
+ if (!this.cache[this.locale])
1826
+ this._readLocaleFile();
1827
+ for (const key in obj) {
1828
+ if (Object.prototype.hasOwnProperty.call(obj, key)) {
1829
+ this.cache[this.locale][key] = obj[key];
1830
+ }
1831
+ }
1832
+ }
1833
+ _taggedLiteral(parts, ...args) {
1834
+ let str = '';
1835
+ parts.forEach(function (part, i) {
1836
+ const arg = args[i + 1];
1837
+ str += part;
1838
+ if (typeof arg !== 'undefined') {
1839
+ str += '%s';
1840
+ }
1841
+ });
1842
+ return this.__.apply(this, [str].concat([].slice.call(args, 1)));
1843
+ }
1844
+ _enqueueWrite(work) {
1845
+ this.writeQueue.push(work);
1846
+ if (this.writeQueue.length === 1)
1847
+ this._processWriteQueue();
1848
+ }
1849
+ _processWriteQueue() {
1850
+ const _this = this;
1851
+ const work = this.writeQueue[0];
1852
+ // destructure the enqueued work.
1853
+ const directory = work.directory;
1854
+ const locale = work.locale;
1855
+ const cb = work.cb;
1856
+ const languageFile = this._resolveLocaleFile(directory, locale);
1857
+ const serializedLocale = JSON.stringify(this.cache[locale], null, 2);
1858
+ shim.fs.writeFile(languageFile, serializedLocale, 'utf-8', function (err) {
1859
+ _this.writeQueue.shift();
1860
+ if (_this.writeQueue.length > 0)
1861
+ _this._processWriteQueue();
1862
+ cb(err);
1863
+ });
1864
+ }
1865
+ _readLocaleFile() {
1866
+ let localeLookup = {};
1867
+ const languageFile = this._resolveLocaleFile(this.directory, this.locale);
1868
+ try {
1869
+ // When using a bundler such as webpack, readFileSync may not be defined:
1870
+ if (shim.fs.readFileSync) {
1871
+ localeLookup = JSON.parse(shim.fs.readFileSync(languageFile, 'utf-8'));
1872
+ }
1873
+ }
1874
+ catch (err) {
1875
+ if (err instanceof SyntaxError) {
1876
+ err.message = 'syntax error in ' + languageFile;
1877
+ }
1878
+ if (err.code === 'ENOENT')
1879
+ localeLookup = {};
1880
+ else
1881
+ throw err;
1882
+ }
1883
+ this.cache[this.locale] = localeLookup;
1884
+ }
1885
+ _resolveLocaleFile(directory, locale) {
1886
+ let file = shim.resolve(directory, './', locale + '.json');
1887
+ if (this.fallbackToLanguage && !this._fileExistsSync(file) && ~locale.lastIndexOf('_')) {
1888
+ // attempt fallback to language only
1889
+ const languageFile = shim.resolve(directory, './', locale.split('_')[0] + '.json');
1890
+ if (this._fileExistsSync(languageFile))
1891
+ file = languageFile;
1892
+ }
1893
+ return file;
1894
+ }
1895
+ _fileExistsSync(file) {
1896
+ return shim.exists(file);
1897
+ }
1898
+ }
1899
+ function y18n$1(opts, _shim) {
1900
+ shim = _shim;
1901
+ const y18n = new Y18N(opts);
1902
+ return {
1903
+ __: y18n.__.bind(y18n),
1904
+ __n: y18n.__n.bind(y18n),
1905
+ setLocale: y18n.setLocale.bind(y18n),
1906
+ getLocale: y18n.getLocale.bind(y18n),
1907
+ updateLocale: y18n.updateLocale.bind(y18n),
1908
+ locale: y18n.locale
1909
+ };
1910
+ }
1911
+
1912
+ const y18n = (opts) => {
1913
+ return y18n$1(opts, shim$1)
1914
+ };
1915
+
1916
+ const REQUIRE_ERROR = 'require is not supported by ESM';
1917
+ const REQUIRE_DIRECTORY_ERROR = 'loading a directory of commands is not supported yet for ESM';
1918
+
1919
+ let __dirname;
1920
+ try {
1921
+ __dirname = fileURLToPath(import.meta.url);
1922
+ } catch (e) {
1923
+ __dirname = process.cwd();
1924
+ }
1925
+ const mainFilename = __dirname.substring(0, __dirname.lastIndexOf('node_modules'));
1926
+
1927
+ ({
1928
+ assert: {
1929
+ notStrictEqual,
1930
+ strictEqual
1931
+ },
1932
+ cliui: ui,
1933
+ findUp: escalade,
1934
+ getEnv: (key) => {
1935
+ return process.env[key]
1936
+ },
1937
+ inspect,
1938
+ getCallerFile: () => {
1939
+ throw new YError(REQUIRE_DIRECTORY_ERROR)
1940
+ },
1941
+ getProcessArgvBin,
1942
+ mainFilename: mainFilename || process.cwd(),
1943
+ Parser: yargsParser,
1944
+ path: {
1945
+ basename,
1946
+ dirname,
1947
+ extname,
1948
+ relative,
1949
+ resolve
1950
+ },
1951
+ process: {
1952
+ argv: () => process.argv,
1953
+ cwd: process.cwd,
1954
+ emitWarning: (warning, type) => process.emitWarning(warning, type),
1955
+ execPath: () => process.execPath,
1956
+ exit: process.exit,
1957
+ nextTick: process.nextTick,
1958
+ stdColumns: typeof process.stdout.columns !== 'undefined' ? process.stdout.columns : null
1959
+ },
1960
+ readFileSync,
1961
+ require: () => {
1962
+ throw new YError(REQUIRE_ERROR)
1963
+ },
1964
+ requireDirectory: () => {
1965
+ throw new YError(REQUIRE_DIRECTORY_ERROR)
1966
+ },
1967
+ stringWidth: (str) => {
1968
+ return [...str].length
1969
+ },
1970
+ y18n: y18n({
1971
+ directory: resolve(__dirname, '../../../locales'),
1972
+ updateFiles: false
1973
+ })
1974
+ });
1975
+
1976
+ function javascriptScaffolderFactory(decisions) {
1977
+ const scope = '@pragmatic-divops';
1978
+
1979
+ return options => scaffold({
1980
+ ...options,
1981
+ configs: {
1982
+ eslint: {scope},
1983
+ remark: `${scope}/remark-preset`,
1984
+ babelPreset: {name: '@form8ion', packageName: '@form8ion/babel-preset'},
1985
+ commitlint: {name: scope, packageName: `${scope}/commitlint-config`}
1986
+ },
1987
+ overrides: {npmAccount: 'form8ion'},
1988
+ ciServices: {'GitHub Actions': {scaffolder: scaffold$1, public: true}},
1989
+ hosts: {Netlify: {projectTypes: ['static'], scaffolder: scaffold$2}},
1990
+ applicationTypes: {Gatsby: {scaffolder: scaffold$3}},
1991
+ packageTypes: {'ESLint Config': {scaffolder: scaffold$4}},
1992
+ unitTestFrameworks: {mocha: {scaffolder: scaffold$5}},
1993
+ decisions
1994
+ });
1995
+ }
1996
+
1997
+ function githubPromptFactory(decisions) {
1998
+ return () => prompt({account: 'pragmatic-divops', decisions});
1999
+ }
2000
+
2001
+ const traviName = 'Matt Travi';
2002
+ const orgName = 'pragmatic-divops';
2003
+
2004
+ function defineDecisions(providedDecisions) {
2005
+ return {
2006
+ ...providedDecisions,
2007
+ [questionNames.COPYRIGHT_HOLDER]: traviName,
2008
+ [questionNames.REPO_HOST]: 'GitHub',
2009
+ [questionNames.REPO_OWNER]: orgName,
2010
+ [questionNames.DEPENDENCY_UPDATER]: 'Renovate',
2011
+ [questionNames$1.AUTHOR_NAME]: traviName,
2012
+ [questionNames$1.AUTHOR_EMAIL]: 'npm@travi.org',
2013
+ [questionNames$1.AUTHOR_URL]: 'https://matt.travi.org',
2014
+ [questionNames$1.UNIT_TEST_FRAMEWORK]: 'mocha',
2015
+ [questionNames$1.SCOPE]: orgName,
2016
+ [questionNames$1.CI_SERVICE]: 'GitHub Actions',
2017
+ [questionNames$1.PACKAGE_MANAGER]: packageManagers.NPM
2018
+ };
2019
+ }
2020
+
2021
+ function defineScaffoldOptions(decisions) {
2022
+ return {
2023
+ languages: {JavaScript: javascriptScaffolderFactory(decisions)},
2024
+ vcsHosts: {GitHub: {scaffolder: scaffold$6, prompt: githubPromptFactory(decisions), public: true}},
2025
+ overrides: {copyrightHolder: traviName},
2026
+ dependencyUpdaters: {Renovate: {scaffolder: scaffold$7}},
2027
+ decisions
2028
+ };
2029
+ }
2030
+
2031
+ function handler$2(providedDecisions) {
2032
+ return scaffold$8(defineScaffoldOptions(defineDecisions(providedDecisions)));
2033
+ }
2034
+
2035
+ const command$2 = 'scaffold';
2036
+ const describe$2 = 'Scaffold a new project';
2037
+
2038
+ var scaffoldCommand = /*#__PURE__*/Object.freeze({
2039
+ __proto__: null,
2040
+ handler: handler$2,
2041
+ command: command$2,
2042
+ describe: describe$2
2043
+ });
2044
+
2045
+ const packageScope = '@pragmatic-divops';
2046
+
2047
+ const javascriptConfigs = {
2048
+ eslint: {scope: packageScope},
2049
+ remark: `${packageScope}/remark-lint-preset`,
2050
+ babelPreset: {
2051
+ name: packageScope,
2052
+ packageName: `${packageScope}/babel-preset`
2053
+ },
2054
+ commitlint: {
2055
+ name: packageScope,
2056
+ packageName: `${packageScope}/commitlint-config`
2057
+ }
2058
+ };
2059
+
2060
+ function javascript(options) {
2061
+ return lift({...options, configs: javascriptConfigs});
2062
+ }
2063
+
2064
+ function getEnhancedCodecovScaffolder() {
2065
+ return options => scaffold$9({...options, visibility: 'Public'});
2066
+ }
2067
+
2068
+ function handler$1({decisions}) {
2069
+ return lift$1({
2070
+ decisions,
2071
+ scaffolders: {
2072
+ Renovate: scaffold$7,
2073
+ Cucumber: scaffold$a,
2074
+ Codecov: getEnhancedCodecovScaffolder()
2075
+ },
2076
+ enhancers: {
2077
+ JavaScript: {test: test, lift: javascript},
2078
+ Renovate: {test: predicate, lift: lift$2},
2079
+ 'GitHub Actions CI': {test: test$1, lift: lift$3}
2080
+ }
2081
+ });
2082
+ }
2083
+
2084
+ const command$1 = 'lift';
2085
+ const describe$1 = 'Lift an existing project with additional functionality';
2086
+
2087
+ var liftCommand = /*#__PURE__*/Object.freeze({
2088
+ __proto__: null,
2089
+ handler: handler$1,
2090
+ command: command$1,
2091
+ describe: describe$1
2092
+ });
2093
+
2094
+ function handler(providedDecisions) {
2095
+ // return extendEslintConfig(defineScaffoldOptions(defineDecisions(providedDecisions)), javascriptScaffolderFactory);
2096
+
2097
+ return extendEslintConfig(defineScaffoldOptions(defineDecisions(providedDecisions)), javascriptScaffolderFactory);
2098
+ }
2099
+
2100
+ const command = 'extend-eslint-config';
2101
+ const describe = 'Extend a @form8ion shareable ESLint config';
2102
+
2103
+ var extendEslintConfigCommand = /*#__PURE__*/Object.freeze({
2104
+ __proto__: null,
2105
+ handler: handler,
2106
+ command: command,
2107
+ describe: describe
2108
+ });
2109
+
2110
+ function cli (yargs) {
2111
+ return yargs(hideBin(process.argv))
2112
+ .scriptName('pragmatic-divops')
2113
+ .usage('Usage: $0 <cmd> [args]')
2114
+ .command(scaffoldCommand)
2115
+ .command(liftCommand)
2116
+ .command(extendEslintConfigCommand)
2117
+ .demandCommand(1, 'You need at least one command before moving on')
2118
+ .help('h')
2119
+ .alias('h', 'help')
2120
+ .argv;
2121
+ }
2122
+
2123
+ cli(yargs);
2124
+
2125
+ updateNotifier({pkg}).notify();
2126
+ //# sourceMappingURL=pragmatic-divops.mjs.map