index.cjs 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048
  1. 'use strict';
  2. var util = require('util');
  3. var path = require('path');
  4. var fs = require('fs');
  5. function camelCase(str) {
  6. const isCamelCase = str !== str.toLowerCase() && str !== str.toUpperCase();
  7. if (!isCamelCase) {
  8. str = str.toLowerCase();
  9. }
  10. if (str.indexOf('-') === -1 && str.indexOf('_') === -1) {
  11. return str;
  12. }
  13. else {
  14. let camelcase = '';
  15. let nextChrUpper = false;
  16. const leadingHyphens = str.match(/^-+/);
  17. for (let i = leadingHyphens ? leadingHyphens[0].length : 0; i < str.length; i++) {
  18. let chr = str.charAt(i);
  19. if (nextChrUpper) {
  20. nextChrUpper = false;
  21. chr = chr.toUpperCase();
  22. }
  23. if (i !== 0 && (chr === '-' || chr === '_')) {
  24. nextChrUpper = true;
  25. }
  26. else if (chr !== '-' && chr !== '_') {
  27. camelcase += chr;
  28. }
  29. }
  30. return camelcase;
  31. }
  32. }
  33. function decamelize(str, joinString) {
  34. const lowercase = str.toLowerCase();
  35. joinString = joinString || '-';
  36. let notCamelcase = '';
  37. for (let i = 0; i < str.length; i++) {
  38. const chrLower = lowercase.charAt(i);
  39. const chrString = str.charAt(i);
  40. if (chrLower !== chrString && i > 0) {
  41. notCamelcase += `${joinString}${lowercase.charAt(i)}`;
  42. }
  43. else {
  44. notCamelcase += chrString;
  45. }
  46. }
  47. return notCamelcase;
  48. }
  49. function looksLikeNumber(x) {
  50. if (x === null || x === undefined)
  51. return false;
  52. if (typeof x === 'number')
  53. return true;
  54. if (/^0x[0-9a-f]+$/i.test(x))
  55. return true;
  56. if (/^0[^.]/.test(x))
  57. return false;
  58. return /^[-]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x);
  59. }
  60. function tokenizeArgString(argString) {
  61. if (Array.isArray(argString)) {
  62. return argString.map(e => typeof e !== 'string' ? e + '' : e);
  63. }
  64. argString = argString.trim();
  65. let i = 0;
  66. let prevC = null;
  67. let c = null;
  68. let opening = null;
  69. const args = [];
  70. for (let ii = 0; ii < argString.length; ii++) {
  71. prevC = c;
  72. c = argString.charAt(ii);
  73. if (c === ' ' && !opening) {
  74. if (!(prevC === ' ')) {
  75. i++;
  76. }
  77. continue;
  78. }
  79. if (c === opening) {
  80. opening = null;
  81. }
  82. else if ((c === "'" || c === '"') && !opening) {
  83. opening = c;
  84. }
  85. if (!args[i])
  86. args[i] = '';
  87. args[i] += c;
  88. }
  89. return args;
  90. }
  91. var DefaultValuesForTypeKey;
  92. (function (DefaultValuesForTypeKey) {
  93. DefaultValuesForTypeKey["BOOLEAN"] = "boolean";
  94. DefaultValuesForTypeKey["STRING"] = "string";
  95. DefaultValuesForTypeKey["NUMBER"] = "number";
  96. DefaultValuesForTypeKey["ARRAY"] = "array";
  97. })(DefaultValuesForTypeKey || (DefaultValuesForTypeKey = {}));
  98. let mixin;
  99. class YargsParser {
  100. constructor(_mixin) {
  101. mixin = _mixin;
  102. }
  103. parse(argsInput, options) {
  104. const opts = Object.assign({
  105. alias: undefined,
  106. array: undefined,
  107. boolean: undefined,
  108. config: undefined,
  109. configObjects: undefined,
  110. configuration: undefined,
  111. coerce: undefined,
  112. count: undefined,
  113. default: undefined,
  114. envPrefix: undefined,
  115. narg: undefined,
  116. normalize: undefined,
  117. string: undefined,
  118. number: undefined,
  119. __: undefined,
  120. key: undefined
  121. }, options);
  122. const args = tokenizeArgString(argsInput);
  123. const inputIsString = typeof argsInput === 'string';
  124. const aliases = combineAliases(Object.assign(Object.create(null), opts.alias));
  125. const configuration = Object.assign({
  126. 'boolean-negation': true,
  127. 'camel-case-expansion': true,
  128. 'combine-arrays': false,
  129. 'dot-notation': true,
  130. 'duplicate-arguments-array': true,
  131. 'flatten-duplicate-arrays': true,
  132. 'greedy-arrays': true,
  133. 'halt-at-non-option': false,
  134. 'nargs-eats-options': false,
  135. 'negation-prefix': 'no-',
  136. 'parse-numbers': true,
  137. 'parse-positional-numbers': true,
  138. 'populate--': false,
  139. 'set-placeholder-key': false,
  140. 'short-option-groups': true,
  141. 'strip-aliased': false,
  142. 'strip-dashed': false,
  143. 'unknown-options-as-args': false
  144. }, opts.configuration);
  145. const defaults = Object.assign(Object.create(null), opts.default);
  146. const configObjects = opts.configObjects || [];
  147. const envPrefix = opts.envPrefix;
  148. const notFlagsOption = configuration['populate--'];
  149. const notFlagsArgv = notFlagsOption ? '--' : '_';
  150. const newAliases = Object.create(null);
  151. const defaulted = Object.create(null);
  152. const __ = opts.__ || mixin.format;
  153. const flags = {
  154. aliases: Object.create(null),
  155. arrays: Object.create(null),
  156. bools: Object.create(null),
  157. strings: Object.create(null),
  158. numbers: Object.create(null),
  159. counts: Object.create(null),
  160. normalize: Object.create(null),
  161. configs: Object.create(null),
  162. nargs: Object.create(null),
  163. coercions: Object.create(null),
  164. keys: []
  165. };
  166. const negative = /^-([0-9]+(\.[0-9]+)?|\.[0-9]+)$/;
  167. const negatedBoolean = new RegExp('^--' + configuration['negation-prefix'] + '(.+)');
  168. [].concat(opts.array || []).filter(Boolean).forEach(function (opt) {
  169. const key = typeof opt === 'object' ? opt.key : opt;
  170. const assignment = Object.keys(opt).map(function (key) {
  171. const arrayFlagKeys = {
  172. boolean: 'bools',
  173. string: 'strings',
  174. number: 'numbers'
  175. };
  176. return arrayFlagKeys[key];
  177. }).filter(Boolean).pop();
  178. if (assignment) {
  179. flags[assignment][key] = true;
  180. }
  181. flags.arrays[key] = true;
  182. flags.keys.push(key);
  183. });
  184. [].concat(opts.boolean || []).filter(Boolean).forEach(function (key) {
  185. flags.bools[key] = true;
  186. flags.keys.push(key);
  187. });
  188. [].concat(opts.string || []).filter(Boolean).forEach(function (key) {
  189. flags.strings[key] = true;
  190. flags.keys.push(key);
  191. });
  192. [].concat(opts.number || []).filter(Boolean).forEach(function (key) {
  193. flags.numbers[key] = true;
  194. flags.keys.push(key);
  195. });
  196. [].concat(opts.count || []).filter(Boolean).forEach(function (key) {
  197. flags.counts[key] = true;
  198. flags.keys.push(key);
  199. });
  200. [].concat(opts.normalize || []).filter(Boolean).forEach(function (key) {
  201. flags.normalize[key] = true;
  202. flags.keys.push(key);
  203. });
  204. if (typeof opts.narg === 'object') {
  205. Object.entries(opts.narg).forEach(([key, value]) => {
  206. if (typeof value === 'number') {
  207. flags.nargs[key] = value;
  208. flags.keys.push(key);
  209. }
  210. });
  211. }
  212. if (typeof opts.coerce === 'object') {
  213. Object.entries(opts.coerce).forEach(([key, value]) => {
  214. if (typeof value === 'function') {
  215. flags.coercions[key] = value;
  216. flags.keys.push(key);
  217. }
  218. });
  219. }
  220. if (typeof opts.config !== 'undefined') {
  221. if (Array.isArray(opts.config) || typeof opts.config === 'string') {
  222. [].concat(opts.config).filter(Boolean).forEach(function (key) {
  223. flags.configs[key] = true;
  224. });
  225. }
  226. else if (typeof opts.config === 'object') {
  227. Object.entries(opts.config).forEach(([key, value]) => {
  228. if (typeof value === 'boolean' || typeof value === 'function') {
  229. flags.configs[key] = value;
  230. }
  231. });
  232. }
  233. }
  234. extendAliases(opts.key, aliases, opts.default, flags.arrays);
  235. Object.keys(defaults).forEach(function (key) {
  236. (flags.aliases[key] || []).forEach(function (alias) {
  237. defaults[alias] = defaults[key];
  238. });
  239. });
  240. let error = null;
  241. checkConfiguration();
  242. let notFlags = [];
  243. const argv = Object.assign(Object.create(null), { _: [] });
  244. const argvReturn = {};
  245. for (let i = 0; i < args.length; i++) {
  246. const arg = args[i];
  247. const truncatedArg = arg.replace(/^-{3,}/, '---');
  248. let broken;
  249. let key;
  250. let letters;
  251. let m;
  252. let next;
  253. let value;
  254. if (arg !== '--' && isUnknownOptionAsArg(arg)) {
  255. pushPositional(arg);
  256. }
  257. else if (truncatedArg.match(/---+(=|$)/)) {
  258. pushPositional(arg);
  259. continue;
  260. }
  261. else if (arg.match(/^--.+=/) || (!configuration['short-option-groups'] && arg.match(/^-.+=/))) {
  262. m = arg.match(/^--?([^=]+)=([\s\S]*)$/);
  263. if (m !== null && Array.isArray(m) && m.length >= 3) {
  264. if (checkAllAliases(m[1], flags.arrays)) {
  265. i = eatArray(i, m[1], args, m[2]);
  266. }
  267. else if (checkAllAliases(m[1], flags.nargs) !== false) {
  268. i = eatNargs(i, m[1], args, m[2]);
  269. }
  270. else {
  271. setArg(m[1], m[2], true);
  272. }
  273. }
  274. }
  275. else if (arg.match(negatedBoolean) && configuration['boolean-negation']) {
  276. m = arg.match(negatedBoolean);
  277. if (m !== null && Array.isArray(m) && m.length >= 2) {
  278. key = m[1];
  279. setArg(key, checkAllAliases(key, flags.arrays) ? [false] : false);
  280. }
  281. }
  282. else if (arg.match(/^--.+/) || (!configuration['short-option-groups'] && arg.match(/^-[^-]+/))) {
  283. m = arg.match(/^--?(.+)/);
  284. if (m !== null && Array.isArray(m) && m.length >= 2) {
  285. key = m[1];
  286. if (checkAllAliases(key, flags.arrays)) {
  287. i = eatArray(i, key, args);
  288. }
  289. else if (checkAllAliases(key, flags.nargs) !== false) {
  290. i = eatNargs(i, key, args);
  291. }
  292. else {
  293. next = args[i + 1];
  294. if (next !== undefined && (!next.match(/^-/) ||
  295. next.match(negative)) &&
  296. !checkAllAliases(key, flags.bools) &&
  297. !checkAllAliases(key, flags.counts)) {
  298. setArg(key, next);
  299. i++;
  300. }
  301. else if (/^(true|false)$/.test(next)) {
  302. setArg(key, next);
  303. i++;
  304. }
  305. else {
  306. setArg(key, defaultValue(key));
  307. }
  308. }
  309. }
  310. }
  311. else if (arg.match(/^-.\..+=/)) {
  312. m = arg.match(/^-([^=]+)=([\s\S]*)$/);
  313. if (m !== null && Array.isArray(m) && m.length >= 3) {
  314. setArg(m[1], m[2]);
  315. }
  316. }
  317. else if (arg.match(/^-.\..+/) && !arg.match(negative)) {
  318. next = args[i + 1];
  319. m = arg.match(/^-(.\..+)/);
  320. if (m !== null && Array.isArray(m) && m.length >= 2) {
  321. key = m[1];
  322. if (next !== undefined && !next.match(/^-/) &&
  323. !checkAllAliases(key, flags.bools) &&
  324. !checkAllAliases(key, flags.counts)) {
  325. setArg(key, next);
  326. i++;
  327. }
  328. else {
  329. setArg(key, defaultValue(key));
  330. }
  331. }
  332. }
  333. else if (arg.match(/^-[^-]+/) && !arg.match(negative)) {
  334. letters = arg.slice(1, -1).split('');
  335. broken = false;
  336. for (let j = 0; j < letters.length; j++) {
  337. next = arg.slice(j + 2);
  338. if (letters[j + 1] && letters[j + 1] === '=') {
  339. value = arg.slice(j + 3);
  340. key = letters[j];
  341. if (checkAllAliases(key, flags.arrays)) {
  342. i = eatArray(i, key, args, value);
  343. }
  344. else if (checkAllAliases(key, flags.nargs) !== false) {
  345. i = eatNargs(i, key, args, value);
  346. }
  347. else {
  348. setArg(key, value);
  349. }
  350. broken = true;
  351. break;
  352. }
  353. if (next === '-') {
  354. setArg(letters[j], next);
  355. continue;
  356. }
  357. if (/[A-Za-z]/.test(letters[j]) &&
  358. /^-?\d+(\.\d*)?(e-?\d+)?$/.test(next) &&
  359. checkAllAliases(next, flags.bools) === false) {
  360. setArg(letters[j], next);
  361. broken = true;
  362. break;
  363. }
  364. if (letters[j + 1] && letters[j + 1].match(/\W/)) {
  365. setArg(letters[j], next);
  366. broken = true;
  367. break;
  368. }
  369. else {
  370. setArg(letters[j], defaultValue(letters[j]));
  371. }
  372. }
  373. key = arg.slice(-1)[0];
  374. if (!broken && key !== '-') {
  375. if (checkAllAliases(key, flags.arrays)) {
  376. i = eatArray(i, key, args);
  377. }
  378. else if (checkAllAliases(key, flags.nargs) !== false) {
  379. i = eatNargs(i, key, args);
  380. }
  381. else {
  382. next = args[i + 1];
  383. if (next !== undefined && (!/^(-|--)[^-]/.test(next) ||
  384. next.match(negative)) &&
  385. !checkAllAliases(key, flags.bools) &&
  386. !checkAllAliases(key, flags.counts)) {
  387. setArg(key, next);
  388. i++;
  389. }
  390. else if (/^(true|false)$/.test(next)) {
  391. setArg(key, next);
  392. i++;
  393. }
  394. else {
  395. setArg(key, defaultValue(key));
  396. }
  397. }
  398. }
  399. }
  400. else if (arg.match(/^-[0-9]$/) &&
  401. arg.match(negative) &&
  402. checkAllAliases(arg.slice(1), flags.bools)) {
  403. key = arg.slice(1);
  404. setArg(key, defaultValue(key));
  405. }
  406. else if (arg === '--') {
  407. notFlags = args.slice(i + 1);
  408. break;
  409. }
  410. else if (configuration['halt-at-non-option']) {
  411. notFlags = args.slice(i);
  412. break;
  413. }
  414. else {
  415. pushPositional(arg);
  416. }
  417. }
  418. applyEnvVars(argv, true);
  419. applyEnvVars(argv, false);
  420. setConfig(argv);
  421. setConfigObjects();
  422. applyDefaultsAndAliases(argv, flags.aliases, defaults, true);
  423. applyCoercions(argv);
  424. if (configuration['set-placeholder-key'])
  425. setPlaceholderKeys(argv);
  426. Object.keys(flags.counts).forEach(function (key) {
  427. if (!hasKey(argv, key.split('.')))
  428. setArg(key, 0);
  429. });
  430. if (notFlagsOption && notFlags.length)
  431. argv[notFlagsArgv] = [];
  432. notFlags.forEach(function (key) {
  433. argv[notFlagsArgv].push(key);
  434. });
  435. if (configuration['camel-case-expansion'] && configuration['strip-dashed']) {
  436. Object.keys(argv).filter(key => key !== '--' && key.includes('-')).forEach(key => {
  437. delete argv[key];
  438. });
  439. }
  440. if (configuration['strip-aliased']) {
  441. [].concat(...Object.keys(aliases).map(k => aliases[k])).forEach(alias => {
  442. if (configuration['camel-case-expansion'] && alias.includes('-')) {
  443. delete argv[alias.split('.').map(prop => camelCase(prop)).join('.')];
  444. }
  445. delete argv[alias];
  446. });
  447. }
  448. function pushPositional(arg) {
  449. const maybeCoercedNumber = maybeCoerceNumber('_', arg);
  450. if (typeof maybeCoercedNumber === 'string' || typeof maybeCoercedNumber === 'number') {
  451. argv._.push(maybeCoercedNumber);
  452. }
  453. }
  454. function eatNargs(i, key, args, argAfterEqualSign) {
  455. let ii;
  456. let toEat = checkAllAliases(key, flags.nargs);
  457. toEat = typeof toEat !== 'number' || isNaN(toEat) ? 1 : toEat;
  458. if (toEat === 0) {
  459. if (!isUndefined(argAfterEqualSign)) {
  460. error = Error(__('Argument unexpected for: %s', key));
  461. }
  462. setArg(key, defaultValue(key));
  463. return i;
  464. }
  465. let available = isUndefined(argAfterEqualSign) ? 0 : 1;
  466. if (configuration['nargs-eats-options']) {
  467. if (args.length - (i + 1) + available < toEat) {
  468. error = Error(__('Not enough arguments following: %s', key));
  469. }
  470. available = toEat;
  471. }
  472. else {
  473. for (ii = i + 1; ii < args.length; ii++) {
  474. if (!args[ii].match(/^-[^0-9]/) || args[ii].match(negative) || isUnknownOptionAsArg(args[ii]))
  475. available++;
  476. else
  477. break;
  478. }
  479. if (available < toEat)
  480. error = Error(__('Not enough arguments following: %s', key));
  481. }
  482. let consumed = Math.min(available, toEat);
  483. if (!isUndefined(argAfterEqualSign) && consumed > 0) {
  484. setArg(key, argAfterEqualSign);
  485. consumed--;
  486. }
  487. for (ii = i + 1; ii < (consumed + i + 1); ii++) {
  488. setArg(key, args[ii]);
  489. }
  490. return (i + consumed);
  491. }
  492. function eatArray(i, key, args, argAfterEqualSign) {
  493. let argsToSet = [];
  494. let next = argAfterEqualSign || args[i + 1];
  495. const nargsCount = checkAllAliases(key, flags.nargs);
  496. if (checkAllAliases(key, flags.bools) && !(/^(true|false)$/.test(next))) {
  497. argsToSet.push(true);
  498. }
  499. else if (isUndefined(next) ||
  500. (isUndefined(argAfterEqualSign) && /^-/.test(next) && !negative.test(next) && !isUnknownOptionAsArg(next))) {
  501. if (defaults[key] !== undefined) {
  502. const defVal = defaults[key];
  503. argsToSet = Array.isArray(defVal) ? defVal : [defVal];
  504. }
  505. }
  506. else {
  507. if (!isUndefined(argAfterEqualSign)) {
  508. argsToSet.push(processValue(key, argAfterEqualSign, true));
  509. }
  510. for (let ii = i + 1; ii < args.length; ii++) {
  511. if ((!configuration['greedy-arrays'] && argsToSet.length > 0) ||
  512. (nargsCount && typeof nargsCount === 'number' && argsToSet.length >= nargsCount))
  513. break;
  514. next = args[ii];
  515. if (/^-/.test(next) && !negative.test(next) && !isUnknownOptionAsArg(next))
  516. break;
  517. i = ii;
  518. argsToSet.push(processValue(key, next, inputIsString));
  519. }
  520. }
  521. if (typeof nargsCount === 'number' && ((nargsCount && argsToSet.length < nargsCount) ||
  522. (isNaN(nargsCount) && argsToSet.length === 0))) {
  523. error = Error(__('Not enough arguments following: %s', key));
  524. }
  525. setArg(key, argsToSet);
  526. return i;
  527. }
  528. function setArg(key, val, shouldStripQuotes = inputIsString) {
  529. if (/-/.test(key) && configuration['camel-case-expansion']) {
  530. const alias = key.split('.').map(function (prop) {
  531. return camelCase(prop);
  532. }).join('.');
  533. addNewAlias(key, alias);
  534. }
  535. const value = processValue(key, val, shouldStripQuotes);
  536. const splitKey = key.split('.');
  537. setKey(argv, splitKey, value);
  538. if (flags.aliases[key]) {
  539. flags.aliases[key].forEach(function (x) {
  540. const keyProperties = x.split('.');
  541. setKey(argv, keyProperties, value);
  542. });
  543. }
  544. if (splitKey.length > 1 && configuration['dot-notation']) {
  545. (flags.aliases[splitKey[0]] || []).forEach(function (x) {
  546. let keyProperties = x.split('.');
  547. const a = [].concat(splitKey);
  548. a.shift();
  549. keyProperties = keyProperties.concat(a);
  550. if (!(flags.aliases[key] || []).includes(keyProperties.join('.'))) {
  551. setKey(argv, keyProperties, value);
  552. }
  553. });
  554. }
  555. if (checkAllAliases(key, flags.normalize) && !checkAllAliases(key, flags.arrays)) {
  556. const keys = [key].concat(flags.aliases[key] || []);
  557. keys.forEach(function (key) {
  558. Object.defineProperty(argvReturn, key, {
  559. enumerable: true,
  560. get() {
  561. return val;
  562. },
  563. set(value) {
  564. val = typeof value === 'string' ? mixin.normalize(value) : value;
  565. }
  566. });
  567. });
  568. }
  569. }
  570. function addNewAlias(key, alias) {
  571. if (!(flags.aliases[key] && flags.aliases[key].length)) {
  572. flags.aliases[key] = [alias];
  573. newAliases[alias] = true;
  574. }
  575. if (!(flags.aliases[alias] && flags.aliases[alias].length)) {
  576. addNewAlias(alias, key);
  577. }
  578. }
  579. function processValue(key, val, shouldStripQuotes) {
  580. if (shouldStripQuotes) {
  581. val = stripQuotes(val);
  582. }
  583. if (checkAllAliases(key, flags.bools) || checkAllAliases(key, flags.counts)) {
  584. if (typeof val === 'string')
  585. val = val === 'true';
  586. }
  587. let value = Array.isArray(val)
  588. ? val.map(function (v) { return maybeCoerceNumber(key, v); })
  589. : maybeCoerceNumber(key, val);
  590. if (checkAllAliases(key, flags.counts) && (isUndefined(value) || typeof value === 'boolean')) {
  591. value = increment();
  592. }
  593. if (checkAllAliases(key, flags.normalize) && checkAllAliases(key, flags.arrays)) {
  594. if (Array.isArray(val))
  595. value = val.map((val) => { return mixin.normalize(val); });
  596. else
  597. value = mixin.normalize(val);
  598. }
  599. return value;
  600. }
  601. function maybeCoerceNumber(key, value) {
  602. if (!configuration['parse-positional-numbers'] && key === '_')
  603. return value;
  604. if (!checkAllAliases(key, flags.strings) && !checkAllAliases(key, flags.bools) && !Array.isArray(value)) {
  605. const shouldCoerceNumber = looksLikeNumber(value) && configuration['parse-numbers'] && (Number.isSafeInteger(Math.floor(parseFloat(`${value}`))));
  606. if (shouldCoerceNumber || (!isUndefined(value) && checkAllAliases(key, flags.numbers))) {
  607. value = Number(value);
  608. }
  609. }
  610. return value;
  611. }
  612. function setConfig(argv) {
  613. const configLookup = Object.create(null);
  614. applyDefaultsAndAliases(configLookup, flags.aliases, defaults);
  615. Object.keys(flags.configs).forEach(function (configKey) {
  616. const configPath = argv[configKey] || configLookup[configKey];
  617. if (configPath) {
  618. try {
  619. let config = null;
  620. const resolvedConfigPath = mixin.resolve(mixin.cwd(), configPath);
  621. const resolveConfig = flags.configs[configKey];
  622. if (typeof resolveConfig === 'function') {
  623. try {
  624. config = resolveConfig(resolvedConfigPath);
  625. }
  626. catch (e) {
  627. config = e;
  628. }
  629. if (config instanceof Error) {
  630. error = config;
  631. return;
  632. }
  633. }
  634. else {
  635. config = mixin.require(resolvedConfigPath);
  636. }
  637. setConfigObject(config);
  638. }
  639. catch (ex) {
  640. if (ex.name === 'PermissionDenied')
  641. error = ex;
  642. else if (argv[configKey])
  643. error = Error(__('Invalid JSON config file: %s', configPath));
  644. }
  645. }
  646. });
  647. }
  648. function setConfigObject(config, prev) {
  649. Object.keys(config).forEach(function (key) {
  650. const value = config[key];
  651. const fullKey = prev ? prev + '.' + key : key;
  652. if (typeof value === 'object' && value !== null && !Array.isArray(value) && configuration['dot-notation']) {
  653. setConfigObject(value, fullKey);
  654. }
  655. else {
  656. if (!hasKey(argv, fullKey.split('.')) || (checkAllAliases(fullKey, flags.arrays) && configuration['combine-arrays'])) {
  657. setArg(fullKey, value);
  658. }
  659. }
  660. });
  661. }
  662. function setConfigObjects() {
  663. if (typeof configObjects !== 'undefined') {
  664. configObjects.forEach(function (configObject) {
  665. setConfigObject(configObject);
  666. });
  667. }
  668. }
  669. function applyEnvVars(argv, configOnly) {
  670. if (typeof envPrefix === 'undefined')
  671. return;
  672. const prefix = typeof envPrefix === 'string' ? envPrefix : '';
  673. const env = mixin.env();
  674. Object.keys(env).forEach(function (envVar) {
  675. if (prefix === '' || envVar.lastIndexOf(prefix, 0) === 0) {
  676. const keys = envVar.split('__').map(function (key, i) {
  677. if (i === 0) {
  678. key = key.substring(prefix.length);
  679. }
  680. return camelCase(key);
  681. });
  682. if (((configOnly && flags.configs[keys.join('.')]) || !configOnly) && !hasKey(argv, keys)) {
  683. setArg(keys.join('.'), env[envVar]);
  684. }
  685. }
  686. });
  687. }
  688. function applyCoercions(argv) {
  689. let coerce;
  690. const applied = new Set();
  691. Object.keys(argv).forEach(function (key) {
  692. if (!applied.has(key)) {
  693. coerce = checkAllAliases(key, flags.coercions);
  694. if (typeof coerce === 'function') {
  695. try {
  696. const value = maybeCoerceNumber(key, coerce(argv[key]));
  697. ([].concat(flags.aliases[key] || [], key)).forEach(ali => {
  698. applied.add(ali);
  699. argv[ali] = value;
  700. });
  701. }
  702. catch (err) {
  703. error = err;
  704. }
  705. }
  706. }
  707. });
  708. }
  709. function setPlaceholderKeys(argv) {
  710. flags.keys.forEach((key) => {
  711. if (~key.indexOf('.'))
  712. return;
  713. if (typeof argv[key] === 'undefined')
  714. argv[key] = undefined;
  715. });
  716. return argv;
  717. }
  718. function applyDefaultsAndAliases(obj, aliases, defaults, canLog = false) {
  719. Object.keys(defaults).forEach(function (key) {
  720. if (!hasKey(obj, key.split('.'))) {
  721. setKey(obj, key.split('.'), defaults[key]);
  722. if (canLog)
  723. defaulted[key] = true;
  724. (aliases[key] || []).forEach(function (x) {
  725. if (hasKey(obj, x.split('.')))
  726. return;
  727. setKey(obj, x.split('.'), defaults[key]);
  728. });
  729. }
  730. });
  731. }
  732. function hasKey(obj, keys) {
  733. let o = obj;
  734. if (!configuration['dot-notation'])
  735. keys = [keys.join('.')];
  736. keys.slice(0, -1).forEach(function (key) {
  737. o = (o[key] || {});
  738. });
  739. const key = keys[keys.length - 1];
  740. if (typeof o !== 'object')
  741. return false;
  742. else
  743. return key in o;
  744. }
  745. function setKey(obj, keys, value) {
  746. let o = obj;
  747. if (!configuration['dot-notation'])
  748. keys = [keys.join('.')];
  749. keys.slice(0, -1).forEach(function (key) {
  750. key = sanitizeKey(key);
  751. if (typeof o === 'object' && o[key] === undefined) {
  752. o[key] = {};
  753. }
  754. if (typeof o[key] !== 'object' || Array.isArray(o[key])) {
  755. if (Array.isArray(o[key])) {
  756. o[key].push({});
  757. }
  758. else {
  759. o[key] = [o[key], {}];
  760. }
  761. o = o[key][o[key].length - 1];
  762. }
  763. else {
  764. o = o[key];
  765. }
  766. });
  767. const key = sanitizeKey(keys[keys.length - 1]);
  768. const isTypeArray = checkAllAliases(keys.join('.'), flags.arrays);
  769. const isValueArray = Array.isArray(value);
  770. let duplicate = configuration['duplicate-arguments-array'];
  771. if (!duplicate && checkAllAliases(key, flags.nargs)) {
  772. duplicate = true;
  773. if ((!isUndefined(o[key]) && flags.nargs[key] === 1) || (Array.isArray(o[key]) && o[key].length === flags.nargs[key])) {
  774. o[key] = undefined;
  775. }
  776. }
  777. if (value === increment()) {
  778. o[key] = increment(o[key]);
  779. }
  780. else if (Array.isArray(o[key])) {
  781. if (duplicate && isTypeArray && isValueArray) {
  782. o[key] = configuration['flatten-duplicate-arrays'] ? o[key].concat(value) : (Array.isArray(o[key][0]) ? o[key] : [o[key]]).concat([value]);
  783. }
  784. else if (!duplicate && Boolean(isTypeArray) === Boolean(isValueArray)) {
  785. o[key] = value;
  786. }
  787. else {
  788. o[key] = o[key].concat([value]);
  789. }
  790. }
  791. else if (o[key] === undefined && isTypeArray) {
  792. o[key] = isValueArray ? value : [value];
  793. }
  794. else if (duplicate && !(o[key] === undefined ||
  795. checkAllAliases(key, flags.counts) ||
  796. checkAllAliases(key, flags.bools))) {
  797. o[key] = [o[key], value];
  798. }
  799. else {
  800. o[key] = value;
  801. }
  802. }
  803. function extendAliases(...args) {
  804. args.forEach(function (obj) {
  805. Object.keys(obj || {}).forEach(function (key) {
  806. if (flags.aliases[key])
  807. return;
  808. flags.aliases[key] = [].concat(aliases[key] || []);
  809. flags.aliases[key].concat(key).forEach(function (x) {
  810. if (/-/.test(x) && configuration['camel-case-expansion']) {
  811. const c = camelCase(x);
  812. if (c !== key && flags.aliases[key].indexOf(c) === -1) {
  813. flags.aliases[key].push(c);
  814. newAliases[c] = true;
  815. }
  816. }
  817. });
  818. flags.aliases[key].concat(key).forEach(function (x) {
  819. if (x.length > 1 && /[A-Z]/.test(x) && configuration['camel-case-expansion']) {
  820. const c = decamelize(x, '-');
  821. if (c !== key && flags.aliases[key].indexOf(c) === -1) {
  822. flags.aliases[key].push(c);
  823. newAliases[c] = true;
  824. }
  825. }
  826. });
  827. flags.aliases[key].forEach(function (x) {
  828. flags.aliases[x] = [key].concat(flags.aliases[key].filter(function (y) {
  829. return x !== y;
  830. }));
  831. });
  832. });
  833. });
  834. }
  835. function checkAllAliases(key, flag) {
  836. const toCheck = [].concat(flags.aliases[key] || [], key);
  837. const keys = Object.keys(flag);
  838. const setAlias = toCheck.find(key => keys.includes(key));
  839. return setAlias ? flag[setAlias] : false;
  840. }
  841. function hasAnyFlag(key) {
  842. const flagsKeys = Object.keys(flags);
  843. const toCheck = [].concat(flagsKeys.map(k => flags[k]));
  844. return toCheck.some(function (flag) {
  845. return Array.isArray(flag) ? flag.includes(key) : flag[key];
  846. });
  847. }
  848. function hasFlagsMatching(arg, ...patterns) {
  849. const toCheck = [].concat(...patterns);
  850. return toCheck.some(function (pattern) {
  851. const match = arg.match(pattern);
  852. return match && hasAnyFlag(match[1]);
  853. });
  854. }
  855. function hasAllShortFlags(arg) {
  856. if (arg.match(negative) || !arg.match(/^-[^-]+/)) {
  857. return false;
  858. }
  859. let hasAllFlags = true;
  860. let next;
  861. const letters = arg.slice(1).split('');
  862. for (let j = 0; j < letters.length; j++) {
  863. next = arg.slice(j + 2);
  864. if (!hasAnyFlag(letters[j])) {
  865. hasAllFlags = false;
  866. break;
  867. }
  868. if ((letters[j + 1] && letters[j + 1] === '=') ||
  869. next === '-' ||
  870. (/[A-Za-z]/.test(letters[j]) && /^-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) ||
  871. (letters[j + 1] && letters[j + 1].match(/\W/))) {
  872. break;
  873. }
  874. }
  875. return hasAllFlags;
  876. }
  877. function isUnknownOptionAsArg(arg) {
  878. return configuration['unknown-options-as-args'] && isUnknownOption(arg);
  879. }
  880. function isUnknownOption(arg) {
  881. arg = arg.replace(/^-{3,}/, '--');
  882. if (arg.match(negative)) {
  883. return false;
  884. }
  885. if (hasAllShortFlags(arg)) {
  886. return false;
  887. }
  888. const flagWithEquals = /^-+([^=]+?)=[\s\S]*$/;
  889. const normalFlag = /^-+([^=]+?)$/;
  890. const flagEndingInHyphen = /^-+([^=]+?)-$/;
  891. const flagEndingInDigits = /^-+([^=]+?\d+)$/;
  892. const flagEndingInNonWordCharacters = /^-+([^=]+?)\W+.*$/;
  893. return !hasFlagsMatching(arg, flagWithEquals, negatedBoolean, normalFlag, flagEndingInHyphen, flagEndingInDigits, flagEndingInNonWordCharacters);
  894. }
  895. function defaultValue(key) {
  896. if (!checkAllAliases(key, flags.bools) &&
  897. !checkAllAliases(key, flags.counts) &&
  898. `${key}` in defaults) {
  899. return defaults[key];
  900. }
  901. else {
  902. return defaultForType(guessType(key));
  903. }
  904. }
  905. function defaultForType(type) {
  906. const def = {
  907. [DefaultValuesForTypeKey.BOOLEAN]: true,
  908. [DefaultValuesForTypeKey.STRING]: '',
  909. [DefaultValuesForTypeKey.NUMBER]: undefined,
  910. [DefaultValuesForTypeKey.ARRAY]: []
  911. };
  912. return def[type];
  913. }
  914. function guessType(key) {
  915. let type = DefaultValuesForTypeKey.BOOLEAN;
  916. if (checkAllAliases(key, flags.strings))
  917. type = DefaultValuesForTypeKey.STRING;
  918. else if (checkAllAliases(key, flags.numbers))
  919. type = DefaultValuesForTypeKey.NUMBER;
  920. else if (checkAllAliases(key, flags.bools))
  921. type = DefaultValuesForTypeKey.BOOLEAN;
  922. else if (checkAllAliases(key, flags.arrays))
  923. type = DefaultValuesForTypeKey.ARRAY;
  924. return type;
  925. }
  926. function isUndefined(num) {
  927. return num === undefined;
  928. }
  929. function checkConfiguration() {
  930. Object.keys(flags.counts).find(key => {
  931. if (checkAllAliases(key, flags.arrays)) {
  932. error = Error(__('Invalid configuration: %s, opts.count excludes opts.array.', key));
  933. return true;
  934. }
  935. else if (checkAllAliases(key, flags.nargs)) {
  936. error = Error(__('Invalid configuration: %s, opts.count excludes opts.narg.', key));
  937. return true;
  938. }
  939. return false;
  940. });
  941. }
  942. return {
  943. aliases: Object.assign({}, flags.aliases),
  944. argv: Object.assign(argvReturn, argv),
  945. configuration: configuration,
  946. defaulted: Object.assign({}, defaulted),
  947. error: error,
  948. newAliases: Object.assign({}, newAliases)
  949. };
  950. }
  951. }
  952. function combineAliases(aliases) {
  953. const aliasArrays = [];
  954. const combined = Object.create(null);
  955. let change = true;
  956. Object.keys(aliases).forEach(function (key) {
  957. aliasArrays.push([].concat(aliases[key], key));
  958. });
  959. while (change) {
  960. change = false;
  961. for (let i = 0; i < aliasArrays.length; i++) {
  962. for (let ii = i + 1; ii < aliasArrays.length; ii++) {
  963. const intersect = aliasArrays[i].filter(function (v) {
  964. return aliasArrays[ii].indexOf(v) !== -1;
  965. });
  966. if (intersect.length) {
  967. aliasArrays[i] = aliasArrays[i].concat(aliasArrays[ii]);
  968. aliasArrays.splice(ii, 1);
  969. change = true;
  970. break;
  971. }
  972. }
  973. }
  974. }
  975. aliasArrays.forEach(function (aliasArray) {
  976. aliasArray = aliasArray.filter(function (v, i, self) {
  977. return self.indexOf(v) === i;
  978. });
  979. const lastAlias = aliasArray.pop();
  980. if (lastAlias !== undefined && typeof lastAlias === 'string') {
  981. combined[lastAlias] = aliasArray;
  982. }
  983. });
  984. return combined;
  985. }
  986. function increment(orig) {
  987. return orig !== undefined ? orig + 1 : 1;
  988. }
  989. function sanitizeKey(key) {
  990. if (key === '__proto__')
  991. return '___proto___';
  992. return key;
  993. }
  994. function stripQuotes(val) {
  995. return (typeof val === 'string' &&
  996. (val[0] === "'" || val[0] === '"') &&
  997. val[val.length - 1] === val[0])
  998. ? val.substring(1, val.length - 1)
  999. : val;
  1000. }
  1001. const minNodeVersion = (process && process.env && process.env.YARGS_MIN_NODE_VERSION)
  1002. ? Number(process.env.YARGS_MIN_NODE_VERSION)
  1003. : 12;
  1004. if (process && process.version) {
  1005. const major = Number(process.version.match(/v([^.]+)/)[1]);
  1006. if (major < minNodeVersion) {
  1007. 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`);
  1008. }
  1009. }
  1010. const env = process ? process.env : {};
  1011. const parser = new YargsParser({
  1012. cwd: process.cwd,
  1013. env: () => {
  1014. return env;
  1015. },
  1016. format: util.format,
  1017. normalize: path.normalize,
  1018. resolve: path.resolve,
  1019. require: (path) => {
  1020. if (typeof require !== 'undefined') {
  1021. return require(path);
  1022. }
  1023. else if (path.match(/\.json$/)) {
  1024. return JSON.parse(fs.readFileSync(path, 'utf8'));
  1025. }
  1026. else {
  1027. throw Error('only .json config files are supported in ESM');
  1028. }
  1029. }
  1030. });
  1031. const yargsParser = function Parser(args, opts) {
  1032. const result = parser.parse(args.slice(), opts);
  1033. return result.argv;
  1034. };
  1035. yargsParser.detailed = function (args, opts) {
  1036. return parser.parse(args.slice(), opts);
  1037. };
  1038. yargsParser.camelCase = camelCase;
  1039. yargsParser.decamelize = decamelize;
  1040. yargsParser.looksLikeNumber = looksLikeNumber;
  1041. module.exports = yargsParser;