rollup 79 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884
  1. #!/usr/bin/env node
  2. /*
  3. @license
  4. Rollup.js v4.41.0
  5. Sun, 18 May 2025 05:33:01 GMT - commit 0928185cd544907dab472754634ddf988452aae6
  6. https://github.com/rollup/rollup
  7. Released under the MIT License.
  8. */
  9. 'use strict';
  10. Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
  11. const process$1 = require('node:process');
  12. const rollup = require('../shared/rollup.js');
  13. const require$$2 = require('util');
  14. const require$$0 = require('path');
  15. const require$$0$1 = require('fs');
  16. const parseAst_js = require('../shared/parseAst.js');
  17. const fseventsImporter = require('../shared/fsevents-importer.js');
  18. const promises = require('node:fs/promises');
  19. const path = require('node:path');
  20. const loadConfigFile_js = require('../shared/loadConfigFile.js');
  21. require('../native.js');
  22. require('node:perf_hooks');
  23. require('node:url');
  24. require('../getLogFilter.js');
  25. const help = "rollup version __VERSION__\n=====================================\n\nUsage: rollup [options] <entry file>\n\nBasic options:\n\n-c, --config <filename> Use this config file (if argument is used but value\n is unspecified, defaults to rollup.config.js)\n-d, --dir <dirname> Directory for chunks (if absent, prints to stdout)\n-e, --external <ids> Comma-separate list of module IDs to exclude\n-f, --format <format> Type of output (amd, cjs, es, iife, umd, system)\n-g, --globals <pairs> Comma-separate list of `moduleID:Global` pairs\n-h, --help Show this help message\n-i, --input <filename> Input (alternative to <entry file>)\n-m, --sourcemap Generate sourcemap (`-m inline` for inline map)\n-n, --name <name> Name for UMD export\n-o, --file <output> Single output file (if absent, prints to stdout)\n-p, --plugin <plugin> Use the plugin specified (may be repeated)\n-v, --version Show version number\n-w, --watch Watch files in bundle and rebuild on changes\n--amd.autoId Generate the AMD ID based off the chunk name\n--amd.basePath <prefix> Path to prepend to auto generated AMD ID\n--amd.define <name> Function to use in place of `define`\n--amd.forceJsExtensionForImports Use `.js` extension in AMD imports\n--amd.id <id> ID for AMD module (default is anonymous)\n--assetFileNames <pattern> Name pattern for emitted assets\n--banner <text> Code to insert at top of bundle (outside wrapper)\n--chunkFileNames <pattern> Name pattern for emitted secondary chunks\n--compact Minify wrapper code\n--context <variable> Specify top-level `this` value\n--no-dynamicImportInCjs Write external dynamic CommonJS imports as require\n--entryFileNames <pattern> Name pattern for emitted entry chunks\n--environment <values> Settings passed to config file (see example)\n--no-esModule Do not add __esModule property\n--exports <mode> Specify export mode (auto, default, named, none)\n--extend Extend global variable defined by --name\n--no-externalImportAttributes Omit import attributes in \"es\" output\n--no-externalLiveBindings Do not generate code to support live bindings\n--failAfterWarnings Exit with an error if the build produced warnings\n--filterLogs <filter> Filter log messages\n--footer <text> Code to insert at end of bundle (outside wrapper)\n--forceExit Force exit the process when done\n--no-freeze Do not freeze namespace objects\n--generatedCode <preset> Which code features to use (es5/es2015)\n--generatedCode.arrowFunctions Use arrow functions in generated code\n--generatedCode.constBindings Use \"const\" in generated code\n--generatedCode.objectShorthand Use shorthand properties in generated code\n--no-generatedCode.reservedNamesAsProps Always quote reserved names as props\n--generatedCode.symbols Use symbols in generated code\n--hashCharacters <name> Use the specified character set for file hashes\n--no-hoistTransitiveImports Do not hoist transitive imports into entry chunks\n--importAttributesKey <name> Use the specified keyword for import attributes\n--no-indent Don't indent result\n--inlineDynamicImports Create single bundle when using dynamic imports\n--no-interop Do not include interop block\n--intro <text> Code to insert at top of bundle (inside wrapper)\n--logLevel <level> Which kind of logs to display\n--no-makeAbsoluteExternalsRelative Prevent normalization of external imports\n--maxParallelFileOps <value> How many files to read in parallel\n--minifyInternalExports Force or disable minification of internal exports\n--noConflict Generate a noConflict method for UMD globals\n--outro <text> Code to insert at end of bundle (inside wrapper)\n--perf Display performance timings\n--no-preserveEntrySignatures Avoid facade chunks for entry points\n--preserveModules Preserve module structure\n--preserveModulesRoot Put preserved modules under this path at root level\n--preserveSymlinks Do not follow symlinks when resolving files\n--no-reexportProtoFromExternal Ignore `__proto__` in star re-exports\n--no-sanitizeFileName Do not replace invalid characters in file names\n--shimMissingExports Create shim variables for missing exports\n--silent Don't print warnings\n--sourcemapBaseUrl <url> Emit absolute sourcemap URLs with given base\n--sourcemapDebugIds Emit unique debug ids in source and sourcemaps\n--sourcemapExcludeSources Do not include source code in source maps\n--sourcemapFile <file> Specify bundle position for source maps\n--sourcemapFileNames <pattern> Name pattern for emitted sourcemaps\n--stdin=ext Specify file extension used for stdin input\n--no-stdin Do not read \"-\" from stdin\n--no-strict Don't emit `\"use strict\";` in the generated modules\n--strictDeprecations Throw errors for deprecated features\n--no-systemNullSetters Do not replace empty SystemJS setters with `null`\n--no-treeshake Disable tree-shaking optimisations\n--no-treeshake.annotations Ignore pure call annotations\n--treeshake.correctVarValueBeforeDeclaration Deoptimize variables until declared\n--treeshake.manualPureFunctions <names> Manually declare functions as pure\n--no-treeshake.moduleSideEffects Assume modules have no side effects\n--no-treeshake.propertyReadSideEffects Ignore property access side effects\n--no-treeshake.tryCatchDeoptimization Do not turn off try-catch-tree-shaking\n--no-treeshake.unknownGlobalSideEffects Assume unknown globals do not throw\n--validate Validate output\n--waitForBundleInput Wait for bundle input files\n--watch.buildDelay <number> Throttle watch rebuilds\n--no-watch.clearScreen Do not clear the screen when rebuilding\n--watch.exclude <files> Exclude files from being watched\n--watch.include <files> Limit watching to specified files\n--watch.onBundleEnd <cmd> Shell command to run on `\"BUNDLE_END\"` event\n--watch.onBundleStart <cmd> Shell command to run on `\"BUNDLE_START\"` event\n--watch.onEnd <cmd> Shell command to run on `\"END\"` event\n--watch.onError <cmd> Shell command to run on `\"ERROR\"` event\n--watch.onStart <cmd> Shell command to run on `\"START\"` event\n--watch.skipWrite Do not write files to disk when watching\n\nExamples:\n\n# use settings in config file\nrollup -c\n\n# in config file, process.env.INCLUDE_DEPS === 'true'\n# and process.env.BUILD === 'production'\nrollup -c --environment INCLUDE_DEPS,BUILD:production\n\n# create CommonJS bundle.js from src/main.js\nrollup --format=cjs --file=bundle.js -- src/main.js\n\n# create self-executing IIFE using `window.jQuery`\n# and `window._` as external globals\nrollup -f iife --globals jquery:jQuery,lodash:_ \\\n -i src/app.js -o build/app.js -m build/app.js.map\n\nNotes:\n\n* When piping to stdout, only inline sourcemaps are permitted\n\nFor more information visit https://rollupjs.org\n";
  26. /**
  27. * @license
  28. * Copyright (c) 2016, Contributors
  29. * SPDX-License-Identifier: ISC
  30. */
  31. function camelCase(str) {
  32. // Handle the case where an argument is provided as camel case, e.g., fooBar.
  33. // by ensuring that the string isn't already mixed case:
  34. const isCamelCase = str !== str.toLowerCase() && str !== str.toUpperCase();
  35. if (!isCamelCase) {
  36. str = str.toLowerCase();
  37. }
  38. if (str.indexOf('-') === -1 && str.indexOf('_') === -1) {
  39. return str;
  40. }
  41. else {
  42. let camelcase = '';
  43. let nextChrUpper = false;
  44. const leadingHyphens = str.match(/^-+/);
  45. for (let i = leadingHyphens ? leadingHyphens[0].length : 0; i < str.length; i++) {
  46. let chr = str.charAt(i);
  47. if (nextChrUpper) {
  48. nextChrUpper = false;
  49. chr = chr.toUpperCase();
  50. }
  51. if (i !== 0 && (chr === '-' || chr === '_')) {
  52. nextChrUpper = true;
  53. }
  54. else if (chr !== '-' && chr !== '_') {
  55. camelcase += chr;
  56. }
  57. }
  58. return camelcase;
  59. }
  60. }
  61. function decamelize(str, joinString) {
  62. const lowercase = str.toLowerCase();
  63. joinString = joinString || '-';
  64. let notCamelcase = '';
  65. for (let i = 0; i < str.length; i++) {
  66. const chrLower = lowercase.charAt(i);
  67. const chrString = str.charAt(i);
  68. if (chrLower !== chrString && i > 0) {
  69. notCamelcase += `${joinString}${lowercase.charAt(i)}`;
  70. }
  71. else {
  72. notCamelcase += chrString;
  73. }
  74. }
  75. return notCamelcase;
  76. }
  77. function looksLikeNumber(x) {
  78. if (x === null || x === undefined)
  79. return false;
  80. // if loaded from config, may already be a number.
  81. if (typeof x === 'number')
  82. return true;
  83. // hexadecimal.
  84. if (/^0x[0-9a-f]+$/i.test(x))
  85. return true;
  86. // don't treat 0123 as a number; as it drops the leading '0'.
  87. if (/^0[^.]/.test(x))
  88. return false;
  89. return /^[-]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x);
  90. }
  91. /**
  92. * @license
  93. * Copyright (c) 2016, Contributors
  94. * SPDX-License-Identifier: ISC
  95. */
  96. // take an un-split argv string and tokenize it.
  97. function tokenizeArgString(argString) {
  98. if (Array.isArray(argString)) {
  99. return argString.map(e => typeof e !== 'string' ? e + '' : e);
  100. }
  101. argString = argString.trim();
  102. let i = 0;
  103. let prevC = null;
  104. let c = null;
  105. let opening = null;
  106. const args = [];
  107. for (let ii = 0; ii < argString.length; ii++) {
  108. prevC = c;
  109. c = argString.charAt(ii);
  110. // split on spaces unless we're in quotes.
  111. if (c === ' ' && !opening) {
  112. if (!(prevC === ' ')) {
  113. i++;
  114. }
  115. continue;
  116. }
  117. // don't split the string if we're in matching
  118. // opening or closing single and double quotes.
  119. if (c === opening) {
  120. opening = null;
  121. }
  122. else if ((c === "'" || c === '"') && !opening) {
  123. opening = c;
  124. }
  125. if (!args[i])
  126. args[i] = '';
  127. args[i] += c;
  128. }
  129. return args;
  130. }
  131. /**
  132. * @license
  133. * Copyright (c) 2016, Contributors
  134. * SPDX-License-Identifier: ISC
  135. */
  136. var DefaultValuesForTypeKey;
  137. (function (DefaultValuesForTypeKey) {
  138. DefaultValuesForTypeKey["BOOLEAN"] = "boolean";
  139. DefaultValuesForTypeKey["STRING"] = "string";
  140. DefaultValuesForTypeKey["NUMBER"] = "number";
  141. DefaultValuesForTypeKey["ARRAY"] = "array";
  142. })(DefaultValuesForTypeKey || (DefaultValuesForTypeKey = {}));
  143. /**
  144. * @license
  145. * Copyright (c) 2016, Contributors
  146. * SPDX-License-Identifier: ISC
  147. */
  148. let mixin;
  149. class YargsParser {
  150. constructor(_mixin) {
  151. mixin = _mixin;
  152. }
  153. parse(argsInput, options) {
  154. const opts = Object.assign({
  155. alias: undefined,
  156. array: undefined,
  157. boolean: undefined,
  158. config: undefined,
  159. configObjects: undefined,
  160. configuration: undefined,
  161. coerce: undefined,
  162. count: undefined,
  163. default: undefined,
  164. envPrefix: undefined,
  165. narg: undefined,
  166. normalize: undefined,
  167. string: undefined,
  168. number: undefined,
  169. __: undefined,
  170. key: undefined
  171. }, options);
  172. // allow a string argument to be passed in rather
  173. // than an argv array.
  174. const args = tokenizeArgString(argsInput);
  175. // tokenizeArgString adds extra quotes to args if argsInput is a string
  176. // only strip those extra quotes in processValue if argsInput is a string
  177. const inputIsString = typeof argsInput === 'string';
  178. // aliases might have transitive relationships, normalize this.
  179. const aliases = combineAliases(Object.assign(Object.create(null), opts.alias));
  180. const configuration = Object.assign({
  181. 'boolean-negation': true,
  182. 'camel-case-expansion': true,
  183. 'combine-arrays': false,
  184. 'dot-notation': true,
  185. 'duplicate-arguments-array': true,
  186. 'flatten-duplicate-arrays': true,
  187. 'greedy-arrays': true,
  188. 'halt-at-non-option': false,
  189. 'nargs-eats-options': false,
  190. 'negation-prefix': 'no-',
  191. 'parse-numbers': true,
  192. 'parse-positional-numbers': true,
  193. 'populate--': false,
  194. 'set-placeholder-key': false,
  195. 'short-option-groups': true,
  196. 'strip-aliased': false,
  197. 'strip-dashed': false,
  198. 'unknown-options-as-args': false
  199. }, opts.configuration);
  200. const defaults = Object.assign(Object.create(null), opts.default);
  201. const configObjects = opts.configObjects || [];
  202. const envPrefix = opts.envPrefix;
  203. const notFlagsOption = configuration['populate--'];
  204. const notFlagsArgv = notFlagsOption ? '--' : '_';
  205. const newAliases = Object.create(null);
  206. const defaulted = Object.create(null);
  207. // allow a i18n handler to be passed in, default to a fake one (util.format).
  208. const __ = opts.__ || mixin.format;
  209. const flags = {
  210. aliases: Object.create(null),
  211. arrays: Object.create(null),
  212. bools: Object.create(null),
  213. strings: Object.create(null),
  214. numbers: Object.create(null),
  215. counts: Object.create(null),
  216. normalize: Object.create(null),
  217. configs: Object.create(null),
  218. nargs: Object.create(null),
  219. coercions: Object.create(null),
  220. keys: []
  221. };
  222. const negative = /^-([0-9]+(\.[0-9]+)?|\.[0-9]+)$/;
  223. const negatedBoolean = new RegExp('^--' + configuration['negation-prefix'] + '(.+)');
  224. [].concat(opts.array || []).filter(Boolean).forEach(function (opt) {
  225. const key = typeof opt === 'object' ? opt.key : opt;
  226. // assign to flags[bools|strings|numbers]
  227. const assignment = Object.keys(opt).map(function (key) {
  228. const arrayFlagKeys = {
  229. boolean: 'bools',
  230. string: 'strings',
  231. number: 'numbers'
  232. };
  233. return arrayFlagKeys[key];
  234. }).filter(Boolean).pop();
  235. // assign key to be coerced
  236. if (assignment) {
  237. flags[assignment][key] = true;
  238. }
  239. flags.arrays[key] = true;
  240. flags.keys.push(key);
  241. });
  242. [].concat(opts.boolean || []).filter(Boolean).forEach(function (key) {
  243. flags.bools[key] = true;
  244. flags.keys.push(key);
  245. });
  246. [].concat(opts.string || []).filter(Boolean).forEach(function (key) {
  247. flags.strings[key] = true;
  248. flags.keys.push(key);
  249. });
  250. [].concat(opts.number || []).filter(Boolean).forEach(function (key) {
  251. flags.numbers[key] = true;
  252. flags.keys.push(key);
  253. });
  254. [].concat(opts.count || []).filter(Boolean).forEach(function (key) {
  255. flags.counts[key] = true;
  256. flags.keys.push(key);
  257. });
  258. [].concat(opts.normalize || []).filter(Boolean).forEach(function (key) {
  259. flags.normalize[key] = true;
  260. flags.keys.push(key);
  261. });
  262. if (typeof opts.narg === 'object') {
  263. Object.entries(opts.narg).forEach(([key, value]) => {
  264. if (typeof value === 'number') {
  265. flags.nargs[key] = value;
  266. flags.keys.push(key);
  267. }
  268. });
  269. }
  270. if (typeof opts.coerce === 'object') {
  271. Object.entries(opts.coerce).forEach(([key, value]) => {
  272. if (typeof value === 'function') {
  273. flags.coercions[key] = value;
  274. flags.keys.push(key);
  275. }
  276. });
  277. }
  278. if (typeof opts.config !== 'undefined') {
  279. if (Array.isArray(opts.config) || typeof opts.config === 'string') {
  280. [].concat(opts.config).filter(Boolean).forEach(function (key) {
  281. flags.configs[key] = true;
  282. });
  283. }
  284. else if (typeof opts.config === 'object') {
  285. Object.entries(opts.config).forEach(([key, value]) => {
  286. if (typeof value === 'boolean' || typeof value === 'function') {
  287. flags.configs[key] = value;
  288. }
  289. });
  290. }
  291. }
  292. // create a lookup table that takes into account all
  293. // combinations of aliases: {f: ['foo'], foo: ['f']}
  294. extendAliases(opts.key, aliases, opts.default, flags.arrays);
  295. // apply default values to all aliases.
  296. Object.keys(defaults).forEach(function (key) {
  297. (flags.aliases[key] || []).forEach(function (alias) {
  298. defaults[alias] = defaults[key];
  299. });
  300. });
  301. let error = null;
  302. checkConfiguration();
  303. let notFlags = [];
  304. const argv = Object.assign(Object.create(null), { _: [] });
  305. // TODO(bcoe): for the first pass at removing object prototype we didn't
  306. // remove all prototypes from objects returned by this API, we might want
  307. // to gradually move towards doing so.
  308. const argvReturn = {};
  309. for (let i = 0; i < args.length; i++) {
  310. const arg = args[i];
  311. const truncatedArg = arg.replace(/^-{3,}/, '---');
  312. let broken;
  313. let key;
  314. let letters;
  315. let m;
  316. let next;
  317. let value;
  318. // any unknown option (except for end-of-options, "--")
  319. if (arg !== '--' && /^-/.test(arg) && isUnknownOptionAsArg(arg)) {
  320. pushPositional(arg);
  321. // ---, ---=, ----, etc,
  322. }
  323. else if (truncatedArg.match(/^---+(=|$)/)) {
  324. // options without key name are invalid.
  325. pushPositional(arg);
  326. continue;
  327. // -- separated by =
  328. }
  329. else if (arg.match(/^--.+=/) || (!configuration['short-option-groups'] && arg.match(/^-.+=/))) {
  330. // Using [\s\S] instead of . because js doesn't support the
  331. // 'dotall' regex modifier. See:
  332. // http://stackoverflow.com/a/1068308/13216
  333. m = arg.match(/^--?([^=]+)=([\s\S]*)$/);
  334. // arrays format = '--f=a b c'
  335. if (m !== null && Array.isArray(m) && m.length >= 3) {
  336. if (checkAllAliases(m[1], flags.arrays)) {
  337. i = eatArray(i, m[1], args, m[2]);
  338. }
  339. else if (checkAllAliases(m[1], flags.nargs) !== false) {
  340. // nargs format = '--f=monkey washing cat'
  341. i = eatNargs(i, m[1], args, m[2]);
  342. }
  343. else {
  344. setArg(m[1], m[2], true);
  345. }
  346. }
  347. }
  348. else if (arg.match(negatedBoolean) && configuration['boolean-negation']) {
  349. m = arg.match(negatedBoolean);
  350. if (m !== null && Array.isArray(m) && m.length >= 2) {
  351. key = m[1];
  352. setArg(key, checkAllAliases(key, flags.arrays) ? [false] : false);
  353. }
  354. // -- separated by space.
  355. }
  356. else if (arg.match(/^--.+/) || (!configuration['short-option-groups'] && arg.match(/^-[^-]+/))) {
  357. m = arg.match(/^--?(.+)/);
  358. if (m !== null && Array.isArray(m) && m.length >= 2) {
  359. key = m[1];
  360. if (checkAllAliases(key, flags.arrays)) {
  361. // array format = '--foo a b c'
  362. i = eatArray(i, key, args);
  363. }
  364. else if (checkAllAliases(key, flags.nargs) !== false) {
  365. // nargs format = '--foo a b c'
  366. // should be truthy even if: flags.nargs[key] === 0
  367. i = eatNargs(i, key, args);
  368. }
  369. else {
  370. next = args[i + 1];
  371. if (next !== undefined && (!next.match(/^-/) ||
  372. next.match(negative)) &&
  373. !checkAllAliases(key, flags.bools) &&
  374. !checkAllAliases(key, flags.counts)) {
  375. setArg(key, next);
  376. i++;
  377. }
  378. else if (/^(true|false)$/.test(next)) {
  379. setArg(key, next);
  380. i++;
  381. }
  382. else {
  383. setArg(key, defaultValue(key));
  384. }
  385. }
  386. }
  387. // dot-notation flag separated by '='.
  388. }
  389. else if (arg.match(/^-.\..+=/)) {
  390. m = arg.match(/^-([^=]+)=([\s\S]*)$/);
  391. if (m !== null && Array.isArray(m) && m.length >= 3) {
  392. setArg(m[1], m[2]);
  393. }
  394. // dot-notation flag separated by space.
  395. }
  396. else if (arg.match(/^-.\..+/) && !arg.match(negative)) {
  397. next = args[i + 1];
  398. m = arg.match(/^-(.\..+)/);
  399. if (m !== null && Array.isArray(m) && m.length >= 2) {
  400. key = m[1];
  401. if (next !== undefined && !next.match(/^-/) &&
  402. !checkAllAliases(key, flags.bools) &&
  403. !checkAllAliases(key, flags.counts)) {
  404. setArg(key, next);
  405. i++;
  406. }
  407. else {
  408. setArg(key, defaultValue(key));
  409. }
  410. }
  411. }
  412. else if (arg.match(/^-[^-]+/) && !arg.match(negative)) {
  413. letters = arg.slice(1, -1).split('');
  414. broken = false;
  415. for (let j = 0; j < letters.length; j++) {
  416. next = arg.slice(j + 2);
  417. if (letters[j + 1] && letters[j + 1] === '=') {
  418. value = arg.slice(j + 3);
  419. key = letters[j];
  420. if (checkAllAliases(key, flags.arrays)) {
  421. // array format = '-f=a b c'
  422. i = eatArray(i, key, args, value);
  423. }
  424. else if (checkAllAliases(key, flags.nargs) !== false) {
  425. // nargs format = '-f=monkey washing cat'
  426. i = eatNargs(i, key, args, value);
  427. }
  428. else {
  429. setArg(key, value);
  430. }
  431. broken = true;
  432. break;
  433. }
  434. if (next === '-') {
  435. setArg(letters[j], next);
  436. continue;
  437. }
  438. // current letter is an alphabetic character and next value is a number
  439. if (/[A-Za-z]/.test(letters[j]) &&
  440. /^-?\d+(\.\d*)?(e-?\d+)?$/.test(next) &&
  441. checkAllAliases(next, flags.bools) === false) {
  442. setArg(letters[j], next);
  443. broken = true;
  444. break;
  445. }
  446. if (letters[j + 1] && letters[j + 1].match(/\W/)) {
  447. setArg(letters[j], next);
  448. broken = true;
  449. break;
  450. }
  451. else {
  452. setArg(letters[j], defaultValue(letters[j]));
  453. }
  454. }
  455. key = arg.slice(-1)[0];
  456. if (!broken && key !== '-') {
  457. if (checkAllAliases(key, flags.arrays)) {
  458. // array format = '-f a b c'
  459. i = eatArray(i, key, args);
  460. }
  461. else if (checkAllAliases(key, flags.nargs) !== false) {
  462. // nargs format = '-f a b c'
  463. // should be truthy even if: flags.nargs[key] === 0
  464. i = eatNargs(i, key, args);
  465. }
  466. else {
  467. next = args[i + 1];
  468. if (next !== undefined && (!/^(-|--)[^-]/.test(next) ||
  469. next.match(negative)) &&
  470. !checkAllAliases(key, flags.bools) &&
  471. !checkAllAliases(key, flags.counts)) {
  472. setArg(key, next);
  473. i++;
  474. }
  475. else if (/^(true|false)$/.test(next)) {
  476. setArg(key, next);
  477. i++;
  478. }
  479. else {
  480. setArg(key, defaultValue(key));
  481. }
  482. }
  483. }
  484. }
  485. else if (arg.match(/^-[0-9]$/) &&
  486. arg.match(negative) &&
  487. checkAllAliases(arg.slice(1), flags.bools)) {
  488. // single-digit boolean alias, e.g: xargs -0
  489. key = arg.slice(1);
  490. setArg(key, defaultValue(key));
  491. }
  492. else if (arg === '--') {
  493. notFlags = args.slice(i + 1);
  494. break;
  495. }
  496. else if (configuration['halt-at-non-option']) {
  497. notFlags = args.slice(i);
  498. break;
  499. }
  500. else {
  501. pushPositional(arg);
  502. }
  503. }
  504. // order of precedence:
  505. // 1. command line arg
  506. // 2. value from env var
  507. // 3. value from config file
  508. // 4. value from config objects
  509. // 5. configured default value
  510. applyEnvVars(argv, true); // special case: check env vars that point to config file
  511. applyEnvVars(argv, false);
  512. setConfig(argv);
  513. setConfigObjects();
  514. applyDefaultsAndAliases(argv, flags.aliases, defaults, true);
  515. applyCoercions(argv);
  516. if (configuration['set-placeholder-key'])
  517. setPlaceholderKeys(argv);
  518. // for any counts either not in args or without an explicit default, set to 0
  519. Object.keys(flags.counts).forEach(function (key) {
  520. if (!hasKey(argv, key.split('.')))
  521. setArg(key, 0);
  522. });
  523. // '--' defaults to undefined.
  524. if (notFlagsOption && notFlags.length)
  525. argv[notFlagsArgv] = [];
  526. notFlags.forEach(function (key) {
  527. argv[notFlagsArgv].push(key);
  528. });
  529. if (configuration['camel-case-expansion'] && configuration['strip-dashed']) {
  530. Object.keys(argv).filter(key => key !== '--' && key.includes('-')).forEach(key => {
  531. delete argv[key];
  532. });
  533. }
  534. if (configuration['strip-aliased']) {
  535. [].concat(...Object.keys(aliases).map(k => aliases[k])).forEach(alias => {
  536. if (configuration['camel-case-expansion'] && alias.includes('-')) {
  537. delete argv[alias.split('.').map(prop => camelCase(prop)).join('.')];
  538. }
  539. delete argv[alias];
  540. });
  541. }
  542. // Push argument into positional array, applying numeric coercion:
  543. function pushPositional(arg) {
  544. const maybeCoercedNumber = maybeCoerceNumber('_', arg);
  545. if (typeof maybeCoercedNumber === 'string' || typeof maybeCoercedNumber === 'number') {
  546. argv._.push(maybeCoercedNumber);
  547. }
  548. }
  549. // how many arguments should we consume, based
  550. // on the nargs option?
  551. function eatNargs(i, key, args, argAfterEqualSign) {
  552. let ii;
  553. let toEat = checkAllAliases(key, flags.nargs);
  554. // NaN has a special meaning for the array type, indicating that one or
  555. // more values are expected.
  556. toEat = typeof toEat !== 'number' || isNaN(toEat) ? 1 : toEat;
  557. if (toEat === 0) {
  558. if (!isUndefined(argAfterEqualSign)) {
  559. error = Error(__('Argument unexpected for: %s', key));
  560. }
  561. setArg(key, defaultValue(key));
  562. return i;
  563. }
  564. let available = isUndefined(argAfterEqualSign) ? 0 : 1;
  565. if (configuration['nargs-eats-options']) {
  566. // classic behavior, yargs eats positional and dash arguments.
  567. if (args.length - (i + 1) + available < toEat) {
  568. error = Error(__('Not enough arguments following: %s', key));
  569. }
  570. available = toEat;
  571. }
  572. else {
  573. // nargs will not consume flag arguments, e.g., -abc, --foo,
  574. // and terminates when one is observed.
  575. for (ii = i + 1; ii < args.length; ii++) {
  576. if (!args[ii].match(/^-[^0-9]/) || args[ii].match(negative) || isUnknownOptionAsArg(args[ii]))
  577. available++;
  578. else
  579. break;
  580. }
  581. if (available < toEat)
  582. error = Error(__('Not enough arguments following: %s', key));
  583. }
  584. let consumed = Math.min(available, toEat);
  585. if (!isUndefined(argAfterEqualSign) && consumed > 0) {
  586. setArg(key, argAfterEqualSign);
  587. consumed--;
  588. }
  589. for (ii = i + 1; ii < (consumed + i + 1); ii++) {
  590. setArg(key, args[ii]);
  591. }
  592. return (i + consumed);
  593. }
  594. // if an option is an array, eat all non-hyphenated arguments
  595. // following it... YUM!
  596. // e.g., --foo apple banana cat becomes ["apple", "banana", "cat"]
  597. function eatArray(i, key, args, argAfterEqualSign) {
  598. let argsToSet = [];
  599. let next = argAfterEqualSign || args[i + 1];
  600. // If both array and nargs are configured, enforce the nargs count:
  601. const nargsCount = checkAllAliases(key, flags.nargs);
  602. if (checkAllAliases(key, flags.bools) && !(/^(true|false)$/.test(next))) {
  603. argsToSet.push(true);
  604. }
  605. else if (isUndefined(next) ||
  606. (isUndefined(argAfterEqualSign) && /^-/.test(next) && !negative.test(next) && !isUnknownOptionAsArg(next))) {
  607. // for keys without value ==> argsToSet remains an empty []
  608. // set user default value, if available
  609. if (defaults[key] !== undefined) {
  610. const defVal = defaults[key];
  611. argsToSet = Array.isArray(defVal) ? defVal : [defVal];
  612. }
  613. }
  614. else {
  615. // value in --option=value is eaten as is
  616. if (!isUndefined(argAfterEqualSign)) {
  617. argsToSet.push(processValue(key, argAfterEqualSign, true));
  618. }
  619. for (let ii = i + 1; ii < args.length; ii++) {
  620. if ((!configuration['greedy-arrays'] && argsToSet.length > 0) ||
  621. (nargsCount && typeof nargsCount === 'number' && argsToSet.length >= nargsCount))
  622. break;
  623. next = args[ii];
  624. if (/^-/.test(next) && !negative.test(next) && !isUnknownOptionAsArg(next))
  625. break;
  626. i = ii;
  627. argsToSet.push(processValue(key, next, inputIsString));
  628. }
  629. }
  630. // If both array and nargs are configured, create an error if less than
  631. // nargs positionals were found. NaN has special meaning, indicating
  632. // that at least one value is required (more are okay).
  633. if (typeof nargsCount === 'number' && ((nargsCount && argsToSet.length < nargsCount) ||
  634. (isNaN(nargsCount) && argsToSet.length === 0))) {
  635. error = Error(__('Not enough arguments following: %s', key));
  636. }
  637. setArg(key, argsToSet);
  638. return i;
  639. }
  640. function setArg(key, val, shouldStripQuotes = inputIsString) {
  641. if (/-/.test(key) && configuration['camel-case-expansion']) {
  642. const alias = key.split('.').map(function (prop) {
  643. return camelCase(prop);
  644. }).join('.');
  645. addNewAlias(key, alias);
  646. }
  647. const value = processValue(key, val, shouldStripQuotes);
  648. const splitKey = key.split('.');
  649. setKey(argv, splitKey, value);
  650. // handle populating aliases of the full key
  651. if (flags.aliases[key]) {
  652. flags.aliases[key].forEach(function (x) {
  653. const keyProperties = x.split('.');
  654. setKey(argv, keyProperties, value);
  655. });
  656. }
  657. // handle populating aliases of the first element of the dot-notation key
  658. if (splitKey.length > 1 && configuration['dot-notation']) {
  659. (flags.aliases[splitKey[0]] || []).forEach(function (x) {
  660. let keyProperties = x.split('.');
  661. // expand alias with nested objects in key
  662. const a = [].concat(splitKey);
  663. a.shift(); // nuke the old key.
  664. keyProperties = keyProperties.concat(a);
  665. // populate alias only if is not already an alias of the full key
  666. // (already populated above)
  667. if (!(flags.aliases[key] || []).includes(keyProperties.join('.'))) {
  668. setKey(argv, keyProperties, value);
  669. }
  670. });
  671. }
  672. // Set normalize getter and setter when key is in 'normalize' but isn't an array
  673. if (checkAllAliases(key, flags.normalize) && !checkAllAliases(key, flags.arrays)) {
  674. const keys = [key].concat(flags.aliases[key] || []);
  675. keys.forEach(function (key) {
  676. Object.defineProperty(argvReturn, key, {
  677. enumerable: true,
  678. get() {
  679. return val;
  680. },
  681. set(value) {
  682. val = typeof value === 'string' ? mixin.normalize(value) : value;
  683. }
  684. });
  685. });
  686. }
  687. }
  688. function addNewAlias(key, alias) {
  689. if (!(flags.aliases[key] && flags.aliases[key].length)) {
  690. flags.aliases[key] = [alias];
  691. newAliases[alias] = true;
  692. }
  693. if (!(flags.aliases[alias] && flags.aliases[alias].length)) {
  694. addNewAlias(alias, key);
  695. }
  696. }
  697. function processValue(key, val, shouldStripQuotes) {
  698. // strings may be quoted, clean this up as we assign values.
  699. if (shouldStripQuotes) {
  700. val = stripQuotes(val);
  701. }
  702. // handle parsing boolean arguments --foo=true --bar false.
  703. if (checkAllAliases(key, flags.bools) || checkAllAliases(key, flags.counts)) {
  704. if (typeof val === 'string')
  705. val = val === 'true';
  706. }
  707. let value = Array.isArray(val)
  708. ? val.map(function (v) { return maybeCoerceNumber(key, v); })
  709. : maybeCoerceNumber(key, val);
  710. // increment a count given as arg (either no value or value parsed as boolean)
  711. if (checkAllAliases(key, flags.counts) && (isUndefined(value) || typeof value === 'boolean')) {
  712. value = increment();
  713. }
  714. // Set normalized value when key is in 'normalize' and in 'arrays'
  715. if (checkAllAliases(key, flags.normalize) && checkAllAliases(key, flags.arrays)) {
  716. if (Array.isArray(val))
  717. value = val.map((val) => { return mixin.normalize(val); });
  718. else
  719. value = mixin.normalize(val);
  720. }
  721. return value;
  722. }
  723. function maybeCoerceNumber(key, value) {
  724. if (!configuration['parse-positional-numbers'] && key === '_')
  725. return value;
  726. if (!checkAllAliases(key, flags.strings) && !checkAllAliases(key, flags.bools) && !Array.isArray(value)) {
  727. const shouldCoerceNumber = looksLikeNumber(value) && configuration['parse-numbers'] && (Number.isSafeInteger(Math.floor(parseFloat(`${value}`))));
  728. if (shouldCoerceNumber || (!isUndefined(value) && checkAllAliases(key, flags.numbers))) {
  729. value = Number(value);
  730. }
  731. }
  732. return value;
  733. }
  734. // set args from config.json file, this should be
  735. // applied last so that defaults can be applied.
  736. function setConfig(argv) {
  737. const configLookup = Object.create(null);
  738. // expand defaults/aliases, in-case any happen to reference
  739. // the config.json file.
  740. applyDefaultsAndAliases(configLookup, flags.aliases, defaults);
  741. Object.keys(flags.configs).forEach(function (configKey) {
  742. const configPath = argv[configKey] || configLookup[configKey];
  743. if (configPath) {
  744. try {
  745. let config = null;
  746. const resolvedConfigPath = mixin.resolve(mixin.cwd(), configPath);
  747. const resolveConfig = flags.configs[configKey];
  748. if (typeof resolveConfig === 'function') {
  749. try {
  750. config = resolveConfig(resolvedConfigPath);
  751. }
  752. catch (e) {
  753. config = e;
  754. }
  755. if (config instanceof Error) {
  756. error = config;
  757. return;
  758. }
  759. }
  760. else {
  761. config = mixin.require(resolvedConfigPath);
  762. }
  763. setConfigObject(config);
  764. }
  765. catch (ex) {
  766. // Deno will receive a PermissionDenied error if an attempt is
  767. // made to load config without the --allow-read flag:
  768. if (ex.name === 'PermissionDenied')
  769. error = ex;
  770. else if (argv[configKey])
  771. error = Error(__('Invalid JSON config file: %s', configPath));
  772. }
  773. }
  774. });
  775. }
  776. // set args from config object.
  777. // it recursively checks nested objects.
  778. function setConfigObject(config, prev) {
  779. Object.keys(config).forEach(function (key) {
  780. const value = config[key];
  781. const fullKey = prev ? prev + '.' + key : key;
  782. // if the value is an inner object and we have dot-notation
  783. // enabled, treat inner objects in config the same as
  784. // heavily nested dot notations (foo.bar.apple).
  785. if (typeof value === 'object' && value !== null && !Array.isArray(value) && configuration['dot-notation']) {
  786. // if the value is an object but not an array, check nested object
  787. setConfigObject(value, fullKey);
  788. }
  789. else {
  790. // setting arguments via CLI takes precedence over
  791. // values within the config file.
  792. if (!hasKey(argv, fullKey.split('.')) || (checkAllAliases(fullKey, flags.arrays) && configuration['combine-arrays'])) {
  793. setArg(fullKey, value);
  794. }
  795. }
  796. });
  797. }
  798. // set all config objects passed in opts
  799. function setConfigObjects() {
  800. if (typeof configObjects !== 'undefined') {
  801. configObjects.forEach(function (configObject) {
  802. setConfigObject(configObject);
  803. });
  804. }
  805. }
  806. function applyEnvVars(argv, configOnly) {
  807. if (typeof envPrefix === 'undefined')
  808. return;
  809. const prefix = typeof envPrefix === 'string' ? envPrefix : '';
  810. const env = mixin.env();
  811. Object.keys(env).forEach(function (envVar) {
  812. if (prefix === '' || envVar.lastIndexOf(prefix, 0) === 0) {
  813. // get array of nested keys and convert them to camel case
  814. const keys = envVar.split('__').map(function (key, i) {
  815. if (i === 0) {
  816. key = key.substring(prefix.length);
  817. }
  818. return camelCase(key);
  819. });
  820. if (((configOnly && flags.configs[keys.join('.')]) || !configOnly) && !hasKey(argv, keys)) {
  821. setArg(keys.join('.'), env[envVar]);
  822. }
  823. }
  824. });
  825. }
  826. function applyCoercions(argv) {
  827. let coerce;
  828. const applied = new Set();
  829. Object.keys(argv).forEach(function (key) {
  830. if (!applied.has(key)) { // If we haven't already coerced this option via one of its aliases
  831. coerce = checkAllAliases(key, flags.coercions);
  832. if (typeof coerce === 'function') {
  833. try {
  834. const value = maybeCoerceNumber(key, coerce(argv[key]));
  835. ([].concat(flags.aliases[key] || [], key)).forEach(ali => {
  836. applied.add(ali);
  837. argv[ali] = value;
  838. });
  839. }
  840. catch (err) {
  841. error = err;
  842. }
  843. }
  844. }
  845. });
  846. }
  847. function setPlaceholderKeys(argv) {
  848. flags.keys.forEach((key) => {
  849. // don't set placeholder keys for dot notation options 'foo.bar'.
  850. if (~key.indexOf('.'))
  851. return;
  852. if (typeof argv[key] === 'undefined')
  853. argv[key] = undefined;
  854. });
  855. return argv;
  856. }
  857. function applyDefaultsAndAliases(obj, aliases, defaults, canLog = false) {
  858. Object.keys(defaults).forEach(function (key) {
  859. if (!hasKey(obj, key.split('.'))) {
  860. setKey(obj, key.split('.'), defaults[key]);
  861. if (canLog)
  862. defaulted[key] = true;
  863. (aliases[key] || []).forEach(function (x) {
  864. if (hasKey(obj, x.split('.')))
  865. return;
  866. setKey(obj, x.split('.'), defaults[key]);
  867. });
  868. }
  869. });
  870. }
  871. function hasKey(obj, keys) {
  872. let o = obj;
  873. if (!configuration['dot-notation'])
  874. keys = [keys.join('.')];
  875. keys.slice(0, -1).forEach(function (key) {
  876. o = (o[key] || {});
  877. });
  878. const key = keys[keys.length - 1];
  879. if (typeof o !== 'object')
  880. return false;
  881. else
  882. return key in o;
  883. }
  884. function setKey(obj, keys, value) {
  885. let o = obj;
  886. if (!configuration['dot-notation'])
  887. keys = [keys.join('.')];
  888. keys.slice(0, -1).forEach(function (key) {
  889. // TODO(bcoe): in the next major version of yargs, switch to
  890. // Object.create(null) for dot notation:
  891. key = sanitizeKey(key);
  892. if (typeof o === 'object' && o[key] === undefined) {
  893. o[key] = {};
  894. }
  895. if (typeof o[key] !== 'object' || Array.isArray(o[key])) {
  896. // ensure that o[key] is an array, and that the last item is an empty object.
  897. if (Array.isArray(o[key])) {
  898. o[key].push({});
  899. }
  900. else {
  901. o[key] = [o[key], {}];
  902. }
  903. // we want to update the empty object at the end of the o[key] array, so set o to that object
  904. o = o[key][o[key].length - 1];
  905. }
  906. else {
  907. o = o[key];
  908. }
  909. });
  910. // TODO(bcoe): in the next major version of yargs, switch to
  911. // Object.create(null) for dot notation:
  912. const key = sanitizeKey(keys[keys.length - 1]);
  913. const isTypeArray = checkAllAliases(keys.join('.'), flags.arrays);
  914. const isValueArray = Array.isArray(value);
  915. let duplicate = configuration['duplicate-arguments-array'];
  916. // nargs has higher priority than duplicate
  917. if (!duplicate && checkAllAliases(key, flags.nargs)) {
  918. duplicate = true;
  919. if ((!isUndefined(o[key]) && flags.nargs[key] === 1) || (Array.isArray(o[key]) && o[key].length === flags.nargs[key])) {
  920. o[key] = undefined;
  921. }
  922. }
  923. if (value === increment()) {
  924. o[key] = increment(o[key]);
  925. }
  926. else if (Array.isArray(o[key])) {
  927. if (duplicate && isTypeArray && isValueArray) {
  928. o[key] = configuration['flatten-duplicate-arrays'] ? o[key].concat(value) : (Array.isArray(o[key][0]) ? o[key] : [o[key]]).concat([value]);
  929. }
  930. else if (!duplicate && Boolean(isTypeArray) === Boolean(isValueArray)) {
  931. o[key] = value;
  932. }
  933. else {
  934. o[key] = o[key].concat([value]);
  935. }
  936. }
  937. else if (o[key] === undefined && isTypeArray) {
  938. o[key] = isValueArray ? value : [value];
  939. }
  940. else if (duplicate && !(o[key] === undefined ||
  941. checkAllAliases(key, flags.counts) ||
  942. checkAllAliases(key, flags.bools))) {
  943. o[key] = [o[key], value];
  944. }
  945. else {
  946. o[key] = value;
  947. }
  948. }
  949. // extend the aliases list with inferred aliases.
  950. function extendAliases(...args) {
  951. args.forEach(function (obj) {
  952. Object.keys(obj || {}).forEach(function (key) {
  953. // short-circuit if we've already added a key
  954. // to the aliases array, for example it might
  955. // exist in both 'opts.default' and 'opts.key'.
  956. if (flags.aliases[key])
  957. return;
  958. flags.aliases[key] = [].concat(aliases[key] || []);
  959. // For "--option-name", also set argv.optionName
  960. flags.aliases[key].concat(key).forEach(function (x) {
  961. if (/-/.test(x) && configuration['camel-case-expansion']) {
  962. const c = camelCase(x);
  963. if (c !== key && flags.aliases[key].indexOf(c) === -1) {
  964. flags.aliases[key].push(c);
  965. newAliases[c] = true;
  966. }
  967. }
  968. });
  969. // For "--optionName", also set argv['option-name']
  970. flags.aliases[key].concat(key).forEach(function (x) {
  971. if (x.length > 1 && /[A-Z]/.test(x) && configuration['camel-case-expansion']) {
  972. const c = decamelize(x, '-');
  973. if (c !== key && flags.aliases[key].indexOf(c) === -1) {
  974. flags.aliases[key].push(c);
  975. newAliases[c] = true;
  976. }
  977. }
  978. });
  979. flags.aliases[key].forEach(function (x) {
  980. flags.aliases[x] = [key].concat(flags.aliases[key].filter(function (y) {
  981. return x !== y;
  982. }));
  983. });
  984. });
  985. });
  986. }
  987. function checkAllAliases(key, flag) {
  988. const toCheck = [].concat(flags.aliases[key] || [], key);
  989. const keys = Object.keys(flag);
  990. const setAlias = toCheck.find(key => keys.includes(key));
  991. return setAlias ? flag[setAlias] : false;
  992. }
  993. function hasAnyFlag(key) {
  994. const flagsKeys = Object.keys(flags);
  995. const toCheck = [].concat(flagsKeys.map(k => flags[k]));
  996. return toCheck.some(function (flag) {
  997. return Array.isArray(flag) ? flag.includes(key) : flag[key];
  998. });
  999. }
  1000. function hasFlagsMatching(arg, ...patterns) {
  1001. const toCheck = [].concat(...patterns);
  1002. return toCheck.some(function (pattern) {
  1003. const match = arg.match(pattern);
  1004. return match && hasAnyFlag(match[1]);
  1005. });
  1006. }
  1007. // based on a simplified version of the short flag group parsing logic
  1008. function hasAllShortFlags(arg) {
  1009. // if this is a negative number, or doesn't start with a single hyphen, it's not a short flag group
  1010. if (arg.match(negative) || !arg.match(/^-[^-]+/)) {
  1011. return false;
  1012. }
  1013. let hasAllFlags = true;
  1014. let next;
  1015. const letters = arg.slice(1).split('');
  1016. for (let j = 0; j < letters.length; j++) {
  1017. next = arg.slice(j + 2);
  1018. if (!hasAnyFlag(letters[j])) {
  1019. hasAllFlags = false;
  1020. break;
  1021. }
  1022. if ((letters[j + 1] && letters[j + 1] === '=') ||
  1023. next === '-' ||
  1024. (/[A-Za-z]/.test(letters[j]) && /^-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) ||
  1025. (letters[j + 1] && letters[j + 1].match(/\W/))) {
  1026. break;
  1027. }
  1028. }
  1029. return hasAllFlags;
  1030. }
  1031. function isUnknownOptionAsArg(arg) {
  1032. return configuration['unknown-options-as-args'] && isUnknownOption(arg);
  1033. }
  1034. function isUnknownOption(arg) {
  1035. arg = arg.replace(/^-{3,}/, '--');
  1036. // ignore negative numbers
  1037. if (arg.match(negative)) {
  1038. return false;
  1039. }
  1040. // if this is a short option group and all of them are configured, it isn't unknown
  1041. if (hasAllShortFlags(arg)) {
  1042. return false;
  1043. }
  1044. // e.g. '--count=2'
  1045. const flagWithEquals = /^-+([^=]+?)=[\s\S]*$/;
  1046. // e.g. '-a' or '--arg'
  1047. const normalFlag = /^-+([^=]+?)$/;
  1048. // e.g. '-a-'
  1049. const flagEndingInHyphen = /^-+([^=]+?)-$/;
  1050. // e.g. '-abc123'
  1051. const flagEndingInDigits = /^-+([^=]+?\d+)$/;
  1052. // e.g. '-a/usr/local'
  1053. const flagEndingInNonWordCharacters = /^-+([^=]+?)\W+.*$/;
  1054. // check the different types of flag styles, including negatedBoolean, a pattern defined near the start of the parse method
  1055. return !hasFlagsMatching(arg, flagWithEquals, negatedBoolean, normalFlag, flagEndingInHyphen, flagEndingInDigits, flagEndingInNonWordCharacters);
  1056. }
  1057. // make a best effort to pick a default value
  1058. // for an option based on name and type.
  1059. function defaultValue(key) {
  1060. if (!checkAllAliases(key, flags.bools) &&
  1061. !checkAllAliases(key, flags.counts) &&
  1062. `${key}` in defaults) {
  1063. return defaults[key];
  1064. }
  1065. else {
  1066. return defaultForType(guessType(key));
  1067. }
  1068. }
  1069. // return a default value, given the type of a flag.,
  1070. function defaultForType(type) {
  1071. const def = {
  1072. [DefaultValuesForTypeKey.BOOLEAN]: true,
  1073. [DefaultValuesForTypeKey.STRING]: '',
  1074. [DefaultValuesForTypeKey.NUMBER]: undefined,
  1075. [DefaultValuesForTypeKey.ARRAY]: []
  1076. };
  1077. return def[type];
  1078. }
  1079. // given a flag, enforce a default type.
  1080. function guessType(key) {
  1081. let type = DefaultValuesForTypeKey.BOOLEAN;
  1082. if (checkAllAliases(key, flags.strings))
  1083. type = DefaultValuesForTypeKey.STRING;
  1084. else if (checkAllAliases(key, flags.numbers))
  1085. type = DefaultValuesForTypeKey.NUMBER;
  1086. else if (checkAllAliases(key, flags.bools))
  1087. type = DefaultValuesForTypeKey.BOOLEAN;
  1088. else if (checkAllAliases(key, flags.arrays))
  1089. type = DefaultValuesForTypeKey.ARRAY;
  1090. return type;
  1091. }
  1092. function isUndefined(num) {
  1093. return num === undefined;
  1094. }
  1095. // check user configuration settings for inconsistencies
  1096. function checkConfiguration() {
  1097. // count keys should not be set as array/narg
  1098. Object.keys(flags.counts).find(key => {
  1099. if (checkAllAliases(key, flags.arrays)) {
  1100. error = Error(__('Invalid configuration: %s, opts.count excludes opts.array.', key));
  1101. return true;
  1102. }
  1103. else if (checkAllAliases(key, flags.nargs)) {
  1104. error = Error(__('Invalid configuration: %s, opts.count excludes opts.narg.', key));
  1105. return true;
  1106. }
  1107. return false;
  1108. });
  1109. }
  1110. return {
  1111. aliases: Object.assign({}, flags.aliases),
  1112. argv: Object.assign(argvReturn, argv),
  1113. configuration: configuration,
  1114. defaulted: Object.assign({}, defaulted),
  1115. error: error,
  1116. newAliases: Object.assign({}, newAliases)
  1117. };
  1118. }
  1119. }
  1120. // if any aliases reference each other, we should
  1121. // merge them together.
  1122. function combineAliases(aliases) {
  1123. const aliasArrays = [];
  1124. const combined = Object.create(null);
  1125. let change = true;
  1126. // turn alias lookup hash {key: ['alias1', 'alias2']} into
  1127. // a simple array ['key', 'alias1', 'alias2']
  1128. Object.keys(aliases).forEach(function (key) {
  1129. aliasArrays.push([].concat(aliases[key], key));
  1130. });
  1131. // combine arrays until zero changes are
  1132. // made in an iteration.
  1133. while (change) {
  1134. change = false;
  1135. for (let i = 0; i < aliasArrays.length; i++) {
  1136. for (let ii = i + 1; ii < aliasArrays.length; ii++) {
  1137. const intersect = aliasArrays[i].filter(function (v) {
  1138. return aliasArrays[ii].indexOf(v) !== -1;
  1139. });
  1140. if (intersect.length) {
  1141. aliasArrays[i] = aliasArrays[i].concat(aliasArrays[ii]);
  1142. aliasArrays.splice(ii, 1);
  1143. change = true;
  1144. break;
  1145. }
  1146. }
  1147. }
  1148. }
  1149. // map arrays back to the hash-lookup (de-dupe while
  1150. // we're at it).
  1151. aliasArrays.forEach(function (aliasArray) {
  1152. aliasArray = aliasArray.filter(function (v, i, self) {
  1153. return self.indexOf(v) === i;
  1154. });
  1155. const lastAlias = aliasArray.pop();
  1156. if (lastAlias !== undefined && typeof lastAlias === 'string') {
  1157. combined[lastAlias] = aliasArray;
  1158. }
  1159. });
  1160. return combined;
  1161. }
  1162. // this function should only be called when a count is given as an arg
  1163. // it is NOT called to set a default value
  1164. // thus we can start the count at 1 instead of 0
  1165. function increment(orig) {
  1166. return orig !== undefined ? orig + 1 : 1;
  1167. }
  1168. // TODO(bcoe): in the next major version of yargs, switch to
  1169. // Object.create(null) for dot notation:
  1170. function sanitizeKey(key) {
  1171. if (key === '__proto__')
  1172. return '___proto___';
  1173. return key;
  1174. }
  1175. function stripQuotes(val) {
  1176. return (typeof val === 'string' &&
  1177. (val[0] === "'" || val[0] === '"') &&
  1178. val[val.length - 1] === val[0])
  1179. ? val.substring(1, val.length - 1)
  1180. : val;
  1181. }
  1182. /**
  1183. * @fileoverview Main entrypoint for libraries using yargs-parser in Node.js
  1184. * CJS and ESM environments.
  1185. *
  1186. * @license
  1187. * Copyright (c) 2016, Contributors
  1188. * SPDX-License-Identifier: ISC
  1189. */
  1190. var _a, _b, _c;
  1191. // See https://github.com/yargs/yargs-parser#supported-nodejs-versions for our
  1192. // version support policy. The YARGS_MIN_NODE_VERSION is used for testing only.
  1193. const minNodeVersion = (process && process.env && process.env.YARGS_MIN_NODE_VERSION)
  1194. ? Number(process.env.YARGS_MIN_NODE_VERSION)
  1195. : 12;
  1196. 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);
  1197. if (nodeVersion) {
  1198. const major = Number(nodeVersion.match(/^([^.]+)/)[1]);
  1199. if (major < minNodeVersion) {
  1200. 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`);
  1201. }
  1202. }
  1203. // Creates a yargs-parser instance using Node.js standard libraries:
  1204. const env = process ? process.env : {};
  1205. const parser = new YargsParser({
  1206. cwd: process.cwd,
  1207. env: () => {
  1208. return env;
  1209. },
  1210. format: require$$2.format,
  1211. normalize: require$$0.normalize,
  1212. resolve: require$$0.resolve,
  1213. // TODO: figure out a way to combine ESM and CJS coverage, such that
  1214. // we can exercise all the lines below:
  1215. require: (path) => {
  1216. if (typeof require !== 'undefined') {
  1217. return require(path);
  1218. }
  1219. else if (path.match(/\.json$/)) {
  1220. // Addresses: https://github.com/yargs/yargs/issues/2040
  1221. return JSON.parse(require$$0$1.readFileSync(path, 'utf8'));
  1222. }
  1223. else {
  1224. throw Error('only .json config files are supported in ESM');
  1225. }
  1226. }
  1227. });
  1228. const yargsParser = function Parser(args, opts) {
  1229. const result = parser.parse(args.slice(), opts);
  1230. return result.argv;
  1231. };
  1232. yargsParser.detailed = function (args, opts) {
  1233. return parser.parse(args.slice(), opts);
  1234. };
  1235. yargsParser.camelCase = camelCase;
  1236. yargsParser.decamelize = decamelize;
  1237. yargsParser.looksLikeNumber = looksLikeNumber;
  1238. /******************************************************************************
  1239. Copyright (c) Microsoft Corporation.
  1240. Permission to use, copy, modify, and/or distribute this software for any
  1241. purpose with or without fee is hereby granted.
  1242. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  1243. REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  1244. AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  1245. INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  1246. LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
  1247. OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  1248. PERFORMANCE OF THIS SOFTWARE.
  1249. ***************************************************************************** */
  1250. /* global Reflect, Promise, SuppressedError, Symbol, Iterator */
  1251. function __addDisposableResource(env, value, async) {
  1252. if (value !== null && value !== void 0) {
  1253. if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
  1254. var dispose, inner;
  1255. if (async) {
  1256. if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
  1257. dispose = value[Symbol.asyncDispose];
  1258. }
  1259. if (dispose === void 0) {
  1260. if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
  1261. dispose = value[Symbol.dispose];
  1262. if (async) inner = dispose;
  1263. }
  1264. if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
  1265. if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };
  1266. env.stack.push({ value: value, dispose: dispose, async: async });
  1267. }
  1268. else if (async) {
  1269. env.stack.push({ async: true });
  1270. }
  1271. return value;
  1272. }
  1273. var _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
  1274. var e = new Error(message);
  1275. return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
  1276. };
  1277. function __disposeResources(env) {
  1278. function fail(e) {
  1279. env.error = env.hasError ? new _SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
  1280. env.hasError = true;
  1281. }
  1282. var r, s = 0;
  1283. function next() {
  1284. while (r = env.stack.pop()) {
  1285. try {
  1286. if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
  1287. if (r.dispose) {
  1288. var result = r.dispose.call(r.value);
  1289. if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });
  1290. }
  1291. else s |= 1;
  1292. }
  1293. catch (e) {
  1294. fail(e);
  1295. }
  1296. }
  1297. if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
  1298. if (env.hasError) throw env.error;
  1299. }
  1300. return next();
  1301. }
  1302. const toZeroIfInfinity = value => Number.isFinite(value) ? value : 0;
  1303. function parseNumber(milliseconds) {
  1304. return {
  1305. days: Math.trunc(milliseconds / 86_400_000),
  1306. hours: Math.trunc(milliseconds / 3_600_000 % 24),
  1307. minutes: Math.trunc(milliseconds / 60_000 % 60),
  1308. seconds: Math.trunc(milliseconds / 1000 % 60),
  1309. milliseconds: Math.trunc(milliseconds % 1000),
  1310. microseconds: Math.trunc(toZeroIfInfinity(milliseconds * 1000) % 1000),
  1311. nanoseconds: Math.trunc(toZeroIfInfinity(milliseconds * 1e6) % 1000),
  1312. };
  1313. }
  1314. function parseBigint(milliseconds) {
  1315. return {
  1316. days: milliseconds / 86_400_000n,
  1317. hours: milliseconds / 3_600_000n % 24n,
  1318. minutes: milliseconds / 60_000n % 60n,
  1319. seconds: milliseconds / 1000n % 60n,
  1320. milliseconds: milliseconds % 1000n,
  1321. microseconds: 0n,
  1322. nanoseconds: 0n,
  1323. };
  1324. }
  1325. function parseMilliseconds(milliseconds) {
  1326. switch (typeof milliseconds) {
  1327. case 'number': {
  1328. if (Number.isFinite(milliseconds)) {
  1329. return parseNumber(milliseconds);
  1330. }
  1331. break;
  1332. }
  1333. case 'bigint': {
  1334. return parseBigint(milliseconds);
  1335. }
  1336. // No default
  1337. }
  1338. throw new TypeError('Expected a finite number or bigint');
  1339. }
  1340. const isZero = value => value === 0 || value === 0n;
  1341. const pluralize = (word, count) => (count === 1 || count === 1n) ? word : `${word}s`;
  1342. const SECOND_ROUNDING_EPSILON = 0.000_000_1;
  1343. const ONE_DAY_IN_MILLISECONDS = 24n * 60n * 60n * 1000n;
  1344. function prettyMilliseconds(milliseconds, options) {
  1345. const isBigInt = typeof milliseconds === 'bigint';
  1346. if (!isBigInt && !Number.isFinite(milliseconds)) {
  1347. throw new TypeError('Expected a finite number or bigint');
  1348. }
  1349. options = {...options};
  1350. const sign = milliseconds < 0 ? '-' : '';
  1351. milliseconds = milliseconds < 0 ? -milliseconds : milliseconds; // Cannot use `Math.abs()` because of BigInt support.
  1352. if (options.colonNotation) {
  1353. options.compact = false;
  1354. options.formatSubMilliseconds = false;
  1355. options.separateMilliseconds = false;
  1356. options.verbose = false;
  1357. }
  1358. if (options.compact) {
  1359. options.unitCount = 1;
  1360. options.secondsDecimalDigits = 0;
  1361. options.millisecondsDecimalDigits = 0;
  1362. }
  1363. let result = [];
  1364. const floorDecimals = (value, decimalDigits) => {
  1365. const flooredInterimValue = Math.floor((value * (10 ** decimalDigits)) + SECOND_ROUNDING_EPSILON);
  1366. const flooredValue = Math.round(flooredInterimValue) / (10 ** decimalDigits);
  1367. return flooredValue.toFixed(decimalDigits);
  1368. };
  1369. const add = (value, long, short, valueString) => {
  1370. if (
  1371. (result.length === 0 || !options.colonNotation)
  1372. && isZero(value)
  1373. && !(options.colonNotation && short === 'm')) {
  1374. return;
  1375. }
  1376. valueString ??= String(value);
  1377. if (options.colonNotation) {
  1378. const wholeDigits = valueString.includes('.') ? valueString.split('.')[0].length : valueString.length;
  1379. const minLength = result.length > 0 ? 2 : 1;
  1380. valueString = '0'.repeat(Math.max(0, minLength - wholeDigits)) + valueString;
  1381. } else {
  1382. valueString += options.verbose ? ' ' + pluralize(long, value) : short;
  1383. }
  1384. result.push(valueString);
  1385. };
  1386. const parsed = parseMilliseconds(milliseconds);
  1387. const days = BigInt(parsed.days);
  1388. if (options.hideYearAndDays) {
  1389. add((BigInt(days) * 24n) + BigInt(parsed.hours), 'hour', 'h');
  1390. } else {
  1391. if (options.hideYear) {
  1392. add(days, 'day', 'd');
  1393. } else {
  1394. add(days / 365n, 'year', 'y');
  1395. add(days % 365n, 'day', 'd');
  1396. }
  1397. add(Number(parsed.hours), 'hour', 'h');
  1398. }
  1399. add(Number(parsed.minutes), 'minute', 'm');
  1400. if (!options.hideSeconds) {
  1401. if (
  1402. options.separateMilliseconds
  1403. || options.formatSubMilliseconds
  1404. || (!options.colonNotation && milliseconds < 1000)
  1405. ) {
  1406. const seconds = Number(parsed.seconds);
  1407. const milliseconds = Number(parsed.milliseconds);
  1408. const microseconds = Number(parsed.microseconds);
  1409. const nanoseconds = Number(parsed.nanoseconds);
  1410. add(seconds, 'second', 's');
  1411. if (options.formatSubMilliseconds) {
  1412. add(milliseconds, 'millisecond', 'ms');
  1413. add(microseconds, 'microsecond', 'µs');
  1414. add(nanoseconds, 'nanosecond', 'ns');
  1415. } else {
  1416. const millisecondsAndBelow
  1417. = milliseconds
  1418. + (microseconds / 1000)
  1419. + (nanoseconds / 1e6);
  1420. const millisecondsDecimalDigits
  1421. = typeof options.millisecondsDecimalDigits === 'number'
  1422. ? options.millisecondsDecimalDigits
  1423. : 0;
  1424. const roundedMilliseconds = millisecondsAndBelow >= 1
  1425. ? Math.round(millisecondsAndBelow)
  1426. : Math.ceil(millisecondsAndBelow);
  1427. const millisecondsString = millisecondsDecimalDigits
  1428. ? millisecondsAndBelow.toFixed(millisecondsDecimalDigits)
  1429. : roundedMilliseconds;
  1430. add(
  1431. Number.parseFloat(millisecondsString),
  1432. 'millisecond',
  1433. 'ms',
  1434. millisecondsString,
  1435. );
  1436. }
  1437. } else {
  1438. const seconds = (
  1439. (isBigInt ? Number(milliseconds % ONE_DAY_IN_MILLISECONDS) : milliseconds)
  1440. / 1000
  1441. ) % 60;
  1442. const secondsDecimalDigits
  1443. = typeof options.secondsDecimalDigits === 'number'
  1444. ? options.secondsDecimalDigits
  1445. : 1;
  1446. const secondsFixed = floorDecimals(seconds, secondsDecimalDigits);
  1447. const secondsString = options.keepDecimalsOnWholeSeconds
  1448. ? secondsFixed
  1449. : secondsFixed.replace(/\.0+$/, '');
  1450. add(Number.parseFloat(secondsString), 'second', 's', secondsString);
  1451. }
  1452. }
  1453. if (result.length === 0) {
  1454. return sign + '0' + (options.verbose ? ' milliseconds' : 'ms');
  1455. }
  1456. const separator = options.colonNotation ? ':' : ' ';
  1457. if (typeof options.unitCount === 'number') {
  1458. result = result.slice(0, Math.max(options.unitCount, 1));
  1459. }
  1460. return sign + result.join(separator);
  1461. }
  1462. const BYTE_UNITS = [
  1463. 'B',
  1464. 'kB',
  1465. 'MB',
  1466. 'GB',
  1467. 'TB',
  1468. 'PB',
  1469. 'EB',
  1470. 'ZB',
  1471. 'YB',
  1472. ];
  1473. const BIBYTE_UNITS = [
  1474. 'B',
  1475. 'KiB',
  1476. 'MiB',
  1477. 'GiB',
  1478. 'TiB',
  1479. 'PiB',
  1480. 'EiB',
  1481. 'ZiB',
  1482. 'YiB',
  1483. ];
  1484. const BIT_UNITS = [
  1485. 'b',
  1486. 'kbit',
  1487. 'Mbit',
  1488. 'Gbit',
  1489. 'Tbit',
  1490. 'Pbit',
  1491. 'Ebit',
  1492. 'Zbit',
  1493. 'Ybit',
  1494. ];
  1495. const BIBIT_UNITS = [
  1496. 'b',
  1497. 'kibit',
  1498. 'Mibit',
  1499. 'Gibit',
  1500. 'Tibit',
  1501. 'Pibit',
  1502. 'Eibit',
  1503. 'Zibit',
  1504. 'Yibit',
  1505. ];
  1506. /*
  1507. Formats the given number using `Number#toLocaleString`.
  1508. - If locale is a string, the value is expected to be a locale-key (for example: `de`).
  1509. - If locale is true, the system default locale is used for translation.
  1510. - If no value for locale is specified, the number is returned unmodified.
  1511. */
  1512. const toLocaleString = (number, locale, options) => {
  1513. let result = number;
  1514. if (typeof locale === 'string' || Array.isArray(locale)) {
  1515. result = number.toLocaleString(locale, options);
  1516. } else if (locale === true || options !== undefined) {
  1517. result = number.toLocaleString(undefined, options);
  1518. }
  1519. return result;
  1520. };
  1521. const log10 = numberOrBigInt => {
  1522. if (typeof numberOrBigInt === 'number') {
  1523. return Math.log10(numberOrBigInt);
  1524. }
  1525. const string = numberOrBigInt.toString(10);
  1526. return string.length + Math.log10('0.' + string.slice(0, 15));
  1527. };
  1528. const log = numberOrBigInt => {
  1529. if (typeof numberOrBigInt === 'number') {
  1530. return Math.log(numberOrBigInt);
  1531. }
  1532. return log10(numberOrBigInt) * Math.log(10);
  1533. };
  1534. const divide = (numberOrBigInt, divisor) => {
  1535. if (typeof numberOrBigInt === 'number') {
  1536. return numberOrBigInt / divisor;
  1537. }
  1538. const integerPart = numberOrBigInt / BigInt(divisor);
  1539. const remainder = numberOrBigInt % BigInt(divisor);
  1540. return Number(integerPart) + (Number(remainder) / divisor);
  1541. };
  1542. function prettyBytes(number, options) {
  1543. if (typeof number !== 'bigint' && !Number.isFinite(number)) {
  1544. throw new TypeError(`Expected a finite number, got ${typeof number}: ${number}`);
  1545. }
  1546. options = {
  1547. bits: false,
  1548. binary: false,
  1549. space: true,
  1550. ...options,
  1551. };
  1552. const UNITS = options.bits
  1553. ? (options.binary ? BIBIT_UNITS : BIT_UNITS)
  1554. : (options.binary ? BIBYTE_UNITS : BYTE_UNITS);
  1555. const separator = options.space ? ' ' : '';
  1556. if (options.signed && (typeof number === 'number' ? number === 0 : number === 0n)) {
  1557. return ` 0${separator}${UNITS[0]}`;
  1558. }
  1559. const isNegative = number < 0;
  1560. const prefix = isNegative ? '-' : (options.signed ? '+' : '');
  1561. if (isNegative) {
  1562. number = -number;
  1563. }
  1564. let localeOptions;
  1565. if (options.minimumFractionDigits !== undefined) {
  1566. localeOptions = {minimumFractionDigits: options.minimumFractionDigits};
  1567. }
  1568. if (options.maximumFractionDigits !== undefined) {
  1569. localeOptions = {maximumFractionDigits: options.maximumFractionDigits, ...localeOptions};
  1570. }
  1571. if (number < 1) {
  1572. const numberString = toLocaleString(number, options.locale, localeOptions);
  1573. return prefix + numberString + separator + UNITS[0];
  1574. }
  1575. const exponent = Math.min(Math.floor(options.binary ? log(number) / Math.log(1024) : log10(number) / 3), UNITS.length - 1);
  1576. number = divide(number, (options.binary ? 1024 : 1000) ** exponent);
  1577. if (!localeOptions) {
  1578. number = number.toPrecision(3);
  1579. }
  1580. const numberString = toLocaleString(Number(number), options.locale, localeOptions);
  1581. const unit = UNITS[exponent];
  1582. return prefix + numberString + separator + unit;
  1583. }
  1584. function printTimings(timings) {
  1585. for (const [label, [time, memory, total]] of Object.entries(timings)) {
  1586. const appliedColor = label[0] === '#' ? (label[1] === '#' ? rollup.bold : rollup.underline) : (text) => text;
  1587. const row = `${label}: ${time.toFixed(0)}ms, ${prettyBytes(memory)} / ${prettyBytes(total)}`;
  1588. console.info(appliedColor(row));
  1589. }
  1590. }
  1591. async function build(inputOptions, warnings, silent = false) {
  1592. const env_1 = { stack: [], error: void 0, hasError: false };
  1593. try {
  1594. const outputOptions = inputOptions.output;
  1595. const useStdout = !outputOptions[0].file && !outputOptions[0].dir;
  1596. const start = Date.now();
  1597. const files = useStdout ? ['stdout'] : outputOptions.map(t => parseAst_js.relativeId(t.file || t.dir));
  1598. if (!silent) {
  1599. let inputFiles;
  1600. if (typeof inputOptions.input === 'string') {
  1601. inputFiles = inputOptions.input;
  1602. }
  1603. else if (Array.isArray(inputOptions.input)) {
  1604. inputFiles = inputOptions.input.join(', ');
  1605. }
  1606. else if (typeof inputOptions.input === 'object' && inputOptions.input !== null) {
  1607. inputFiles = Object.values(inputOptions.input).join(', ');
  1608. }
  1609. rollup.stderr(rollup.cyan(`\n${rollup.bold(inputFiles)} → ${rollup.bold(files.join(', '))}...`));
  1610. }
  1611. const bundle = __addDisposableResource(env_1, await rollup.rollup(inputOptions), true);
  1612. if (useStdout) {
  1613. const output = outputOptions[0];
  1614. if (output.sourcemap && output.sourcemap !== 'inline') {
  1615. rollup.handleError(parseAst_js.logOnlyInlineSourcemapsForStdout());
  1616. }
  1617. const { output: outputs } = await bundle.generate(output);
  1618. for (const file of outputs) {
  1619. if (outputs.length > 1)
  1620. process$1.stdout.write(`\n${rollup.cyan(rollup.bold(`//→ ${file.fileName}:`))}\n`);
  1621. process$1.stdout.write(file.type === 'asset' ? file.source : file.code);
  1622. }
  1623. if (!silent) {
  1624. warnings.flush();
  1625. }
  1626. return;
  1627. }
  1628. await Promise.all(outputOptions.map(bundle.write));
  1629. if (!silent) {
  1630. warnings.flush();
  1631. rollup.stderr(rollup.green(`created ${rollup.bold(files.join(', '))} in ${rollup.bold(prettyMilliseconds(Date.now() - start))}`));
  1632. if (bundle && bundle.getTimings) {
  1633. printTimings(bundle.getTimings());
  1634. }
  1635. }
  1636. }
  1637. catch (e_1) {
  1638. env_1.error = e_1;
  1639. env_1.hasError = true;
  1640. }
  1641. finally {
  1642. const result_1 = __disposeResources(env_1);
  1643. if (result_1)
  1644. await result_1;
  1645. }
  1646. }
  1647. const DEFAULT_CONFIG_BASE = 'rollup.config';
  1648. async function getConfigPath(commandConfig) {
  1649. if (commandConfig === true) {
  1650. return path.resolve(await findConfigFileNameInCwd());
  1651. }
  1652. if (commandConfig.slice(0, 5) === 'node:') {
  1653. const packageName = commandConfig.slice(5);
  1654. try {
  1655. return require.resolve(`rollup-config-${packageName}`, { paths: [process$1.cwd()] });
  1656. }
  1657. catch {
  1658. try {
  1659. return require.resolve(packageName, { paths: [process$1.cwd()] });
  1660. }
  1661. catch (error) {
  1662. if (error.code === 'MODULE_NOT_FOUND') {
  1663. rollup.handleError(parseAst_js.logMissingExternalConfig(commandConfig));
  1664. }
  1665. throw error;
  1666. }
  1667. }
  1668. }
  1669. return path.resolve(commandConfig);
  1670. }
  1671. async function findConfigFileNameInCwd() {
  1672. const filesInWorkingDirectory = new Set(await promises.readdir(process$1.cwd()));
  1673. for (const extension of ['mjs', 'cjs', 'ts']) {
  1674. const fileName = `${DEFAULT_CONFIG_BASE}.${extension}`;
  1675. if (filesInWorkingDirectory.has(fileName))
  1676. return fileName;
  1677. }
  1678. return `${DEFAULT_CONFIG_BASE}.js`;
  1679. }
  1680. async function loadConfigFromCommand(commandOptions, watchMode) {
  1681. const warnings = loadConfigFile_js.batchWarnings(commandOptions);
  1682. if (!commandOptions.input && (commandOptions.stdin || !process$1.stdin.isTTY)) {
  1683. commandOptions.input = loadConfigFile_js.stdinName;
  1684. }
  1685. const options = await rollup.mergeOptions({ input: [] }, watchMode, commandOptions, warnings.log);
  1686. await loadConfigFile_js.addCommandPluginsToInputOptions(options, commandOptions);
  1687. return { options: [options], warnings };
  1688. }
  1689. async function runRollup(command) {
  1690. let inputSource;
  1691. if (command._.length > 0) {
  1692. if (command.input) {
  1693. rollup.handleError(parseAst_js.logDuplicateImportOptions());
  1694. }
  1695. inputSource = command._;
  1696. }
  1697. else if (typeof command.input === 'string') {
  1698. inputSource = [command.input];
  1699. }
  1700. else {
  1701. inputSource = command.input;
  1702. }
  1703. if (inputSource && inputSource.length > 0) {
  1704. if (inputSource.some((input) => input.includes('='))) {
  1705. command.input = {};
  1706. for (const input of inputSource) {
  1707. const equalsIndex = input.indexOf('=');
  1708. const value = input.slice(Math.max(0, equalsIndex + 1));
  1709. const key = input.slice(0, Math.max(0, equalsIndex)) || parseAst_js.getAliasName(input);
  1710. command.input[key] = value;
  1711. }
  1712. }
  1713. else {
  1714. command.input = inputSource;
  1715. }
  1716. }
  1717. if (command.environment) {
  1718. const environment = Array.isArray(command.environment)
  1719. ? command.environment
  1720. : [command.environment];
  1721. for (const argument of environment) {
  1722. for (const pair of argument.split(',')) {
  1723. const [key, ...value] = pair.split(':');
  1724. process$1.env[key] = value.length === 0 ? String(true) : value.join(':');
  1725. }
  1726. }
  1727. }
  1728. if (rollup.isWatchEnabled(command.watch)) {
  1729. await fseventsImporter.loadFsEvents();
  1730. const { watch } = await Promise.resolve().then(() => require('../shared/watch-cli.js'));
  1731. await watch(command);
  1732. }
  1733. else {
  1734. try {
  1735. const { options, warnings } = await getConfigs(command);
  1736. try {
  1737. for (const inputOptions of options) {
  1738. if (!inputOptions.cache) {
  1739. // We explicitly disable the cache when unused as the CLI will not
  1740. // use the cache object on the bundle when not in watch mode. This
  1741. // improves performance as the cache is not generated.
  1742. inputOptions.cache = false;
  1743. }
  1744. await build(inputOptions, warnings, command.silent);
  1745. }
  1746. if (command.failAfterWarnings && warnings.warningOccurred) {
  1747. warnings.flush();
  1748. rollup.handleError(parseAst_js.logFailAfterWarnings());
  1749. }
  1750. }
  1751. catch (error) {
  1752. warnings.flush();
  1753. rollup.handleError(error);
  1754. }
  1755. }
  1756. catch (error) {
  1757. rollup.handleError(error);
  1758. }
  1759. }
  1760. }
  1761. async function getConfigs(command) {
  1762. if (command.config) {
  1763. const configFile = await getConfigPath(command.config);
  1764. const { options, warnings } = await loadConfigFile_js.loadConfigFile(configFile, command, false);
  1765. return { options, warnings };
  1766. }
  1767. return await loadConfigFromCommand(command, false);
  1768. }
  1769. const command = yargsParser(process$1.argv.slice(2), {
  1770. alias: rollup.commandAliases,
  1771. configuration: { 'camel-case-expansion': false }
  1772. });
  1773. if (command.help || (process$1.argv.length <= 2 && process$1.stdin.isTTY)) {
  1774. console.log(`\n${help.replace('__VERSION__', rollup.version)}\n`);
  1775. }
  1776. else if (command.version) {
  1777. console.log(`rollup v${rollup.version}`);
  1778. }
  1779. else {
  1780. try {
  1781. // eslint-disable-next-line @typescript-eslint/no-require-imports
  1782. require('source-map-support').install();
  1783. }
  1784. catch {
  1785. // do nothing
  1786. }
  1787. const promise = runRollup(command);
  1788. if (command.forceExit) {
  1789. promise.then(() => process$1.exit());
  1790. }
  1791. }
  1792. exports.getConfigPath = getConfigPath;
  1793. exports.loadConfigFromCommand = loadConfigFromCommand;
  1794. exports.prettyMilliseconds = prettyMilliseconds;
  1795. exports.printTimings = printTimings;
  1796. //# sourceMappingURL=rollup.map