index.cjs 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050
  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 !== '--' && /^-/.test(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. var _a, _b, _c;
  1002. const minNodeVersion = (process && process.env && process.env.YARGS_MIN_NODE_VERSION)
  1003. ? Number(process.env.YARGS_MIN_NODE_VERSION)
  1004. : 12;
  1005. const nodeVersion = (_b = (_a = process === null || process === void 0 ? void 0 : process.versions) === null || _a === void 0 ? void 0 : _a.node) !== null && _b !== void 0 ? _b : (_c = process === null || process === void 0 ? void 0 : process.version) === null || _c === void 0 ? void 0 : _c.slice(1);
  1006. if (nodeVersion) {
  1007. const major = Number(nodeVersion.match(/^([^.]+)/)[1]);
  1008. if (major < minNodeVersion) {
  1009. 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`);
  1010. }
  1011. }
  1012. const env = process ? process.env : {};
  1013. const parser = new YargsParser({
  1014. cwd: process.cwd,
  1015. env: () => {
  1016. return env;
  1017. },
  1018. format: util.format,
  1019. normalize: path.normalize,
  1020. resolve: path.resolve,
  1021. require: (path) => {
  1022. if (typeof require !== 'undefined') {
  1023. return require(path);
  1024. }
  1025. else if (path.match(/\.json$/)) {
  1026. return JSON.parse(fs.readFileSync(path, 'utf8'));
  1027. }
  1028. else {
  1029. throw Error('only .json config files are supported in ESM');
  1030. }
  1031. }
  1032. });
  1033. const yargsParser = function Parser(args, opts) {
  1034. const result = parser.parse(args.slice(), opts);
  1035. return result.argv;
  1036. };
  1037. yargsParser.detailed = function (args, opts) {
  1038. return parser.parse(args.slice(), opts);
  1039. };
  1040. yargsParser.camelCase = camelCase;
  1041. yargsParser.decamelize = decamelize;
  1042. yargsParser.looksLikeNumber = looksLikeNumber;
  1043. module.exports = yargsParser;