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