UNPKG

21.4 kBJavaScriptView Raw
1/*
2 @license
3 Rollup.js v2.33.1
4 Mon, 02 Nov 2020 06:50:50 GMT - commit d861c91c068bc4e64d84db3b84232d3fb7f1d073
5
6
7 https://github.com/rollup/rollup
8
9 Released under the MIT License.
10*/
11'use strict';
12
13var rollup = require('./rollup.js');
14var fs = require('fs');
15var sysPath = require('path');
16var mergeOptions = require('./mergeOptions.js');
17var url = require('url');
18
19let enabled =
20 !("NO_COLOR" in process.env) &&
21 ("FORCE_COLOR" in process.env ||
22 process.platform === "win32" ||
23 (process.stdout != null &&
24 process.stdout.isTTY &&
25 process.env.TERM &&
26 process.env.TERM !== "dumb"));
27
28const raw = (open, close, searchRegex, replaceValue) => (s) =>
29 enabled
30 ? open +
31 (~(s += "").indexOf(close, 4) // skip opening \x1b[
32 ? s.replace(searchRegex, replaceValue)
33 : s) +
34 close
35 : s;
36
37const init = (open, close) => {
38 return raw(
39 `\x1b[${open}m`,
40 `\x1b[${close}m`,
41 new RegExp(`\\x1b\\[${close}m`, "g"),
42 `\x1b[${open}m`
43 )
44};
45
46const options = Object.defineProperty({}, "enabled", {
47 get: () => enabled,
48 set: (value) => (enabled = value),
49});
50const bold = raw("\x1b[1m", "\x1b[22m", /\x1b\[22m/g, "\x1b[22m\x1b[1m");
51const dim = raw("\x1b[2m", "\x1b[22m", /\x1b\[22m/g, "\x1b[22m\x1b[2m");
52const underline = init(4, 24);
53const red = init(31, 39);
54const green = init(32, 39);
55const yellow = init(33, 39);
56const cyan = init(36, 39);
57const gray = init(90, 39);
58
59// @see https://no-color.org
60// @see https://www.npmjs.com/package/chalk
61if (process.env.FORCE_COLOR === '0' || process.env.NO_COLOR) {
62 options.enabled = false;
63}
64// log to stderr to keep `rollup main.js > bundle.js` from breaking
65const stderr = console.error.bind(console);
66function handleError(err, recover = false) {
67 let description = err.message || err;
68 if (err.name)
69 description = `${err.name}: ${description}`;
70 const message = (err.plugin ? `(plugin ${err.plugin}) ${description}` : description) || err;
71 stderr(bold(red(`[!] ${bold(message.toString())}`)));
72 if (err.url) {
73 stderr(cyan(err.url));
74 }
75 if (err.loc) {
76 stderr(`${rollup.relativeId((err.loc.file || err.id))} (${err.loc.line}:${err.loc.column})`);
77 }
78 else if (err.id) {
79 stderr(rollup.relativeId(err.id));
80 }
81 if (err.frame) {
82 stderr(dim(err.frame));
83 }
84 if (err.stack) {
85 stderr(dim(err.stack));
86 }
87 stderr('');
88 if (!recover)
89 process.exit(1);
90}
91
92function batchWarnings() {
93 let count = 0;
94 let deferredWarnings = new Map();
95 let warningOccurred = false;
96 return {
97 get count() {
98 return count;
99 },
100 get warningOccurred() {
101 return warningOccurred;
102 },
103 add: (warning) => {
104 count += 1;
105 warningOccurred = true;
106 if (warning.code in deferredHandlers) {
107 rollup.getOrCreate(deferredWarnings, warning.code, () => []).push(warning);
108 }
109 else if (warning.code in immediateHandlers) {
110 immediateHandlers[warning.code](warning);
111 }
112 else {
113 title(warning.message);
114 if (warning.url)
115 info(warning.url);
116 const id = (warning.loc && warning.loc.file) || warning.id;
117 if (id) {
118 const loc = warning.loc
119 ? `${rollup.relativeId(id)}: (${warning.loc.line}:${warning.loc.column})`
120 : rollup.relativeId(id);
121 stderr(bold(rollup.relativeId(loc)));
122 }
123 if (warning.frame)
124 info(warning.frame);
125 }
126 },
127 flush: () => {
128 if (count === 0)
129 return;
130 const codes = Array.from(deferredWarnings.keys()).sort((a, b) => deferredWarnings.get(b).length - deferredWarnings.get(a).length);
131 for (const code of codes) {
132 deferredHandlers[code](deferredWarnings.get(code));
133 }
134 deferredWarnings = new Map();
135 count = 0;
136 }
137 };
138}
139const immediateHandlers = {
140 UNKNOWN_OPTION: warning => {
141 title(`You have passed an unrecognized option`);
142 stderr(warning.message);
143 },
144 MISSING_NODE_BUILTINS: warning => {
145 title(`Missing shims for Node.js built-ins`);
146 const detail = warning.modules.length === 1
147 ? `'${warning.modules[0]}'`
148 : `${warning
149 .modules.slice(0, -1)
150 .map((name) => `'${name}'`)
151 .join(', ')} and '${warning.modules.slice(-1)}'`;
152 stderr(`Creating a browser bundle that depends on ${detail}. You might need to include https://github.com/ionic-team/rollup-plugin-node-polyfills`);
153 }
154};
155const deferredHandlers = {
156 CIRCULAR_DEPENDENCY(warnings) {
157 title(`Circular dependenc${warnings.length > 1 ? 'ies' : 'y'}`);
158 const displayed = warnings.length > 5 ? warnings.slice(0, 3) : warnings;
159 for (const warning of displayed) {
160 stderr(warning.cycle.join(' -> '));
161 }
162 if (warnings.length > displayed.length) {
163 stderr(`...and ${warnings.length - displayed.length} more`);
164 }
165 },
166 EMPTY_BUNDLE(warnings) {
167 title(`Generated${warnings.length === 1 ? ' an' : ''} empty ${warnings.length > 1 ? 'chunks' : 'chunk'}`);
168 stderr(warnings.map(warning => warning.chunkName).join(', '));
169 },
170 EVAL(warnings) {
171 title('Use of eval is strongly discouraged');
172 info('https://rollupjs.org/guide/en/#avoiding-eval');
173 showTruncatedWarnings(warnings);
174 },
175 MISSING_EXPORT(warnings) {
176 title('Missing exports');
177 info('https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module');
178 for (const warning of warnings) {
179 stderr(bold(warning.importer));
180 stderr(`${warning.missing} is not exported by ${warning.exporter}`);
181 stderr(gray(warning.frame));
182 }
183 },
184 MISSING_GLOBAL_NAME(warnings) {
185 title(`Missing global variable ${warnings.length > 1 ? 'names' : 'name'}`);
186 stderr(`Use output.globals to specify browser global variable names corresponding to external modules`);
187 for (const warning of warnings) {
188 stderr(`${bold(warning.source)} (guessing '${warning.guess}')`);
189 }
190 },
191 MIXED_EXPORTS: warnings => {
192 title('Mixing named and default exports');
193 info(`https://rollupjs.org/guide/en/#outputexports`);
194 stderr(bold('The following entry modules are using named and default exports together:'));
195 const displayedWarnings = warnings.length > 5 ? warnings.slice(0, 3) : warnings;
196 for (const warning of displayedWarnings) {
197 stderr(rollup.relativeId(warning.id));
198 }
199 if (displayedWarnings.length < warnings.length) {
200 stderr(`...and ${warnings.length - displayedWarnings.length} other entry modules`);
201 }
202 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`);
203 },
204 NAMESPACE_CONFLICT(warnings) {
205 title(`Conflicting re-exports`);
206 for (const warning of warnings) {
207 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)`);
208 }
209 },
210 NON_EXISTENT_EXPORT(warnings) {
211 title(`Import of non-existent ${warnings.length > 1 ? 'exports' : 'export'}`);
212 showTruncatedWarnings(warnings);
213 },
214 PLUGIN_WARNING(warnings) {
215 var _a;
216 const nestedByPlugin = nest(warnings, 'plugin');
217 for (const { key: plugin, items } of nestedByPlugin) {
218 const nestedByMessage = nest(items, 'message');
219 let lastUrl = '';
220 for (const { key: message, items } of nestedByMessage) {
221 title(`Plugin ${plugin}: ${message}`);
222 for (const warning of items) {
223 if (warning.url && warning.url !== lastUrl)
224 info((lastUrl = warning.url));
225 const id = warning.id || ((_a = warning.loc) === null || _a === void 0 ? void 0 : _a.file);
226 if (id) {
227 let loc = rollup.relativeId(id);
228 if (warning.loc) {
229 loc += `: (${warning.loc.line}:${warning.loc.column})`;
230 }
231 stderr(bold(loc));
232 }
233 if (warning.frame)
234 info(warning.frame);
235 }
236 }
237 }
238 },
239 SOURCEMAP_BROKEN(warnings) {
240 title(`Broken sourcemap`);
241 info('https://rollupjs.org/guide/en/#warning-sourcemap-is-likely-to-be-incorrect');
242 const plugins = Array.from(new Set(warnings.map(w => w.plugin).filter(Boolean)));
243 const detail = plugins.length > 1
244 ? ` (such as ${plugins
245 .slice(0, -1)
246 .map(p => `'${p}'`)
247 .join(', ')} and '${plugins.slice(-1)}')`
248 : ` (such as '${plugins[0]}')`;
249 stderr(`Plugins that transform code${detail} should generate accompanying sourcemaps`);
250 },
251 THIS_IS_UNDEFINED(warnings) {
252 title('`this` has been rewritten to `undefined`');
253 info('https://rollupjs.org/guide/en/#error-this-is-undefined');
254 showTruncatedWarnings(warnings);
255 },
256 UNRESOLVED_IMPORT(warnings) {
257 title('Unresolved dependencies');
258 info('https://rollupjs.org/guide/en/#warning-treating-module-as-external-dependency');
259 const dependencies = new Map();
260 for (const warning of warnings) {
261 rollup.getOrCreate(dependencies, warning.source, () => []).push(warning.importer);
262 }
263 for (const dependency of dependencies.keys()) {
264 const importers = dependencies.get(dependency);
265 stderr(`${bold(dependency)} (imported by ${importers.join(', ')})`);
266 }
267 },
268 UNUSED_EXTERNAL_IMPORT(warnings) {
269 title('Unused external imports');
270 for (const warning of warnings) {
271 stderr(`${warning.names} imported from external module '${warning.source}' but never used`);
272 }
273 }
274};
275function title(str) {
276 stderr(bold(yellow(`(!) ${str}`)));
277}
278function info(url) {
279 stderr(gray(url));
280}
281function nest(array, prop) {
282 const nested = [];
283 const lookup = new Map();
284 for (const item of array) {
285 const key = item[prop];
286 rollup.getOrCreate(lookup, key, () => {
287 const items = {
288 items: [],
289 key
290 };
291 nested.push(items);
292 return items;
293 }).items.push(item);
294 }
295 return nested;
296}
297function showTruncatedWarnings(warnings) {
298 const nestedByModule = nest(warnings, 'id');
299 const displayedByModule = nestedByModule.length > 5 ? nestedByModule.slice(0, 3) : nestedByModule;
300 for (const { key: id, items } of displayedByModule) {
301 stderr(bold(rollup.relativeId(id)));
302 stderr(gray(items[0].frame));
303 if (items.length > 1) {
304 stderr(`...and ${items.length - 1} other ${items.length > 2 ? 'occurrences' : 'occurrence'}`);
305 }
306 }
307 if (nestedByModule.length > displayedByModule.length) {
308 stderr(`\n...and ${nestedByModule.length - displayedByModule.length} other files`);
309 }
310}
311
312const stdinName = '-';
313let stdinResult = null;
314function stdinPlugin(arg) {
315 const suffix = typeof arg == 'string' && arg.length ? '.' + arg : '';
316 return {
317 name: 'stdin',
318 resolveId(id) {
319 if (id === stdinName) {
320 return id + suffix;
321 }
322 },
323 load(id) {
324 if (id === stdinName || id.startsWith(stdinName + '.')) {
325 return stdinResult || (stdinResult = readStdin());
326 }
327 }
328 };
329}
330function readStdin() {
331 return new Promise((resolve, reject) => {
332 const chunks = [];
333 process.stdin.setEncoding('utf8');
334 process.stdin
335 .on('data', chunk => chunks.push(chunk))
336 .on('end', () => {
337 const result = chunks.join('');
338 resolve(result);
339 })
340 .on('error', err => {
341 reject(err);
342 });
343 });
344}
345
346function waitForInputPlugin() {
347 return {
348 name: 'wait-for-input',
349 async buildStart(options) {
350 const inputSpecifiers = Array.isArray(options.input)
351 ? options.input
352 : Object.keys(options.input);
353 let lastAwaitedSpecifier = null;
354 checkSpecifiers: while (true) {
355 for (const specifier of inputSpecifiers) {
356 if ((await this.resolve(specifier)) === null) {
357 if (lastAwaitedSpecifier !== specifier) {
358 stderr(`waiting for input ${bold(specifier)}...`);
359 lastAwaitedSpecifier = specifier;
360 }
361 await new Promise(resolve => setTimeout(resolve, 500));
362 continue checkSpecifiers;
363 }
364 }
365 break;
366 }
367 }
368 };
369}
370
371function addCommandPluginsToInputOptions(inputOptions, command) {
372 if (command.stdin !== false) {
373 inputOptions.plugins.push(stdinPlugin(command.stdin));
374 }
375 if (command.waitForBundleInput === true) {
376 inputOptions.plugins.push(waitForInputPlugin());
377 }
378 const commandPlugin = command.plugin;
379 if (commandPlugin) {
380 const plugins = Array.isArray(commandPlugin) ? commandPlugin : [commandPlugin];
381 for (const plugin of plugins) {
382 if (/[={}]/.test(plugin)) {
383 // -p plugin=value
384 // -p "{transform(c,i){...}}"
385 loadAndRegisterPlugin(inputOptions, plugin);
386 }
387 else {
388 // split out plugins joined by commas
389 // -p node-resolve,commonjs,buble
390 plugin.split(',').forEach((plugin) => loadAndRegisterPlugin(inputOptions, plugin));
391 }
392 }
393 }
394}
395function loadAndRegisterPlugin(inputOptions, pluginText) {
396 let plugin = null;
397 let pluginArg = undefined;
398 if (pluginText[0] === '{') {
399 // -p "{transform(c,i){...}}"
400 plugin = new Function('return ' + pluginText);
401 }
402 else {
403 const match = pluginText.match(/^([@.\/\\\w|^{}-]+)(=(.*))?$/);
404 if (match) {
405 // -p plugin
406 // -p plugin=arg
407 pluginText = match[1];
408 pluginArg = new Function('return ' + match[3])();
409 }
410 else {
411 throw new Error(`Invalid --plugin argument format: ${JSON.stringify(pluginText)}`);
412 }
413 if (!/^\.|^rollup-plugin-|[@\/\\]/.test(pluginText)) {
414 // Try using plugin prefix variations first if applicable.
415 // Prefix order is significant - left has higher precedence.
416 for (const prefix of ['@rollup/plugin-', 'rollup-plugin-']) {
417 try {
418 plugin = require(prefix + pluginText);
419 break;
420 }
421 catch (ex) {
422 // if this does not work, we try requiring the actual name below
423 }
424 }
425 }
426 if (!plugin) {
427 try {
428 if (pluginText[0] == '.')
429 pluginText = sysPath.resolve(pluginText);
430 plugin = require(pluginText);
431 }
432 catch (ex) {
433 throw new Error(`Cannot load plugin "${pluginText}": ${ex.message}.`);
434 }
435 }
436 }
437 // some plugins do not use `module.exports` for their entry point,
438 // in which case we try the named default export and the plugin name
439 if (typeof plugin === 'object') {
440 plugin = plugin.default || plugin[getCamelizedPluginBaseName(pluginText)];
441 }
442 if (!plugin) {
443 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.`);
444 }
445 inputOptions.plugins.push(typeof plugin === 'function' ? plugin.call(plugin, pluginArg) : plugin);
446}
447function getCamelizedPluginBaseName(pluginText) {
448 var _a;
449 return (((_a = pluginText.match(/(@rollup\/plugin-|rollup-plugin-)(.+)$/)) === null || _a === void 0 ? void 0 : _a[2]) || pluginText)
450 .split(/[\\/]/)
451 .slice(-1)[0]
452 .split('.')[0]
453 .split('-')
454 .map((part, index) => (index === 0 || !part ? part : part[0].toUpperCase() + part.slice(1)))
455 .join('');
456}
457
458function supportsNativeESM() {
459 return Number(/^v(\d+)/.exec(process.version)[1]) >= 13;
460}
461async function loadAndParseConfigFile(fileName, commandOptions = {}) {
462 const configs = await loadConfigFile(fileName, commandOptions);
463 const warnings = batchWarnings();
464 try {
465 const normalizedConfigs = configs.map(config => {
466 const options = mergeOptions.mergeOptions(config, commandOptions, warnings.add);
467 addCommandPluginsToInputOptions(options, commandOptions);
468 return options;
469 });
470 return { options: normalizedConfigs, warnings };
471 }
472 catch (err) {
473 warnings.flush();
474 throw err;
475 }
476}
477async function loadConfigFile(fileName, commandOptions) {
478 const extension = sysPath.extname(fileName);
479 const configFileExport = extension === '.mjs' && supportsNativeESM()
480 ? (await import(url.pathToFileURL(fileName).href)).default
481 : extension === '.cjs'
482 ? getDefaultFromCjs(require(fileName))
483 : await getDefaultFromTranspiledConfigFile(fileName, commandOptions.silent);
484 return getConfigList(configFileExport, commandOptions);
485}
486function getDefaultFromCjs(namespace) {
487 return namespace.__esModule ? namespace.default : namespace;
488}
489async function getDefaultFromTranspiledConfigFile(fileName, silent) {
490 const warnings = batchWarnings();
491 const bundle = await rollup.rollup({
492 external: (id) => (id[0] !== '.' && !sysPath.isAbsolute(id)) || id.slice(-5, id.length) === '.json',
493 input: fileName,
494 onwarn: warnings.add,
495 treeshake: false
496 });
497 if (!silent && warnings.count > 0) {
498 stderr(bold(`loaded ${rollup.relativeId(fileName)} with warnings`));
499 warnings.flush();
500 }
501 const { output: [{ code }] } = await bundle.generate({
502 exports: 'named',
503 format: 'cjs'
504 });
505 return loadConfigFromBundledFile(fileName, code);
506}
507async function loadConfigFromBundledFile(fileName, bundledCode) {
508 const resolvedFileName = fs.realpathSync(fileName);
509 const extension = sysPath.extname(resolvedFileName);
510 const defaultLoader = require.extensions[extension];
511 require.extensions[extension] = (module, requiredFileName) => {
512 if (requiredFileName === resolvedFileName) {
513 module._compile(bundledCode, requiredFileName);
514 }
515 else {
516 defaultLoader(module, requiredFileName);
517 }
518 };
519 delete require.cache[resolvedFileName];
520 try {
521 const config = getDefaultFromCjs(require(fileName));
522 require.extensions[extension] = defaultLoader;
523 return config;
524 }
525 catch (err) {
526 if (err.code === 'ERR_REQUIRE_ESM') {
527 return rollup.error({
528 code: 'TRANSPILED_ESM_CONFIG',
529 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.`,
530 url: 'https://rollupjs.org/guide/en/#using-untranspiled-config-files'
531 });
532 }
533 throw err;
534 }
535}
536async function getConfigList(configFileExport, commandOptions) {
537 const config = await (typeof configFileExport === 'function'
538 ? configFileExport(commandOptions)
539 : configFileExport);
540 if (Object.keys(config).length === 0) {
541 return rollup.error({
542 code: 'MISSING_CONFIG',
543 message: 'Config file must export an options object, or an array of options objects',
544 url: 'https://rollupjs.org/guide/en/#configuration-files'
545 });
546 }
547 return Array.isArray(config) ? config : [config];
548}
549
550exports.addCommandPluginsToInputOptions = addCommandPluginsToInputOptions;
551exports.batchWarnings = batchWarnings;
552exports.bold = bold;
553exports.cyan = cyan;
554exports.green = green;
555exports.handleError = handleError;
556exports.loadAndParseConfigFile = loadAndParseConfigFile;
557exports.stderr = stderr;
558exports.stdinName = stdinName;
559exports.underline = underline;
560//# sourceMappingURL=loadConfigFile.js.map