UNPKG

24.4 kBJavaScriptView Raw
1/*
2 @license
3 Rollup.js v2.75.7
4 Mon, 20 Jun 2022 07:24:02 GMT - commit 057171c2d3bc2092b7f543fc05ead01f12595f12
5
6 https://github.com/rollup/rollup
7
8 Released under the MIT License.
9*/
10'use strict';
11
12const require$$0 = require('path');
13const process$1 = require('process');
14const url = require('url');
15const rollup = require('./rollup.js');
16const tty = require('tty');
17const mergeOptions = require('./mergeOptions.js');
18
19function _interopNamespaceDefault(e) {
20 const n = Object.create(null, { [Symbol.toStringTag]: { value: 'Module' } });
21 if (e) {
22 for (const k in e) {
23 n[k] = e[k];
24 }
25 }
26 n.default = e;
27 return n;
28}
29
30const tty__namespace = /*#__PURE__*/_interopNamespaceDefault(tty);
31
32const env = process.env || {};
33const argv = process.argv || [];
34
35const isDisabled = "NO_COLOR" in env || argv.includes("--no-color");
36const isForced = "FORCE_COLOR" in env || argv.includes("--color");
37const isWindows = process.platform === "win32";
38const isDumbTerminal = env.TERM === "dumb";
39
40const isCompatibleTerminal =
41 tty__namespace && tty__namespace.isatty && tty__namespace.isatty(1) && env.TERM && !isDumbTerminal;
42
43const isCI =
44 "CI" in env &&
45 ("GITHUB_ACTIONS" in env || "GITLAB_CI" in env || "CIRCLECI" in env);
46
47const isColorSupported =
48 !isDisabled && (isForced || (isWindows && !isDumbTerminal) || isCompatibleTerminal || isCI);
49
50const replaceClose = (
51 index,
52 string,
53 close,
54 replace,
55 head = string.substring(0, index) + replace,
56 tail = string.substring(index + close.length),
57 next = tail.indexOf(close)
58) => head + (next < 0 ? tail : replaceClose(next, tail, close, replace));
59
60const clearBleed = (index, string, open, close, replace) =>
61 index < 0
62 ? open + string + close
63 : open + replaceClose(index, string, close, replace) + close;
64
65const filterEmpty =
66 (open, close, replace = open, at = open.length + 1) =>
67 (string) =>
68 string || !(string === "" || string === undefined)
69 ? clearBleed(
70 ("" + string).indexOf(close, at),
71 string,
72 open,
73 close,
74 replace
75 )
76 : "";
77
78const init = (open, close, replace) =>
79 filterEmpty(`\x1b[${open}m`, `\x1b[${close}m`, replace);
80
81const colors = {
82 reset: init(0, 0),
83 bold: init(1, 22, "\x1b[22m\x1b[1m"),
84 dim: init(2, 22, "\x1b[22m\x1b[2m"),
85 italic: init(3, 23),
86 underline: init(4, 24),
87 inverse: init(7, 27),
88 hidden: init(8, 28),
89 strikethrough: init(9, 29),
90 black: init(30, 39),
91 red: init(31, 39),
92 green: init(32, 39),
93 yellow: init(33, 39),
94 blue: init(34, 39),
95 magenta: init(35, 39),
96 cyan: init(36, 39),
97 white: init(37, 39),
98 gray: init(90, 39),
99 bgBlack: init(40, 49),
100 bgRed: init(41, 49),
101 bgGreen: init(42, 49),
102 bgYellow: init(43, 49),
103 bgBlue: init(44, 49),
104 bgMagenta: init(45, 49),
105 bgCyan: init(46, 49),
106 bgWhite: init(47, 49),
107 blackBright: init(90, 39),
108 redBright: init(91, 39),
109 greenBright: init(92, 39),
110 yellowBright: init(93, 39),
111 blueBright: init(94, 39),
112 magentaBright: init(95, 39),
113 cyanBright: init(96, 39),
114 whiteBright: init(97, 39),
115 bgBlackBright: init(100, 49),
116 bgRedBright: init(101, 49),
117 bgGreenBright: init(102, 49),
118 bgYellowBright: init(103, 49),
119 bgBlueBright: init(104, 49),
120 bgMagentaBright: init(105, 49),
121 bgCyanBright: init(106, 49),
122 bgWhiteBright: init(107, 49),
123};
124
125const createColors = ({ useColor = isColorSupported } = {}) =>
126 useColor
127 ? colors
128 : Object.keys(colors).reduce(
129 (colors, key) => ({ ...colors, [key]: String }),
130 {}
131 );
132
133createColors();
134
135// @see https://no-color.org
136// @see https://www.npmjs.com/package/chalk
137const { bold, cyan, dim, gray, green, red, underline, yellow } = createColors({
138 useColor: process$1.env.FORCE_COLOR !== '0' && !process$1.env.NO_COLOR
139});
140
141// log to stderr to keep `rollup main.js > bundle.js` from breaking
142const stderr = (...args) => process$1.stderr.write(`${args.join('')}\n`);
143function handleError(err, recover = false) {
144 let description = err.message || err;
145 if (err.name)
146 description = `${err.name}: ${description}`;
147 const message = (err.plugin ? `(plugin ${err.plugin}) ${description}` : description) || err;
148 stderr(bold(red(`[!] ${bold(message.toString())}`)));
149 if (err.url) {
150 stderr(cyan(err.url));
151 }
152 if (err.loc) {
153 stderr(`${rollup.relativeId((err.loc.file || err.id))} (${err.loc.line}:${err.loc.column})`);
154 }
155 else if (err.id) {
156 stderr(rollup.relativeId(err.id));
157 }
158 if (err.frame) {
159 stderr(dim(err.frame));
160 }
161 if (err.stack) {
162 stderr(dim(err.stack));
163 }
164 stderr('');
165 if (!recover)
166 process$1.exit(1);
167}
168
169function batchWarnings() {
170 let count = 0;
171 const deferredWarnings = new Map();
172 let warningOccurred = false;
173 return {
174 add(warning) {
175 count += 1;
176 warningOccurred = true;
177 if (warning.code in deferredHandlers) {
178 rollup.getOrCreate(deferredWarnings, warning.code, () => []).push(warning);
179 }
180 else if (warning.code in immediateHandlers) {
181 immediateHandlers[warning.code](warning);
182 }
183 else {
184 title(warning.message);
185 if (warning.url)
186 info(warning.url);
187 const id = (warning.loc && warning.loc.file) || warning.id;
188 if (id) {
189 const loc = warning.loc
190 ? `${rollup.relativeId(id)} (${warning.loc.line}:${warning.loc.column})`
191 : rollup.relativeId(id);
192 stderr(bold(rollup.relativeId(loc)));
193 }
194 if (warning.frame)
195 info(warning.frame);
196 }
197 },
198 get count() {
199 return count;
200 },
201 flush() {
202 if (count === 0)
203 return;
204 const codes = Array.from(deferredWarnings.keys()).sort((a, b) => deferredWarnings.get(b).length - deferredWarnings.get(a).length);
205 for (const code of codes) {
206 deferredHandlers[code](deferredWarnings.get(code));
207 }
208 deferredWarnings.clear();
209 count = 0;
210 },
211 get warningOccurred() {
212 return warningOccurred;
213 }
214 };
215}
216const immediateHandlers = {
217 MISSING_NODE_BUILTINS(warning) {
218 title(`Missing shims for Node.js built-ins`);
219 stderr(`Creating a browser bundle that depends on ${rollup.printQuotedStringList(warning.modules)}. You might need to include https://github.com/FredKSchott/rollup-plugin-polyfill-node`);
220 },
221 UNKNOWN_OPTION(warning) {
222 title(`You have passed an unrecognized option`);
223 stderr(warning.message);
224 }
225};
226const deferredHandlers = {
227 CIRCULAR_DEPENDENCY(warnings) {
228 title(`Circular dependenc${warnings.length > 1 ? 'ies' : 'y'}`);
229 const displayed = warnings.length > 5 ? warnings.slice(0, 3) : warnings;
230 for (const warning of displayed) {
231 stderr(warning.cycle.join(' -> '));
232 }
233 if (warnings.length > displayed.length) {
234 stderr(`...and ${warnings.length - displayed.length} more`);
235 }
236 },
237 EMPTY_BUNDLE(warnings) {
238 title(`Generated${warnings.length === 1 ? ' an' : ''} empty ${warnings.length > 1 ? 'chunks' : 'chunk'}`);
239 stderr(warnings.map(warning => warning.chunkName).join(', '));
240 },
241 EVAL(warnings) {
242 title('Use of eval is strongly discouraged');
243 info('https://rollupjs.org/guide/en/#avoiding-eval');
244 showTruncatedWarnings(warnings);
245 },
246 MISSING_EXPORT(warnings) {
247 title('Missing exports');
248 info('https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module');
249 for (const warning of warnings) {
250 stderr(bold(warning.importer));
251 stderr(`${warning.missing} is not exported by ${warning.exporter}`);
252 stderr(gray(warning.frame));
253 }
254 },
255 MISSING_GLOBAL_NAME(warnings) {
256 title(`Missing global variable ${warnings.length > 1 ? 'names' : 'name'}`);
257 stderr(`Use output.globals to specify browser global variable names corresponding to external modules`);
258 for (const warning of warnings) {
259 stderr(`${bold(warning.source)} (guessing '${warning.guess}')`);
260 }
261 },
262 MIXED_EXPORTS(warnings) {
263 title('Mixing named and default exports');
264 info(`https://rollupjs.org/guide/en/#outputexports`);
265 stderr(bold('The following entry modules are using named and default exports together:'));
266 warnings.sort((a, b) => (a.id < b.id ? -1 : 1));
267 const displayedWarnings = warnings.length > 5 ? warnings.slice(0, 3) : warnings;
268 for (const warning of displayedWarnings) {
269 stderr(rollup.relativeId(warning.id));
270 }
271 if (displayedWarnings.length < warnings.length) {
272 stderr(`...and ${warnings.length - displayedWarnings.length} other entry modules`);
273 }
274 stderr(`\nConsumers of your bundle will have to use chunk['default'] to access their default export, which may not be what you want. Use \`output.exports: 'named'\` to disable this warning`);
275 },
276 NAMESPACE_CONFLICT(warnings) {
277 title(`Conflicting re-exports`);
278 for (const warning of warnings) {
279 stderr(`"${bold(rollup.relativeId(warning.reexporter))}" re-exports "${warning.name}" from both "${rollup.relativeId(warning.sources[0])}" and "${rollup.relativeId(warning.sources[1])}" (will be ignored)`);
280 }
281 },
282 NON_EXISTENT_EXPORT(warnings) {
283 title(`Import of non-existent ${warnings.length > 1 ? 'exports' : 'export'}`);
284 showTruncatedWarnings(warnings);
285 },
286 PLUGIN_WARNING(warnings) {
287 var _a;
288 const nestedByPlugin = nest(warnings, 'plugin');
289 for (const { key: plugin, items } of nestedByPlugin) {
290 const nestedByMessage = nest(items, 'message');
291 let lastUrl = '';
292 for (const { key: message, items } of nestedByMessage) {
293 title(`Plugin ${plugin}: ${message}`);
294 for (const warning of items) {
295 if (warning.url && warning.url !== lastUrl)
296 info((lastUrl = warning.url));
297 const id = warning.id || ((_a = warning.loc) === null || _a === void 0 ? void 0 : _a.file);
298 if (id) {
299 let loc = rollup.relativeId(id);
300 if (warning.loc) {
301 loc += `: (${warning.loc.line}:${warning.loc.column})`;
302 }
303 stderr(bold(loc));
304 }
305 if (warning.frame)
306 info(warning.frame);
307 }
308 }
309 }
310 },
311 SOURCEMAP_BROKEN(warnings) {
312 title(`Broken sourcemap`);
313 info('https://rollupjs.org/guide/en/#warning-sourcemap-is-likely-to-be-incorrect');
314 const plugins = [...new Set(warnings.map(({ plugin }) => plugin).filter(Boolean))];
315 stderr(`Plugins that transform code (such as ${rollup.printQuotedStringList(plugins)}) should generate accompanying sourcemaps`);
316 },
317 THIS_IS_UNDEFINED(warnings) {
318 title('`this` has been rewritten to `undefined`');
319 info('https://rollupjs.org/guide/en/#error-this-is-undefined');
320 showTruncatedWarnings(warnings);
321 },
322 UNRESOLVED_IMPORT(warnings) {
323 title('Unresolved dependencies');
324 info('https://rollupjs.org/guide/en/#warning-treating-module-as-external-dependency');
325 const dependencies = new Map();
326 for (const warning of warnings) {
327 rollup.getOrCreate(dependencies, warning.source, () => []).push(warning.importer);
328 }
329 for (const [dependency, importers] of dependencies) {
330 stderr(`${bold(dependency)} (imported by ${importers.join(', ')})`);
331 }
332 },
333 UNUSED_EXTERNAL_IMPORT(warnings) {
334 title('Unused external imports');
335 for (const warning of warnings) {
336 stderr(warning.names +
337 ' imported from external module "' +
338 warning.source +
339 '" but never used in ' +
340 rollup.printQuotedStringList(warning.sources.map(id => rollup.relativeId(id))));
341 }
342 }
343};
344function title(str) {
345 stderr(bold(yellow(`(!) ${str}`)));
346}
347function info(url) {
348 stderr(gray(url));
349}
350function nest(array, prop) {
351 const nested = [];
352 const lookup = new Map();
353 for (const item of array) {
354 const key = item[prop];
355 rollup.getOrCreate(lookup, key, () => {
356 const items = {
357 items: [],
358 key
359 };
360 nested.push(items);
361 return items;
362 }).items.push(item);
363 }
364 return nested;
365}
366function showTruncatedWarnings(warnings) {
367 const nestedByModule = nest(warnings, 'id');
368 const displayedByModule = nestedByModule.length > 5 ? nestedByModule.slice(0, 3) : nestedByModule;
369 for (const { key: id, items } of displayedByModule) {
370 stderr(bold(rollup.relativeId(id)));
371 stderr(gray(items[0].frame));
372 if (items.length > 1) {
373 stderr(`...and ${items.length - 1} other ${items.length > 2 ? 'occurrences' : 'occurrence'}`);
374 }
375 }
376 if (nestedByModule.length > displayedByModule.length) {
377 stderr(`\n...and ${nestedByModule.length - displayedByModule.length} other files`);
378 }
379}
380
381const stdinName = '-';
382let stdinResult = null;
383function stdinPlugin(arg) {
384 const suffix = typeof arg == 'string' && arg.length ? '.' + arg : '';
385 return {
386 load(id) {
387 if (id === stdinName || id.startsWith(stdinName + '.')) {
388 return stdinResult || (stdinResult = readStdin());
389 }
390 },
391 name: 'stdin',
392 resolveId(id) {
393 if (id === stdinName) {
394 return id + suffix;
395 }
396 }
397 };
398}
399function readStdin() {
400 return new Promise((resolve, reject) => {
401 const chunks = [];
402 process$1.stdin.setEncoding('utf8');
403 process$1.stdin
404 .on('data', chunk => chunks.push(chunk))
405 .on('end', () => {
406 const result = chunks.join('');
407 resolve(result);
408 })
409 .on('error', err => {
410 reject(err);
411 });
412 });
413}
414
415function waitForInputPlugin() {
416 return {
417 async buildStart(options) {
418 const inputSpecifiers = Array.isArray(options.input)
419 ? options.input
420 : Object.keys(options.input);
421 let lastAwaitedSpecifier = null;
422 checkSpecifiers: while (true) {
423 for (const specifier of inputSpecifiers) {
424 if ((await this.resolve(specifier)) === null) {
425 if (lastAwaitedSpecifier !== specifier) {
426 stderr(`waiting for input ${bold(specifier)}...`);
427 lastAwaitedSpecifier = specifier;
428 }
429 await new Promise(resolve => setTimeout(resolve, 500));
430 continue checkSpecifiers;
431 }
432 }
433 break;
434 }
435 },
436 name: 'wait-for-input'
437 };
438}
439
440async function addCommandPluginsToInputOptions(inputOptions, command) {
441 if (command.stdin !== false) {
442 inputOptions.plugins.push(stdinPlugin(command.stdin));
443 }
444 if (command.waitForBundleInput === true) {
445 inputOptions.plugins.push(waitForInputPlugin());
446 }
447 await addPluginsFromCommandOption(command.plugin, inputOptions);
448}
449async function addPluginsFromCommandOption(commandPlugin, inputOptions) {
450 if (commandPlugin) {
451 const plugins = Array.isArray(commandPlugin) ? commandPlugin : [commandPlugin];
452 for (const plugin of plugins) {
453 if (/[={}]/.test(plugin)) {
454 // -p plugin=value
455 // -p "{transform(c,i){...}}"
456 await loadAndRegisterPlugin(inputOptions, plugin);
457 }
458 else {
459 // split out plugins joined by commas
460 // -p node-resolve,commonjs,buble
461 for (const p of plugin.split(',')) {
462 await loadAndRegisterPlugin(inputOptions, p);
463 }
464 }
465 }
466 }
467}
468async function loadAndRegisterPlugin(inputOptions, pluginText) {
469 let plugin = null;
470 let pluginArg = undefined;
471 if (pluginText[0] === '{') {
472 // -p "{transform(c,i){...}}"
473 plugin = new Function('return ' + pluginText);
474 }
475 else {
476 const match = pluginText.match(/^([@./\\\w|^{}-]+)(=(.*))?$/);
477 if (match) {
478 // -p plugin
479 // -p plugin=arg
480 pluginText = match[1];
481 pluginArg = new Function('return ' + match[3])();
482 }
483 else {
484 throw new Error(`Invalid --plugin argument format: ${JSON.stringify(pluginText)}`);
485 }
486 if (!/^\.|^rollup-plugin-|[@/\\]/.test(pluginText)) {
487 // Try using plugin prefix variations first if applicable.
488 // Prefix order is significant - left has higher precedence.
489 for (const prefix of ['@rollup/plugin-', 'rollup-plugin-']) {
490 try {
491 plugin = await requireOrImport(prefix + pluginText);
492 break;
493 }
494 catch (_a) {
495 // if this does not work, we try requiring the actual name below
496 }
497 }
498 }
499 if (!plugin) {
500 try {
501 if (pluginText[0] == '.')
502 pluginText = require$$0.resolve(pluginText);
503 plugin = await requireOrImport(pluginText);
504 }
505 catch (err) {
506 throw new Error(`Cannot load plugin "${pluginText}": ${err.message}.`);
507 }
508 }
509 }
510 // some plugins do not use `module.exports` for their entry point,
511 // in which case we try the named default export and the plugin name
512 if (typeof plugin === 'object') {
513 plugin = plugin.default || plugin[getCamelizedPluginBaseName(pluginText)];
514 }
515 if (!plugin) {
516 throw new Error(`Cannot find entry for plugin "${pluginText}". The plugin needs to export a function either as "default" or "${getCamelizedPluginBaseName(pluginText)}" for Rollup to recognize it.`);
517 }
518 inputOptions.plugins.push(typeof plugin === 'function' ? plugin.call(plugin, pluginArg) : plugin);
519}
520function getCamelizedPluginBaseName(pluginText) {
521 var _a;
522 return (((_a = pluginText.match(/(@rollup\/plugin-|rollup-plugin-)(.+)$/)) === null || _a === void 0 ? void 0 : _a[2]) || pluginText)
523 .split(/[\\/]/)
524 .slice(-1)[0]
525 .split('.')[0]
526 .split('-')
527 .map((part, index) => (index === 0 || !part ? part : part[0].toUpperCase() + part.slice(1)))
528 .join('');
529}
530async function requireOrImport(pluginPath) {
531 try {
532 return require(pluginPath);
533 }
534 catch (_a) {
535 return import(pluginPath);
536 }
537}
538
539function supportsNativeESM() {
540 return Number(/^v(\d+)/.exec(process$1.version)[1]) >= 13;
541}
542async function loadAndParseConfigFile(fileName, commandOptions = {}) {
543 const configs = await loadConfigFile(fileName, commandOptions);
544 const warnings = batchWarnings();
545 try {
546 const normalizedConfigs = [];
547 for (const config of configs) {
548 const options = mergeOptions.mergeOptions(config, commandOptions, warnings.add);
549 await addCommandPluginsToInputOptions(options, commandOptions);
550 normalizedConfigs.push(options);
551 }
552 return { options: normalizedConfigs, warnings };
553 }
554 catch (err) {
555 warnings.flush();
556 throw err;
557 }
558}
559async function loadConfigFile(fileName, commandOptions) {
560 const extension = require$$0.extname(fileName);
561 const configFileExport = commandOptions.configPlugin ||
562 !(extension === '.cjs' || (extension === '.mjs' && supportsNativeESM()))
563 ? await getDefaultFromTranspiledConfigFile(fileName, commandOptions)
564 : extension === '.cjs'
565 ? getDefaultFromCjs(require(fileName))
566 : (await import(url.pathToFileURL(fileName).href)).default;
567 return getConfigList(configFileExport, commandOptions);
568}
569function getDefaultFromCjs(namespace) {
570 return namespace.__esModule ? namespace.default : namespace;
571}
572async function getDefaultFromTranspiledConfigFile(fileName, commandOptions) {
573 const warnings = batchWarnings();
574 const inputOptions = {
575 external: (id) => (id[0] !== '.' && !require$$0.isAbsolute(id)) || id.slice(-5, id.length) === '.json',
576 input: fileName,
577 onwarn: warnings.add,
578 plugins: [],
579 treeshake: false
580 };
581 await addPluginsFromCommandOption(commandOptions.configPlugin, inputOptions);
582 const bundle = await rollup.rollup(inputOptions);
583 if (!commandOptions.silent && warnings.count > 0) {
584 stderr(bold(`loaded ${rollup.relativeId(fileName)} with warnings`));
585 warnings.flush();
586 }
587 const { output: [{ code }] } = await bundle.generate({
588 exports: 'named',
589 format: 'cjs',
590 plugins: [
591 {
592 name: 'transpile-import-meta',
593 resolveImportMeta(property, { moduleId }) {
594 if (property === 'url') {
595 return `'${url.pathToFileURL(moduleId).href}'`;
596 }
597 if (property == null) {
598 return `{url:'${url.pathToFileURL(moduleId).href}'}`;
599 }
600 }
601 }
602 ]
603 });
604 return loadConfigFromBundledFile(fileName, code);
605}
606function loadConfigFromBundledFile(fileName, bundledCode) {
607 const resolvedFileName = require.resolve(fileName);
608 const extension = require$$0.extname(resolvedFileName);
609 const defaultLoader = require.extensions[extension];
610 require.extensions[extension] = (module, requiredFileName) => {
611 if (requiredFileName === resolvedFileName) {
612 module._compile(bundledCode, requiredFileName);
613 }
614 else {
615 if (defaultLoader) {
616 defaultLoader(module, requiredFileName);
617 }
618 }
619 };
620 delete require.cache[resolvedFileName];
621 try {
622 const config = getDefaultFromCjs(require(fileName));
623 require.extensions[extension] = defaultLoader;
624 return config;
625 }
626 catch (err) {
627 if (err.code === 'ERR_REQUIRE_ESM') {
628 return rollup.error({
629 code: 'TRANSPILED_ESM_CONFIG',
630 message: `While loading the Rollup configuration from "${rollup.relativeId(fileName)}", Node tried to require an ES module from a CommonJS file, which is not supported. A common cause is if there is a package.json file with "type": "module" in the same folder. You can try to fix this by changing the extension of your configuration file to ".cjs" or ".mjs" depending on the content, which will prevent Rollup from trying to preprocess the file but rather hand it to Node directly.`,
631 url: 'https://rollupjs.org/guide/en/#using-untranspiled-config-files'
632 });
633 }
634 throw err;
635 }
636}
637async function getConfigList(configFileExport, commandOptions) {
638 const config = await (typeof configFileExport === 'function'
639 ? configFileExport(commandOptions)
640 : configFileExport);
641 if (Object.keys(config).length === 0) {
642 return rollup.error({
643 code: 'MISSING_CONFIG',
644 message: 'Config file must export an options object, or an array of options objects',
645 url: 'https://rollupjs.org/guide/en/#configuration-files'
646 });
647 }
648 return Array.isArray(config) ? config : [config];
649}
650
651exports.addCommandPluginsToInputOptions = addCommandPluginsToInputOptions;
652exports.batchWarnings = batchWarnings;
653exports.bold = bold;
654exports.cyan = cyan;
655exports.green = green;
656exports.handleError = handleError;
657exports.loadAndParseConfigFile = loadAndParseConfigFile;
658exports.stderr = stderr;
659exports.stdinName = stdinName;
660exports.underline = underline;
661//# sourceMappingURL=loadConfigFile.js.map