UNPKG

61.1 kBPlain TextView Raw
1#!/usr/bin/env node
2'use strict';
3
4function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
5
6var fs = require('fs');
7var fs__default = _interopDefault(fs);
8var path = require('path');
9var path__default = _interopDefault(path);
10var module$1 = _interopDefault(require('module'));
11var rollup = require('../dist/rollup.js');
12var rollup__default = _interopDefault(rollup);
13var assert = _interopDefault(require('assert'));
14var events = _interopDefault(require('events'));
15
16var 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, esm, iife, umd)\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-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.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--dynamicImportFunction <name> Rename the dynamic `import()` function\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--footer <text> Code to insert at end of bundle (outside wrapper)\n--no-freeze Do not freeze namespace objects\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--namespaceToStringTag Create proper `.toString` methods for namespaces\n--noConflict Generate a noConflict method for UMD globals\n--no-strict Don't emit `\"use strict\";` in the generated modules\n--outro <text> Code to insert at end of bundle (inside wrapper)\n--preferConst Use `const` instead of `var` for exports\n--preserveModules Preserve module structure\n--preserveSymlinks Do not follow symlinks when resolving files\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--strictDeprecations Throw errors for deprecated features\n--no-treeshake Disable tree-shaking optimisations\n--no-treeshake.annotations Ignore pure call annotations\n--no-treeshake.propertyReadSideEffects Ignore property access side-effects\n--treeshake.pureExternalModules Assume side-effect free externals\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";
17
18var minimist = function (args, opts) {
19 if (!opts)
20 opts = {};
21 var flags = { bools: {}, strings: {}, unknownFn: null };
22 if (typeof opts['unknown'] === 'function') {
23 flags.unknownFn = opts['unknown'];
24 }
25 if (typeof opts['boolean'] === 'boolean' && opts['boolean']) {
26 flags.allBools = true;
27 }
28 else {
29 [].concat(opts['boolean']).filter(Boolean).forEach(function (key) {
30 flags.bools[key] = true;
31 });
32 }
33 var aliases = {};
34 Object.keys(opts.alias || {}).forEach(function (key) {
35 aliases[key] = [].concat(opts.alias[key]);
36 aliases[key].forEach(function (x) {
37 aliases[x] = [key].concat(aliases[key].filter(function (y) {
38 return x !== y;
39 }));
40 });
41 });
42 [].concat(opts.string).filter(Boolean).forEach(function (key) {
43 flags.strings[key] = true;
44 if (aliases[key]) {
45 flags.strings[aliases[key]] = true;
46 }
47 });
48 var defaults = opts['default'] || {};
49 var argv = { _: [] };
50 Object.keys(flags.bools).forEach(function (key) {
51 setArg(key, defaults[key] === undefined ? false : defaults[key]);
52 });
53 var notFlags = [];
54 if (args.indexOf('--') !== -1) {
55 notFlags = args.slice(args.indexOf('--') + 1);
56 args = args.slice(0, args.indexOf('--'));
57 }
58 function argDefined(key, arg) {
59 return (flags.allBools && /^--[^=]+$/.test(arg)) ||
60 flags.strings[key] || flags.bools[key] || aliases[key];
61 }
62 function setArg(key, val, arg) {
63 if (arg && flags.unknownFn && !argDefined(key, arg)) {
64 if (flags.unknownFn(arg) === false)
65 return;
66 }
67 var value = !flags.strings[key] && isNumber(val)
68 ? Number(val) : val;
69 setKey(argv, key.split('.'), value);
70 (aliases[key] || []).forEach(function (x) {
71 setKey(argv, x.split('.'), value);
72 });
73 }
74 function setKey(obj, keys, value) {
75 var o = obj;
76 keys.slice(0, -1).forEach(function (key) {
77 if (o[key] === undefined)
78 o[key] = {};
79 o = o[key];
80 });
81 var key = keys[keys.length - 1];
82 if (o[key] === undefined || flags.bools[key] || typeof o[key] === 'boolean') {
83 o[key] = value;
84 }
85 else if (Array.isArray(o[key])) {
86 o[key].push(value);
87 }
88 else {
89 o[key] = [o[key], value];
90 }
91 }
92 function aliasIsBoolean(key) {
93 return aliases[key].some(function (x) {
94 return flags.bools[x];
95 });
96 }
97 for (var i = 0; i < args.length; i++) {
98 var arg = args[i];
99 if (/^--.+=/.test(arg)) {
100 // Using [\s\S] instead of . because js doesn't support the
101 // 'dotall' regex modifier. See:
102 // http://stackoverflow.com/a/1068308/13216
103 var m = arg.match(/^--([^=]+)=([\s\S]*)$/);
104 var key = m[1];
105 var value = m[2];
106 if (flags.bools[key]) {
107 value = value !== 'false';
108 }
109 setArg(key, value, arg);
110 }
111 else if (/^--no-.+/.test(arg)) {
112 var key = arg.match(/^--no-(.+)/)[1];
113 setArg(key, false, arg);
114 }
115 else if (/^--.+/.test(arg)) {
116 var key = arg.match(/^--(.+)/)[1];
117 var next = args[i + 1];
118 if (next !== undefined && !/^-/.test(next)
119 && !flags.bools[key]
120 && !flags.allBools
121 && (aliases[key] ? !aliasIsBoolean(key) : true)) {
122 setArg(key, next, arg);
123 i++;
124 }
125 else if (/^(true|false)$/.test(next)) {
126 setArg(key, next === 'true', arg);
127 i++;
128 }
129 else {
130 setArg(key, flags.strings[key] ? '' : true, arg);
131 }
132 }
133 else if (/^-[^-]+/.test(arg)) {
134 var letters = arg.slice(1, -1).split('');
135 var broken = false;
136 for (var j = 0; j < letters.length; j++) {
137 var next = arg.slice(j + 2);
138 if (next === '-') {
139 setArg(letters[j], next, arg);
140 continue;
141 }
142 if (/[A-Za-z]/.test(letters[j]) && /=/.test(next)) {
143 setArg(letters[j], next.split('=')[1], arg);
144 broken = true;
145 break;
146 }
147 if (/[A-Za-z]/.test(letters[j])
148 && /-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) {
149 setArg(letters[j], next, arg);
150 broken = true;
151 break;
152 }
153 if (letters[j + 1] && letters[j + 1].match(/\W/)) {
154 setArg(letters[j], arg.slice(j + 2), arg);
155 broken = true;
156 break;
157 }
158 else {
159 setArg(letters[j], flags.strings[letters[j]] ? '' : true, arg);
160 }
161 }
162 var key = arg.slice(-1)[0];
163 if (!broken && key !== '-') {
164 if (args[i + 1] && !/^(-|--)[^-]/.test(args[i + 1])
165 && !flags.bools[key]
166 && (aliases[key] ? !aliasIsBoolean(key) : true)) {
167 setArg(key, args[i + 1], arg);
168 i++;
169 }
170 else if (args[i + 1] && /true|false/.test(args[i + 1])) {
171 setArg(key, args[i + 1] === 'true', arg);
172 i++;
173 }
174 else {
175 setArg(key, flags.strings[key] ? '' : true, arg);
176 }
177 }
178 }
179 else {
180 if (!flags.unknownFn || flags.unknownFn(arg) !== false) {
181 argv._.push(flags.strings['_'] || !isNumber(arg) ? arg : Number(arg));
182 }
183 if (opts.stopEarly) {
184 argv._.push.apply(argv._, args.slice(i + 1));
185 break;
186 }
187 }
188 }
189 Object.keys(defaults).forEach(function (key) {
190 if (!hasKey(argv, key.split('.'))) {
191 setKey(argv, key.split('.'), defaults[key]);
192 (aliases[key] || []).forEach(function (x) {
193 setKey(argv, x.split('.'), defaults[key]);
194 });
195 }
196 });
197 if (opts['--']) {
198 argv['--'] = new Array();
199 notFlags.forEach(function (key) {
200 argv['--'].push(key);
201 });
202 }
203 else {
204 notFlags.forEach(function (key) {
205 argv._.push(key);
206 });
207 }
208 return argv;
209};
210function hasKey(obj, keys) {
211 var o = obj;
212 keys.slice(0, -1).forEach(function (key) {
213 o = (o[key] || {});
214 });
215 var key = keys[keys.length - 1];
216 return key in o;
217}
218function isNumber(x) {
219 if (typeof x === 'number')
220 return true;
221 if (/^0x[0-9a-f]+$/i.test(x))
222 return true;
223 return /^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x);
224}
225
226var version = "1.18.0";
227
228const createGetOption = (config, command) => (name, defaultValue) => command[name] !== undefined
229 ? command[name]
230 : config[name] !== undefined
231 ? config[name]
232 : defaultValue;
233const normalizeObjectOptionValue = (optionValue) => {
234 if (!optionValue) {
235 return optionValue;
236 }
237 if (typeof optionValue !== 'object') {
238 return {};
239 }
240 return optionValue;
241};
242const getObjectOption = (config, command, name) => {
243 const commandOption = normalizeObjectOptionValue(command[name]);
244 const configOption = normalizeObjectOptionValue(config[name]);
245 if (commandOption !== undefined) {
246 return commandOption && configOption ? Object.assign({}, configOption, commandOption) : commandOption;
247 }
248 return configOption;
249};
250const defaultOnWarn = warning => {
251 if (typeof warning === 'string') {
252 console.warn(warning);
253 }
254 else {
255 console.warn(warning.message);
256 }
257};
258const getOnWarn = (config, defaultOnWarnHandler = defaultOnWarn) => config.onwarn
259 ? warning => config.onwarn(warning, defaultOnWarnHandler)
260 : defaultOnWarnHandler;
261const getExternal = (config, command) => {
262 const configExternal = config.external;
263 return typeof configExternal === 'function'
264 ? (id, ...rest) => configExternal(id, ...rest) || command.external.indexOf(id) !== -1
265 : (typeof config.external === 'string'
266 ? [configExternal]
267 : Array.isArray(configExternal)
268 ? configExternal
269 : []).concat(command.external);
270};
271const commandAliases = {
272 c: 'config',
273 d: 'dir',
274 e: 'external',
275 f: 'format',
276 g: 'globals',
277 h: 'help',
278 i: 'input',
279 m: 'sourcemap',
280 n: 'name',
281 o: 'file',
282 v: 'version',
283 w: 'watch'
284};
285function mergeOptions({ config = {}, command: rawCommandOptions = {}, defaultOnWarnHandler }) {
286 const command = getCommandOptions(rawCommandOptions);
287 const inputOptions = getInputOptions(config, command, defaultOnWarnHandler);
288 if (command.output) {
289 Object.assign(command, command.output);
290 }
291 const output = config.output;
292 const normalizedOutputOptions = Array.isArray(output) ? output : output ? [output] : [];
293 if (normalizedOutputOptions.length === 0)
294 normalizedOutputOptions.push({});
295 const outputOptions = normalizedOutputOptions.map(singleOutputOptions => getOutputOptions(singleOutputOptions, command));
296 const unknownOptionErrors = [];
297 const validInputOptions = Object.keys(inputOptions);
298 addUnknownOptionErrors(unknownOptionErrors, Object.keys(config), validInputOptions, 'input option', /^output$/);
299 const validOutputOptions = Object.keys(outputOptions[0]);
300 addUnknownOptionErrors(unknownOptionErrors, outputOptions.reduce((allKeys, options) => allKeys.concat(Object.keys(options)), []), validOutputOptions, 'output option');
301 const validCliOutputOptions = validOutputOptions.filter(option => option !== 'sourcemapPathTransform');
302 addUnknownOptionErrors(unknownOptionErrors, Object.keys(command), validInputOptions.concat(validCliOutputOptions, Object.keys(commandAliases), 'config', 'environment', 'silent'), 'CLI flag', /^_|output|(config.*)$/);
303 return {
304 inputOptions,
305 optionError: unknownOptionErrors.length > 0 ? unknownOptionErrors.join('\n') : null,
306 outputOptions
307 };
308}
309function addUnknownOptionErrors(errors, options, validOptions, optionType, ignoredKeys = /$./) {
310 const unknownOptions = options.filter(key => validOptions.indexOf(key) === -1 && !ignoredKeys.test(key));
311 if (unknownOptions.length > 0)
312 errors.push(`Unknown ${optionType}: ${unknownOptions.join(', ')}. Allowed options: ${validOptions.sort().join(', ')}`);
313}
314function getCommandOptions(rawCommandOptions) {
315 const external = rawCommandOptions.external && typeof rawCommandOptions.external === 'string'
316 ? rawCommandOptions.external.split(',')
317 : [];
318 return Object.assign({}, rawCommandOptions, { external, globals: typeof rawCommandOptions.globals === 'string'
319 ? rawCommandOptions.globals.split(',').reduce((globals, globalDefinition) => {
320 const [id, variableName] = globalDefinition.split(':');
321 globals[id] = variableName;
322 if (external.indexOf(id) === -1) {
323 external.push(id);
324 }
325 return globals;
326 }, Object.create(null))
327 : undefined });
328}
329function getInputOptions(config, command = { external: [], globals: undefined }, defaultOnWarnHandler) {
330 const getOption = createGetOption(config, command);
331 const inputOptions = {
332 acorn: config.acorn,
333 acornInjectPlugins: config.acornInjectPlugins,
334 cache: getOption('cache'),
335 chunkGroupingSize: getOption('chunkGroupingSize', 5000),
336 context: config.context,
337 experimentalCacheExpiry: getOption('experimentalCacheExpiry', 10),
338 experimentalOptimizeChunks: getOption('experimentalOptimizeChunks'),
339 experimentalTopLevelAwait: getOption('experimentalTopLevelAwait'),
340 external: getExternal(config, command),
341 inlineDynamicImports: getOption('inlineDynamicImports', false),
342 input: getOption('input', []),
343 manualChunks: getOption('manualChunks'),
344 moduleContext: config.moduleContext,
345 onwarn: getOnWarn(config, defaultOnWarnHandler),
346 perf: getOption('perf', false),
347 plugins: config.plugins,
348 preserveModules: getOption('preserveModules'),
349 preserveSymlinks: getOption('preserveSymlinks'),
350 shimMissingExports: getOption('shimMissingExports'),
351 strictDeprecations: getOption('strictDeprecations', false),
352 treeshake: getObjectOption(config, command, 'treeshake'),
353 watch: config.watch
354 };
355 // support rollup({ cache: prevBuildObject })
356 if (inputOptions.cache && inputOptions.cache.cache)
357 inputOptions.cache = inputOptions.cache.cache;
358 return inputOptions;
359}
360function getOutputOptions(config, command = {}) {
361 const getOption = createGetOption(config, command);
362 let format = getOption('format');
363 // Handle format aliases
364 switch (format) {
365 case 'esm':
366 case 'module':
367 format = 'es';
368 break;
369 case 'commonjs':
370 format = 'cjs';
371 }
372 return {
373 amd: Object.assign({}, config.amd, command.amd),
374 assetFileNames: getOption('assetFileNames'),
375 banner: getOption('banner'),
376 chunkFileNames: getOption('chunkFileNames'),
377 compact: getOption('compact', false),
378 dir: getOption('dir'),
379 dynamicImportFunction: getOption('dynamicImportFunction'),
380 entryFileNames: getOption('entryFileNames'),
381 esModule: getOption('esModule', true),
382 exports: getOption('exports'),
383 extend: getOption('extend'),
384 externalLiveBindings: getOption('externalLiveBindings', true),
385 file: getOption('file'),
386 footer: getOption('footer'),
387 format: format === 'esm' ? 'es' : format,
388 freeze: getOption('freeze', true),
389 globals: getOption('globals'),
390 indent: getOption('indent', true),
391 interop: getOption('interop', true),
392 intro: getOption('intro'),
393 name: getOption('name'),
394 namespaceToStringTag: getOption('namespaceToStringTag', false),
395 noConflict: getOption('noConflict'),
396 outro: getOption('outro'),
397 paths: getOption('paths'),
398 preferConst: getOption('preferConst'),
399 sourcemap: getOption('sourcemap'),
400 sourcemapExcludeSources: getOption('sourcemapExcludeSources'),
401 sourcemapFile: getOption('sourcemapFile'),
402 sourcemapPathTransform: getOption('sourcemapPathTransform'),
403 strict: getOption('strict', true)
404 };
405}
406
407var modules = {};
408var getModule = function (dir) {
409 var rootPath = dir ? path__default.resolve(dir) : process.cwd();
410 var rootName = path__default.join(rootPath, '@root');
411 var root = modules[rootName];
412 if (!root) {
413 root = new module$1(rootName);
414 root.filename = rootName;
415 root.paths = module$1._nodeModulePaths(rootPath);
416 modules[rootName] = root;
417 }
418 return root;
419};
420var requireRelative = function (requested, relativeTo) {
421 var root = getModule(relativeTo);
422 return root.require(requested);
423};
424requireRelative.resolve = function (requested, relativeTo) {
425 var root = getModule(relativeTo);
426 return module$1._resolveFilename(requested, root);
427};
428var requireRelative_1 = requireRelative;
429
430const absolutePath = /^(?:\/|(?:[A-Za-z]:)?[\\|/])/;
431function isAbsolute(path) {
432 return absolutePath.test(path);
433}
434
435function getAliasName(id) {
436 const base = path.basename(id);
437 return base.substr(0, base.length - path.extname(id).length);
438}
439function relativeId(id) {
440 if (typeof process === 'undefined' || !isAbsolute(id))
441 return id;
442 return path.relative(process.cwd(), id);
443}
444
445const tc = {
446 enabled: process.env.FORCE_COLOR ||
447 process.platform === "win32" ||
448 (process.stdout.isTTY && process.env.TERM && process.env.TERM !== "dumb")
449};
450const Styles = (tc.Styles = {});
451const defineProp = Object.defineProperty;
452const init = (style, open, close, re) => {
453 let i, len = 1, seq = [(Styles[style] = { open, close, re })];
454 const fn = s => {
455 if (tc.enabled) {
456 for (i = 0, s += ""; i < len; i++) {
457 style = seq[i];
458 s =
459 (open = style.open) +
460 (~s.indexOf((close = style.close), 4) // skip first \x1b[
461 ? s.replace(style.re, open)
462 : s) +
463 close;
464 }
465 len = 1;
466 }
467 return s;
468 };
469 defineProp(tc, style, {
470 get: () => {
471 for (let k in Styles)
472 defineProp(fn, k, {
473 get: () => ((seq[len++] = Styles[k]), fn)
474 });
475 delete tc[style];
476 return (tc[style] = fn);
477 },
478 configurable: true
479 });
480};
481init("reset", "\x1b[0m", "\x1b[0m", /\x1b\[0m/g);
482init("bold", "\x1b[1m", "\x1b[22m", /\x1b\[22m/g);
483init("dim", "\x1b[2m", "\x1b[22m", /\x1b\[22m/g);
484init("italic", "\x1b[3m", "\x1b[23m", /\x1b\[23m/g);
485init("underline", "\x1b[4m", "\x1b[24m", /\x1b\[24m/g);
486init("inverse", "\x1b[7m", "\x1b[27m", /\x1b\[27m/g);
487init("hidden", "\x1b[8m", "\x1b[28m", /\x1b\[28m/g);
488init("strikethrough", "\x1b[9m", "\x1b[29m", /\x1b\[29m/g);
489init("black", "\x1b[30m", "\x1b[39m", /\x1b\[39m/g);
490init("red", "\x1b[31m", "\x1b[39m", /\x1b\[39m/g);
491init("green", "\x1b[32m", "\x1b[39m", /\x1b\[39m/g);
492init("yellow", "\x1b[33m", "\x1b[39m", /\x1b\[39m/g);
493init("blue", "\x1b[34m", "\x1b[39m", /\x1b\[39m/g);
494init("magenta", "\x1b[35m", "\x1b[39m", /\x1b\[39m/g);
495init("cyan", "\x1b[36m", "\x1b[39m", /\x1b\[39m/g);
496init("white", "\x1b[37m", "\x1b[39m", /\x1b\[39m/g);
497init("gray", "\x1b[90m", "\x1b[39m", /\x1b\[39m/g);
498init("bgBlack", "\x1b[40m", "\x1b[49m", /\x1b\[49m/g);
499init("bgRed", "\x1b[41m", "\x1b[49m", /\x1b\[49m/g);
500init("bgGreen", "\x1b[42m", "\x1b[49m", /\x1b\[49m/g);
501init("bgYellow", "\x1b[43m", "\x1b[49m", /\x1b\[49m/g);
502init("bgBlue", "\x1b[44m", "\x1b[49m", /\x1b\[49m/g);
503init("bgMagenta", "\x1b[45m", "\x1b[49m", /\x1b\[49m/g);
504init("bgCyan", "\x1b[46m", "\x1b[49m", /\x1b\[49m/g);
505init("bgWhite", "\x1b[47m", "\x1b[49m", /\x1b\[49m/g);
506var turbocolor = tc;
507
508// log to stderr to keep `rollup main.js > bundle.js` from breaking
509const stderr = console.error.bind(console);
510function handleError(err, recover = false) {
511 let description = err.message || err;
512 if (err.name)
513 description = `${err.name}: ${description}`;
514 const message = (err.plugin
515 ? `(plugin ${err.plugin}) ${description}`
516 : description) || err;
517 stderr(turbocolor.bold.red(`[!] ${turbocolor.bold(message.toString())}`));
518 if (err.url) {
519 stderr(turbocolor.cyan(err.url));
520 }
521 if (err.loc) {
522 stderr(`${relativeId((err.loc.file || err.id))} (${err.loc.line}:${err.loc.column})`);
523 }
524 else if (err.id) {
525 stderr(relativeId(err.id));
526 }
527 if (err.frame) {
528 stderr(turbocolor.dim(err.frame));
529 }
530 if (err.stack) {
531 stderr(turbocolor.dim(err.stack));
532 }
533 stderr('');
534 if (!recover)
535 process.exit(1);
536}
537
538function batchWarnings() {
539 let allWarnings = new Map();
540 let count = 0;
541 return {
542 get count() {
543 return count;
544 },
545 add: (warning) => {
546 if (typeof warning === 'string') {
547 warning = { code: 'UNKNOWN', message: warning };
548 }
549 if (warning.code in immediateHandlers) {
550 immediateHandlers[warning.code](warning);
551 return;
552 }
553 if (!allWarnings.has(warning.code))
554 allWarnings.set(warning.code, []);
555 allWarnings.get(warning.code).push(warning);
556 count += 1;
557 },
558 flush: () => {
559 if (count === 0)
560 return;
561 const codes = Array.from(allWarnings.keys()).sort((a, b) => {
562 if (deferredHandlers[a] && deferredHandlers[b]) {
563 return deferredHandlers[a].priority - deferredHandlers[b].priority;
564 }
565 if (deferredHandlers[a])
566 return -1;
567 if (deferredHandlers[b])
568 return 1;
569 return (allWarnings.get(b).length -
570 allWarnings.get(a).length);
571 });
572 codes.forEach(code => {
573 const handler = deferredHandlers[code];
574 const warnings = allWarnings.get(code);
575 if (handler) {
576 handler.fn(warnings);
577 }
578 else {
579 warnings.forEach(warning => {
580 title(warning.message);
581 if (warning.url)
582 info(warning.url);
583 const id = (warning.loc && warning.loc.file) || warning.id;
584 if (id) {
585 const loc = warning.loc
586 ? `${relativeId(id)}: (${warning.loc.line}:${warning.loc.column})`
587 : relativeId(id);
588 stderr(turbocolor.bold(relativeId(loc)));
589 }
590 if (warning.frame)
591 info(warning.frame);
592 });
593 }
594 });
595 allWarnings = new Map();
596 count = 0;
597 }
598 };
599}
600const immediateHandlers = {
601 UNKNOWN_OPTION: warning => {
602 title(`You have passed an unrecognized option`);
603 stderr(warning.message);
604 },
605 MISSING_NODE_BUILTINS: warning => {
606 title(`Missing shims for Node.js built-ins`);
607 const detail = warning.modules.length === 1
608 ? `'${warning.modules[0]}'`
609 : `${warning.modules
610 .slice(0, -1)
611 .map((name) => `'${name}'`)
612 .join(', ')} and '${warning.modules.slice(-1)}'`;
613 stderr(`Creating a browser bundle that depends on ${detail}. You might need to include https://www.npmjs.com/package/rollup-plugin-node-builtins`);
614 },
615 MIXED_EXPORTS: () => {
616 title('Mixing named and default exports');
617 stderr(`Consumers of your bundle will have to use bundle['default'] to access the default export, which may not be what you want. Use \`output.exports: 'named'\` to disable this warning`);
618 },
619 EMPTY_BUNDLE: () => {
620 title(`Generated an empty bundle`);
621 }
622};
623// TODO select sensible priorities
624const deferredHandlers = {
625 UNUSED_EXTERNAL_IMPORT: {
626 fn: warnings => {
627 title('Unused external imports');
628 warnings.forEach(warning => {
629 stderr(`${warning.names} imported from external module '${warning.source}' but never used`);
630 });
631 },
632 priority: 1
633 },
634 UNRESOLVED_IMPORT: {
635 fn: warnings => {
636 title('Unresolved dependencies');
637 info('https://rollupjs.org/guide/en/#warning-treating-module-as-external-dependency');
638 const dependencies = new Map();
639 warnings.forEach(warning => {
640 if (!dependencies.has(warning.source))
641 dependencies.set(warning.source, []);
642 dependencies.get(warning.source).push(warning.importer);
643 });
644 Array.from(dependencies.keys()).forEach(dependency => {
645 const importers = dependencies.get(dependency);
646 stderr(`${turbocolor.bold(dependency)} (imported by ${importers.join(', ')})`);
647 });
648 },
649 priority: 1
650 },
651 MISSING_EXPORT: {
652 fn: warnings => {
653 title('Missing exports');
654 info('https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module-');
655 warnings.forEach(warning => {
656 stderr(turbocolor.bold(warning.importer));
657 stderr(`${warning.missing} is not exported by ${warning.exporter}`);
658 stderr(turbocolor.gray(warning.frame));
659 });
660 },
661 priority: 1
662 },
663 THIS_IS_UNDEFINED: {
664 fn: warnings => {
665 title('`this` has been rewritten to `undefined`');
666 info('https://rollupjs.org/guide/en/#error-this-is-undefined');
667 showTruncatedWarnings(warnings);
668 },
669 priority: 1
670 },
671 EVAL: {
672 fn: warnings => {
673 title('Use of eval is strongly discouraged');
674 info('https://rollupjs.org/guide/en/#avoiding-eval');
675 showTruncatedWarnings(warnings);
676 },
677 priority: 1
678 },
679 NON_EXISTENT_EXPORT: {
680 fn: warnings => {
681 title(`Import of non-existent ${warnings.length > 1 ? 'exports' : 'export'}`);
682 showTruncatedWarnings(warnings);
683 },
684 priority: 1
685 },
686 NAMESPACE_CONFLICT: {
687 fn: warnings => {
688 title(`Conflicting re-exports`);
689 warnings.forEach(warning => {
690 stderr(`${turbocolor.bold(relativeId(warning.reexporter))} re-exports '${warning.name}' from both ${relativeId(warning.sources[0])} and ${relativeId(warning.sources[1])} (will be ignored)`);
691 });
692 },
693 priority: 1
694 },
695 MISSING_GLOBAL_NAME: {
696 fn: warnings => {
697 title(`Missing global variable ${warnings.length > 1 ? 'names' : 'name'}`);
698 stderr(`Use output.globals to specify browser global variable names corresponding to external modules`);
699 warnings.forEach(warning => {
700 stderr(`${turbocolor.bold(warning.source)} (guessing '${warning.guess}')`);
701 });
702 },
703 priority: 1
704 },
705 SOURCEMAP_BROKEN: {
706 fn: warnings => {
707 title(`Broken sourcemap`);
708 info('https://rollupjs.org/guide/en/#warning-sourcemap-is-likely-to-be-incorrect');
709 const plugins = Array.from(new Set(warnings.map(w => w.plugin).filter(Boolean)));
710 const detail = plugins.length === 0
711 ? ''
712 : plugins.length > 1
713 ? ` (such as ${plugins
714 .slice(0, -1)
715 .map(p => `'${p}'`)
716 .join(', ')} and '${plugins.slice(-1)}')`
717 : ` (such as '${plugins[0]}')`;
718 stderr(`Plugins that transform code${detail} should generate accompanying sourcemaps`);
719 },
720 priority: 1
721 },
722 PLUGIN_WARNING: {
723 fn: warnings => {
724 const nestedByPlugin = nest(warnings, 'plugin');
725 nestedByPlugin.forEach(({ key: plugin, items }) => {
726 const nestedByMessage = nest(items, 'message');
727 let lastUrl;
728 nestedByMessage.forEach(({ key: message, items }) => {
729 title(`Plugin ${plugin}: ${message}`);
730 items.forEach(warning => {
731 if (warning.url !== lastUrl)
732 info((lastUrl = warning.url));
733 if (warning.id) {
734 let loc = relativeId(warning.id);
735 if (warning.loc) {
736 loc += `: (${warning.loc.line}:${warning.loc.column})`;
737 }
738 stderr(turbocolor.bold(loc));
739 }
740 if (warning.frame)
741 info(warning.frame);
742 });
743 });
744 });
745 },
746 priority: 1
747 }
748};
749function title(str) {
750 stderr(`${turbocolor.bold.yellow('(!)')} ${turbocolor.bold.yellow(str)}`);
751}
752function info(url) {
753 stderr(turbocolor.gray(url));
754}
755function nest(array, prop) {
756 const nested = [];
757 const lookup = new Map();
758 array.forEach(item => {
759 const key = item[prop];
760 if (!lookup.has(key)) {
761 lookup.set(key, {
762 items: [],
763 key
764 });
765 nested.push(lookup.get(key));
766 }
767 lookup.get(key).items.push(item);
768 });
769 return nested;
770}
771function showTruncatedWarnings(warnings) {
772 const nestedByModule = nest(warnings, 'id');
773 const sliced = nestedByModule.length > 5 ? nestedByModule.slice(0, 3) : nestedByModule;
774 sliced.forEach(({ key: id, items }) => {
775 stderr(turbocolor.bold(relativeId(id)));
776 stderr(turbocolor.gray(items[0].frame));
777 if (items.length > 1) {
778 stderr(`...and ${items.length - 1} other ${items.length > 2 ? 'occurrences' : 'occurrence'}`);
779 }
780 });
781 if (nestedByModule.length > sliced.length) {
782 stderr(`\n...and ${nestedByModule.length - sliced.length} other files`);
783 }
784}
785
786var parseMs = milliseconds => {
787 if (typeof milliseconds !== 'number') {
788 throw new TypeError('Expected a number');
789 }
790 const roundTowardsZero = milliseconds > 0 ? Math.floor : Math.ceil;
791 return {
792 days: roundTowardsZero(milliseconds / 86400000),
793 hours: roundTowardsZero(milliseconds / 3600000) % 24,
794 minutes: roundTowardsZero(milliseconds / 60000) % 60,
795 seconds: roundTowardsZero(milliseconds / 1000) % 60,
796 milliseconds: roundTowardsZero(milliseconds) % 1000,
797 microseconds: roundTowardsZero(milliseconds * 1000) % 1000,
798 nanoseconds: roundTowardsZero(milliseconds * 1e6) % 1000
799 };
800};
801
802const pluralize = (word, count) => count === 1 ? word : word + 's';
803var prettyMs = (milliseconds, options = {}) => {
804 if (!Number.isFinite(milliseconds)) {
805 throw new TypeError('Expected a finite number');
806 }
807 if (options.compact) {
808 options.secondsDecimalDigits = 0;
809 options.millisecondsDecimalDigits = 0;
810 }
811 const result = [];
812 const add = (value, long, short, valueString) => {
813 if (value === 0) {
814 return;
815 }
816 const postfix = options.verbose ? ' ' + pluralize(long, value) : short;
817 result.push((valueString || value) + postfix);
818 };
819 const secondsDecimalDigits = typeof options.secondsDecimalDigits === 'number' ?
820 options.secondsDecimalDigits :
821 1;
822 if (secondsDecimalDigits < 1) {
823 const difference = 1000 - (milliseconds % 1000);
824 if (difference < 500) {
825 milliseconds += difference;
826 }
827 }
828 const parsed = parseMs(milliseconds);
829 add(Math.trunc(parsed.days / 365), 'year', 'y');
830 add(parsed.days % 365, 'day', 'd');
831 add(parsed.hours, 'hour', 'h');
832 add(parsed.minutes, 'minute', 'm');
833 if (options.separateMilliseconds ||
834 options.formatSubMilliseconds ||
835 milliseconds < 1000) {
836 add(parsed.seconds, 'second', 's');
837 if (options.formatSubMilliseconds) {
838 add(parsed.milliseconds, 'millisecond', 'ms');
839 add(parsed.microseconds, 'microsecond', 'µs');
840 add(parsed.nanoseconds, 'nanosecond', 'ns');
841 }
842 else {
843 const millisecondsAndBelow = parsed.milliseconds +
844 (parsed.microseconds / 1000) +
845 (parsed.nanoseconds / 1e6);
846 const millisecondsDecimalDigits = typeof options.millisecondsDecimalDigits === 'number' ?
847 options.millisecondsDecimalDigits :
848 0;
849 const millisecondsString = millisecondsDecimalDigits ?
850 millisecondsAndBelow.toFixed(millisecondsDecimalDigits) :
851 Math.ceil(millisecondsAndBelow);
852 add(parseFloat(millisecondsString, 10), 'millisecond', 'ms', millisecondsString);
853 }
854 }
855 else {
856 const seconds = (milliseconds / 1000) % 60;
857 const secondsDecimalDigits = typeof options.secondsDecimalDigits === 'number' ?
858 options.secondsDecimalDigits :
859 1;
860 const secondsFixed = seconds.toFixed(secondsDecimalDigits);
861 const secondsString = options.keepDecimalsOnWholeSeconds ?
862 secondsFixed :
863 secondsFixed.replace(/\.0+$/, '');
864 add(parseFloat(secondsString, 10), 'second', 's', secondsString);
865 }
866 if (result.length === 0) {
867 return '0' + (options.verbose ? ' milliseconds' : 'ms');
868 }
869 if (options.compact) {
870 return '~' + result[0];
871 }
872 if (typeof options.unitCount === 'number') {
873 return '~' + result.slice(0, Math.max(options.unitCount, 1)).join(' ');
874 }
875 return result.join(' ');
876};
877
878let SOURCEMAPPING_URL = 'sourceMa';
879SOURCEMAPPING_URL += 'ppingURL';
880var SOURCEMAPPING_URL$1 = SOURCEMAPPING_URL;
881
882const UNITS = [
883 'B',
884 'kB',
885 'MB',
886 'GB',
887 'TB',
888 'PB',
889 'EB',
890 'ZB',
891 'YB'
892];
893/*
894Formats the given number using `Number#toLocaleString`.
895- If locale is a string, the value is expected to be a locale-key (for example: `de`).
896- If locale is true, the system default locale is used for translation.
897- If no value for locale is specified, the number is returned unmodified.
898*/
899const toLocaleString = (number, locale) => {
900 let result = number;
901 if (typeof locale === 'string') {
902 result = number.toLocaleString(locale);
903 }
904 else if (locale === true) {
905 result = number.toLocaleString();
906 }
907 return result;
908};
909var prettyBytes = (number, options) => {
910 if (!Number.isFinite(number)) {
911 throw new TypeError(`Expected a finite number, got ${typeof number}: ${number}`);
912 }
913 options = Object.assign({}, options);
914 if (options.signed && number === 0) {
915 return ' 0 B';
916 }
917 const isNegative = number < 0;
918 const prefix = isNegative ? '-' : (options.signed ? '+' : '');
919 if (isNegative) {
920 number = -number;
921 }
922 if (number < 1) {
923 const numberString = toLocaleString(number, options.locale);
924 return prefix + numberString + ' B';
925 }
926 const exponent = Math.min(Math.floor(Math.log10(number) / 3), UNITS.length - 1);
927 // eslint-disable-next-line unicorn/prefer-exponentiation-operator
928 number = Number((number / Math.pow(1000, exponent)).toPrecision(3));
929 const numberString = toLocaleString(number, options.locale);
930 const unit = UNITS[exponent];
931 return prefix + numberString + ' ' + unit;
932};
933
934function printTimings(timings) {
935 Object.keys(timings).forEach(label => {
936 const color = label[0] === '#' ? (label[1] !== '#' ? turbocolor.underline : turbocolor.bold) : (text) => text;
937 const [time, memory, total] = timings[label];
938 const row = `${label}: ${time.toFixed(0)}ms, ${prettyBytes(memory)} / ${prettyBytes(total)}`;
939 console.info(color(row));
940 });
941}
942
943function build(inputOptions, outputOptions, warnings, silent = false) {
944 const useStdout = !outputOptions[0].file && !outputOptions[0].dir;
945 const start = Date.now();
946 const files = useStdout
947 ? ['stdout']
948 : outputOptions.map(t => relativeId(t.file || t.dir));
949 if (!silent) {
950 let inputFiles = undefined;
951 if (typeof inputOptions.input === 'string') {
952 inputFiles = inputOptions.input;
953 }
954 else if (inputOptions.input instanceof Array) {
955 inputFiles = inputOptions.input.join(', ');
956 }
957 else if (typeof inputOptions.input === 'object' && inputOptions.input !== null) {
958 inputFiles = Object.keys(inputOptions.input)
959 .map(name => inputOptions.input[name])
960 .join(', ');
961 }
962 stderr(turbocolor.cyan(`\n${turbocolor.bold(inputFiles)} → ${turbocolor.bold(files.join(', '))}...`));
963 }
964 return rollup.rollup(inputOptions)
965 .then((bundle) => {
966 if (useStdout) {
967 const output = outputOptions[0];
968 if (output.sourcemap && output.sourcemap !== 'inline') {
969 handleError({
970 code: 'MISSING_OUTPUT_OPTION',
971 message: 'You must specify a --file (-o) option when creating a file with a sourcemap'
972 });
973 }
974 return bundle.generate(output).then(({ output: outputs }) => {
975 for (const file of outputs) {
976 let source;
977 if (file.isAsset) {
978 source = file.source;
979 }
980 else {
981 source = file.code;
982 if (output.sourcemap === 'inline') {
983 source += `\n//# ${SOURCEMAPPING_URL$1}=${file
984 .map.toUrl()}\n`;
985 }
986 }
987 if (outputs.length > 1)
988 process.stdout.write('\n' + turbocolor.cyan(turbocolor.bold('//→ ' + file.fileName + ':')) + '\n');
989 process.stdout.write(source);
990 }
991 });
992 }
993 return Promise.all(outputOptions.map(output => bundle.write(output))).then(() => bundle);
994 })
995 .then((bundle) => {
996 if (!silent) {
997 warnings.flush();
998 stderr(turbocolor.green(`created ${turbocolor.bold(files.join(', '))} in ${turbocolor.bold(prettyMs(Date.now() - start))}`));
999 if (bundle && bundle.getTimings) {
1000 printTimings(bundle.getTimings());
1001 }
1002 }
1003 })
1004 .catch((err) => {
1005 if (warnings.count > 0)
1006 warnings.flush();
1007 handleError(err);
1008 });
1009}
1010
1011function loadConfigFile(configFile, commandOptions = {}) {
1012 const silent = commandOptions.silent || false;
1013 const warnings = batchWarnings();
1014 return rollup__default
1015 .rollup({
1016 external: (id) => (id[0] !== '.' && !path__default.isAbsolute(id)) || id.slice(-5, id.length) === '.json',
1017 input: configFile,
1018 onwarn: warnings.add,
1019 treeshake: false
1020 })
1021 .then((bundle) => {
1022 if (!silent && warnings.count > 0) {
1023 stderr(turbocolor.bold(`loaded ${relativeId(configFile)} with warnings`));
1024 warnings.flush();
1025 }
1026 return bundle.generate({
1027 exports: 'named',
1028 format: 'cjs'
1029 });
1030 })
1031 .then(({ output: [{ code }] }) => {
1032 // temporarily override require
1033 const defaultLoader = require.extensions['.js'];
1034 require.extensions['.js'] = (module, filename) => {
1035 if (filename === configFile) {
1036 module._compile(code, filename);
1037 }
1038 else {
1039 defaultLoader(module, filename);
1040 }
1041 };
1042 delete require.cache[configFile];
1043 return Promise.resolve(require(configFile))
1044 .then(configFileContent => {
1045 if (configFileContent.default)
1046 configFileContent = configFileContent.default;
1047 if (typeof configFileContent === 'function') {
1048 return configFileContent(commandOptions);
1049 }
1050 return configFileContent;
1051 })
1052 .then(configs => {
1053 if (Object.keys(configs).length === 0) {
1054 handleError({
1055 code: 'MISSING_CONFIG',
1056 message: 'Config file must export an options object, or an array of options objects',
1057 url: 'https://rollupjs.org/guide/en/#configuration-files'
1058 });
1059 }
1060 require.extensions['.js'] = defaultLoader;
1061 return Array.isArray(configs) ? configs : [configs];
1062 });
1063 });
1064}
1065
1066var timeZone = date => {
1067 const offset = (date || new Date()).getTimezoneOffset();
1068 const absOffset = Math.abs(offset);
1069 const hours = Math.floor(absOffset / 60);
1070 const minutes = absOffset % 60;
1071 const minutesOut = minutes > 0 ? ':' + ('0' + minutes).slice(-2) : '';
1072 return (offset < 0 ? '+' : '-') + hours + minutesOut;
1073};
1074
1075const dateTime = options => {
1076 options = Object.assign({
1077 date: new Date(),
1078 local: true,
1079 showTimeZone: false,
1080 showMilliseconds: false
1081 }, options);
1082 let { date } = options;
1083 if (options.local) {
1084 // Offset the date so it will return the correct value when getting the ISO string
1085 date = new Date(date.getTime() - (date.getTimezoneOffset() * 60000));
1086 }
1087 let end = '';
1088 if (options.showTimeZone) {
1089 end = ' UTC' + (options.local ? timeZone(date) : '');
1090 }
1091 if (options.showMilliseconds && date.getUTCMilliseconds() > 0) {
1092 end = ` ${date.getUTCMilliseconds()}ms${end}`;
1093 }
1094 return date
1095 .toISOString()
1096 .replace(/T/, ' ')
1097 .replace(/\..+/, end);
1098};
1099var dateTime_1 = dateTime;
1100// TODO: Remove this for the next major release
1101var default_1 = dateTime;
1102dateTime_1.default = default_1;
1103
1104function createCommonjsModule(fn, module) {
1105 return module = { exports: {} }, fn(module, module.exports), module.exports;
1106}
1107
1108var signals = createCommonjsModule(function (module) {
1109 // This is not the set of all possible signals.
1110 //
1111 // It IS, however, the set of all signals that trigger
1112 // an exit on either Linux or BSD systems. Linux is a
1113 // superset of the signal names supported on BSD, and
1114 // the unknown signals just fail to register, so we can
1115 // catch that easily enough.
1116 //
1117 // Don't bother with SIGKILL. It's uncatchable, which
1118 // means that we can't fire any callbacks anyway.
1119 //
1120 // If a user does happen to register a handler on a non-
1121 // fatal signal like SIGWINCH or something, and then
1122 // exit, it'll end up firing `process.emit('exit')`, so
1123 // the handler will be fired anyway.
1124 //
1125 // SIGBUS, SIGFPE, SIGSEGV and SIGILL, when not raised
1126 // artificially, inherently leave the process in a
1127 // state from which it is not safe to try and enter JS
1128 // listeners.
1129 module.exports = [
1130 'SIGABRT',
1131 'SIGALRM',
1132 'SIGHUP',
1133 'SIGINT',
1134 'SIGTERM'
1135 ];
1136 if (process.platform !== 'win32') {
1137 module.exports.push('SIGVTALRM', 'SIGXCPU', 'SIGXFSZ', 'SIGUSR2', 'SIGTRAP', 'SIGSYS', 'SIGQUIT', 'SIGIOT'
1138 // should detect profiler and enable/disable accordingly.
1139 // see #21
1140 // 'SIGPROF'
1141 );
1142 }
1143 if (process.platform === 'linux') {
1144 module.exports.push('SIGIO', 'SIGPOLL', 'SIGPWR', 'SIGSTKFLT', 'SIGUNUSED');
1145 }
1146});
1147
1148// Note: since nyc uses this module to output coverage, any lines
1149// that are in the direct sync flow of nyc's outputCoverage are
1150// ignored, since we can never get coverage for them.
1151var signals$1 = signals;
1152var EE = events;
1153/* istanbul ignore if */
1154if (typeof EE !== 'function') {
1155 EE = EE.EventEmitter;
1156}
1157var emitter;
1158if (process.__signal_exit_emitter__) {
1159 emitter = process.__signal_exit_emitter__;
1160}
1161else {
1162 emitter = process.__signal_exit_emitter__ = new EE();
1163 emitter.count = 0;
1164 emitter.emitted = {};
1165}
1166// Because this emitter is a global, we have to check to see if a
1167// previous version of this library failed to enable infinite listeners.
1168// I know what you're about to say. But literally everything about
1169// signal-exit is a compromise with evil. Get used to it.
1170if (!emitter.infinite) {
1171 emitter.setMaxListeners(Infinity);
1172 emitter.infinite = true;
1173}
1174var signalExit = function (cb, opts) {
1175 assert.equal(typeof cb, 'function', 'a callback must be provided for exit handler');
1176 if (loaded === false) {
1177 load();
1178 }
1179 var ev = 'exit';
1180 if (opts && opts.alwaysLast) {
1181 ev = 'afterexit';
1182 }
1183 var remove = function () {
1184 emitter.removeListener(ev, cb);
1185 if (emitter.listeners('exit').length === 0 &&
1186 emitter.listeners('afterexit').length === 0) {
1187 unload();
1188 }
1189 };
1190 emitter.on(ev, cb);
1191 return remove;
1192};
1193var unload_1 = unload;
1194function unload() {
1195 if (!loaded) {
1196 return;
1197 }
1198 loaded = false;
1199 signals$1.forEach(function (sig) {
1200 try {
1201 process.removeListener(sig, sigListeners[sig]);
1202 }
1203 catch (er) { }
1204 });
1205 process.emit = originalProcessEmit;
1206 process.reallyExit = originalProcessReallyExit;
1207 emitter.count -= 1;
1208}
1209function emit(event, code, signal) {
1210 if (emitter.emitted[event]) {
1211 return;
1212 }
1213 emitter.emitted[event] = true;
1214 emitter.emit(event, code, signal);
1215}
1216// { <signal>: <listener fn>, ... }
1217var sigListeners = {};
1218signals$1.forEach(function (sig) {
1219 sigListeners[sig] = function listener() {
1220 // If there are no other listeners, an exit is coming!
1221 // Simplest way: remove us and then re-send the signal.
1222 // We know that this will kill the process, so we can
1223 // safely emit now.
1224 var listeners = process.listeners(sig);
1225 if (listeners.length === emitter.count) {
1226 unload();
1227 emit('exit', null, sig);
1228 /* istanbul ignore next */
1229 emit('afterexit', null, sig);
1230 /* istanbul ignore next */
1231 process.kill(process.pid, sig);
1232 }
1233 };
1234});
1235var signals_1 = function () {
1236 return signals$1;
1237};
1238var load_1 = load;
1239var loaded = false;
1240function load() {
1241 if (loaded) {
1242 return;
1243 }
1244 loaded = true;
1245 // This is the number of onSignalExit's that are in play.
1246 // It's important so that we can count the correct number of
1247 // listeners on signals, and don't wait for the other one to
1248 // handle it instead of us.
1249 emitter.count += 1;
1250 signals$1 = signals$1.filter(function (sig) {
1251 try {
1252 process.on(sig, sigListeners[sig]);
1253 return true;
1254 }
1255 catch (er) {
1256 return false;
1257 }
1258 });
1259 process.emit = processEmit;
1260 process.reallyExit = processReallyExit;
1261}
1262var originalProcessReallyExit = process.reallyExit;
1263function processReallyExit(code) {
1264 process.exitCode = code || 0;
1265 emit('exit', process.exitCode, null);
1266 /* istanbul ignore next */
1267 emit('afterexit', process.exitCode, null);
1268 /* istanbul ignore next */
1269 originalProcessReallyExit.call(process, process.exitCode);
1270}
1271var originalProcessEmit = process.emit;
1272function processEmit(ev, arg) {
1273 if (ev === 'exit') {
1274 if (arg !== undefined) {
1275 process.exitCode = arg;
1276 }
1277 var ret = originalProcessEmit.apply(this, arguments);
1278 emit('exit', process.exitCode, null);
1279 /* istanbul ignore next */
1280 emit('afterexit', process.exitCode, null);
1281 return ret;
1282 }
1283 else {
1284 return originalProcessEmit.apply(this, arguments);
1285 }
1286}
1287signalExit.unload = unload_1;
1288signalExit.signals = signals_1;
1289signalExit.load = load_1;
1290
1291const CLEAR_SCREEN = '\u001Bc';
1292function getResetScreen(clearScreen) {
1293 if (clearScreen) {
1294 return (heading) => stderr(CLEAR_SCREEN + heading);
1295 }
1296 let firstRun = true;
1297 return (heading) => {
1298 if (firstRun) {
1299 stderr(heading);
1300 firstRun = false;
1301 }
1302 };
1303}
1304
1305function watch(configFile, configs, command, silent = false) {
1306 const isTTY = Boolean(process.stderr.isTTY);
1307 const warnings = batchWarnings();
1308 const initialConfigs = processConfigs(configs);
1309 const clearScreen = initialConfigs.every(config => config.watch.clearScreen !== false);
1310 const resetScreen = getResetScreen(isTTY && clearScreen);
1311 let watcher;
1312 let configWatcher;
1313 function processConfigs(configs) {
1314 return configs.map(options => {
1315 const merged = mergeOptions({
1316 command,
1317 config: options,
1318 defaultOnWarnHandler: warnings.add
1319 });
1320 const result = Object.assign({}, merged.inputOptions, { output: merged.outputOptions });
1321 if (!result.watch)
1322 result.watch = {};
1323 if (merged.optionError)
1324 merged.inputOptions.onwarn({
1325 code: 'UNKNOWN_OPTION',
1326 message: merged.optionError
1327 });
1328 return result;
1329 });
1330 }
1331 function start(configs) {
1332 watcher = rollup.watch(configs);
1333 watcher.on('event', (event) => {
1334 switch (event.code) {
1335 case 'FATAL':
1336 handleError(event.error, true);
1337 process.exit(1);
1338 break;
1339 case 'ERROR':
1340 warnings.flush();
1341 handleError(event.error, true);
1342 break;
1343 case 'START':
1344 if (!silent) {
1345 resetScreen(turbocolor.underline(`rollup v${rollup.VERSION}`));
1346 }
1347 break;
1348 case 'BUNDLE_START':
1349 if (!silent) {
1350 let input = event.input;
1351 if (typeof input !== 'string') {
1352 input = Array.isArray(input)
1353 ? input.join(', ')
1354 : Object.keys(input)
1355 .map(key => input[key])
1356 .join(', ');
1357 }
1358 stderr(turbocolor.cyan(`bundles ${turbocolor.bold(input)} → ${turbocolor.bold(event.output.map(relativeId).join(', '))}...`));
1359 }
1360 break;
1361 case 'BUNDLE_END':
1362 warnings.flush();
1363 if (!silent)
1364 stderr(turbocolor.green(`created ${turbocolor.bold(event.output.map(relativeId).join(', '))} in ${turbocolor.bold(prettyMs(event.duration))}`));
1365 if (event.result && event.result.getTimings) {
1366 printTimings(event.result.getTimings());
1367 }
1368 break;
1369 case 'END':
1370 if (!silent && isTTY) {
1371 stderr(`\n[${dateTime_1()}] waiting for changes...`);
1372 }
1373 }
1374 });
1375 }
1376 // catch ctrl+c, kill, and uncaught errors
1377 const removeOnExit = signalExit(close);
1378 process.on('uncaughtException', close);
1379 // only listen to stdin if it is a pipe
1380 if (!process.stdin.isTTY) {
1381 process.stdin.on('end', close); // in case we ever support stdin!
1382 }
1383 function close(err) {
1384 removeOnExit();
1385 process.removeListener('uncaughtException', close);
1386 // removing a non-existent listener is a no-op
1387 process.stdin.removeListener('end', close);
1388 if (watcher)
1389 watcher.close();
1390 if (configWatcher)
1391 configWatcher.close();
1392 if (err) {
1393 console.error(err);
1394 process.exit(1);
1395 }
1396 }
1397 try {
1398 start(initialConfigs);
1399 }
1400 catch (err) {
1401 close(err);
1402 return;
1403 }
1404 if (configFile && !configFile.startsWith('node:')) {
1405 let restarting = false;
1406 let aborted = false;
1407 let configFileData = fs__default.readFileSync(configFile, 'utf-8');
1408 const restart = () => {
1409 const newConfigFileData = fs__default.readFileSync(configFile, 'utf-8');
1410 if (newConfigFileData === configFileData)
1411 return;
1412 configFileData = newConfigFileData;
1413 if (restarting) {
1414 aborted = true;
1415 return;
1416 }
1417 restarting = true;
1418 loadConfigFile(configFile, command)
1419 .then((_configs) => {
1420 restarting = false;
1421 if (aborted) {
1422 aborted = false;
1423 restart();
1424 }
1425 else {
1426 watcher.close();
1427 start(initialConfigs);
1428 }
1429 })
1430 .catch((err) => {
1431 handleError(err, true);
1432 });
1433 };
1434 configWatcher = fs__default.watch(configFile, (event) => {
1435 if (event === 'change')
1436 restart();
1437 });
1438 }
1439}
1440
1441function runRollup(command) {
1442 let inputSource;
1443 if (command._.length > 0) {
1444 if (command.input) {
1445 handleError({
1446 code: 'DUPLICATE_IMPORT_OPTIONS',
1447 message: 'use --input, or pass input path as argument'
1448 });
1449 }
1450 inputSource = command._;
1451 }
1452 else if (typeof command.input === 'string') {
1453 inputSource = [command.input];
1454 }
1455 else {
1456 inputSource = command.input;
1457 }
1458 if (inputSource && inputSource.length > 0) {
1459 if (inputSource.some((input) => input.indexOf('=') !== -1)) {
1460 command.input = {};
1461 inputSource.forEach((input) => {
1462 const equalsIndex = input.indexOf('=');
1463 const value = input.substr(equalsIndex + 1);
1464 let key = input.substr(0, equalsIndex);
1465 if (!key)
1466 key = getAliasName(input);
1467 command.input[key] = value;
1468 });
1469 }
1470 else {
1471 command.input = inputSource;
1472 }
1473 }
1474 if (command.environment) {
1475 const environment = Array.isArray(command.environment)
1476 ? command.environment
1477 : [command.environment];
1478 environment.forEach((arg) => {
1479 arg.split(',').forEach((pair) => {
1480 const [key, value] = pair.split(':');
1481 if (value) {
1482 process.env[key] = value;
1483 }
1484 else {
1485 process.env[key] = String(true);
1486 }
1487 });
1488 });
1489 }
1490 let configFile = command.config === true ? 'rollup.config.js' : command.config;
1491 if (configFile) {
1492 if (configFile.slice(0, 5) === 'node:') {
1493 const pkgName = configFile.slice(5);
1494 try {
1495 configFile = requireRelative_1.resolve(`rollup-config-${pkgName}`, process.cwd());
1496 }
1497 catch (err) {
1498 try {
1499 configFile = requireRelative_1.resolve(pkgName, process.cwd());
1500 }
1501 catch (err) {
1502 if (err.code === 'MODULE_NOT_FOUND') {
1503 handleError({
1504 code: 'MISSING_EXTERNAL_CONFIG',
1505 message: `Could not resolve config file ${configFile}`
1506 });
1507 }
1508 throw err;
1509 }
1510 }
1511 }
1512 else {
1513 // find real path of config so it matches what Node provides to callbacks in require.extensions
1514 configFile = fs.realpathSync(configFile);
1515 }
1516 if (command.watch)
1517 process.env.ROLLUP_WATCH = 'true';
1518 loadConfigFile(configFile, command)
1519 .then(configs => execute(configFile, configs, command))
1520 .catch(handleError);
1521 }
1522 else {
1523 return execute(configFile, [{ input: null }], command);
1524 }
1525}
1526function execute(configFile, configs, command) {
1527 if (command.watch) {
1528 watch(configFile, configs, command, command.silent);
1529 }
1530 else {
1531 let promise = Promise.resolve();
1532 for (const config of configs) {
1533 promise = promise.then(() => {
1534 const warnings = batchWarnings();
1535 const { inputOptions, outputOptions, optionError } = mergeOptions({
1536 command,
1537 config,
1538 defaultOnWarnHandler: warnings.add
1539 });
1540 if (optionError)
1541 inputOptions.onwarn({ code: 'UNKNOWN_OPTION', message: optionError });
1542 return build(inputOptions, outputOptions, warnings, command.silent);
1543 });
1544 }
1545 return promise;
1546 }
1547}
1548
1549const command = minimist(process.argv.slice(2), {
1550 alias: commandAliases
1551});
1552if (command.help || (process.argv.length <= 2 && process.stdin.isTTY)) {
1553 console.log(`\n${help.replace('__VERSION__', version)}\n`);
1554}
1555else if (command.version) {
1556 console.log(`rollup v${version}`);
1557}
1558else {
1559 try {
1560 require('source-map-support').install();
1561 }
1562 catch (err) {
1563 // do nothing
1564 }
1565 runRollup(command);
1566}
1567//# sourceMappingURL=rollup.map