Keine Beschreibung
Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

index.cjs 41KB

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