UNPKG

21.2 kBJavaScriptView Raw
1/*
2 @license
3 Rollup.js v2.29.0
4 Thu, 08 Oct 2020 04:24:04 GMT - commit 0b02e52bc7816c473784794670a2c3047ac62a07
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 const nestedByPlugin = nest(warnings, 'plugin');
216 for (const { key: plugin, items } of nestedByPlugin) {
217 const nestedByMessage = nest(items, 'message');
218 let lastUrl = '';
219 for (const { key: message, items } of nestedByMessage) {
220 title(`Plugin ${plugin}: ${message}`);
221 for (const warning of items) {
222 if (warning.url && warning.url !== lastUrl)
223 info((lastUrl = warning.url));
224 if (warning.id) {
225 let loc = rollup.relativeId(warning.id);
226 if (warning.loc) {
227 loc += `: (${warning.loc.line}:${warning.loc.column})`;
228 }
229 stderr(bold(loc));
230 }
231 if (warning.frame)
232 info(warning.frame);
233 }
234 }
235 }
236 },
237 SOURCEMAP_BROKEN(warnings) {
238 title(`Broken sourcemap`);
239 info('https://rollupjs.org/guide/en/#warning-sourcemap-is-likely-to-be-incorrect');
240 const plugins = Array.from(new Set(warnings.map(w => w.plugin).filter(Boolean)));
241 const detail = plugins.length > 1
242 ? ` (such as ${plugins
243 .slice(0, -1)
244 .map(p => `'${p}'`)
245 .join(', ')} and '${plugins.slice(-1)}')`
246 : ` (such as '${plugins[0]}')`;
247 stderr(`Plugins that transform code${detail} should generate accompanying sourcemaps`);
248 },
249 THIS_IS_UNDEFINED(warnings) {
250 title('`this` has been rewritten to `undefined`');
251 info('https://rollupjs.org/guide/en/#error-this-is-undefined');
252 showTruncatedWarnings(warnings);
253 },
254 UNRESOLVED_IMPORT(warnings) {
255 title('Unresolved dependencies');
256 info('https://rollupjs.org/guide/en/#warning-treating-module-as-external-dependency');
257 const dependencies = new Map();
258 for (const warning of warnings) {
259 rollup.getOrCreate(dependencies, warning.source, () => []).push(warning.importer);
260 }
261 for (const dependency of dependencies.keys()) {
262 const importers = dependencies.get(dependency);
263 stderr(`${bold(dependency)} (imported by ${importers.join(', ')})`);
264 }
265 },
266 UNUSED_EXTERNAL_IMPORT(warnings) {
267 title('Unused external imports');
268 for (const warning of warnings) {
269 stderr(`${warning.names} imported from external module '${warning.source}' but never used`);
270 }
271 }
272};
273function title(str) {
274 stderr(bold(yellow(`(!) ${str}`)));
275}
276function info(url) {
277 stderr(gray(url));
278}
279function nest(array, prop) {
280 const nested = [];
281 const lookup = new Map();
282 for (const item of array) {
283 const key = item[prop];
284 rollup.getOrCreate(lookup, key, () => {
285 const items = {
286 items: [],
287 key
288 };
289 nested.push(items);
290 return items;
291 }).items.push(item);
292 }
293 return nested;
294}
295function showTruncatedWarnings(warnings) {
296 const nestedByModule = nest(warnings, 'id');
297 const displayedByModule = nestedByModule.length > 5 ? nestedByModule.slice(0, 3) : nestedByModule;
298 for (const { key: id, items } of displayedByModule) {
299 stderr(bold(rollup.relativeId(id)));
300 stderr(gray(items[0].frame));
301 if (items.length > 1) {
302 stderr(`...and ${items.length - 1} other ${items.length > 2 ? 'occurrences' : 'occurrence'}`);
303 }
304 }
305 if (nestedByModule.length > displayedByModule.length) {
306 stderr(`\n...and ${nestedByModule.length - displayedByModule.length} other files`);
307 }
308}
309
310const stdinName = '-';
311let stdinResult = null;
312function stdinPlugin(arg) {
313 const suffix = typeof arg == 'string' && arg.length ? '.' + arg : '';
314 return {
315 name: 'stdin',
316 resolveId(id) {
317 if (id === stdinName) {
318 return id + suffix;
319 }
320 },
321 load(id) {
322 if (id === stdinName || id.startsWith(stdinName + '.')) {
323 return stdinResult || (stdinResult = readStdin());
324 }
325 }
326 };
327}
328function readStdin() {
329 return new Promise((resolve, reject) => {
330 const chunks = [];
331 process.stdin.setEncoding('utf8');
332 process.stdin
333 .on('data', chunk => chunks.push(chunk))
334 .on('end', () => {
335 const result = chunks.join('');
336 resolve(result);
337 })
338 .on('error', err => {
339 reject(err);
340 });
341 });
342}
343
344function waitForInputPlugin() {
345 return {
346 name: 'wait-for-input',
347 async buildStart(options) {
348 const inputSpecifiers = Array.isArray(options.input)
349 ? options.input
350 : Object.keys(options.input);
351 let lastAwaitedSpecifier = null;
352 checkSpecifiers: while (true) {
353 for (const specifier of inputSpecifiers) {
354 if ((await this.resolve(specifier)) === null) {
355 if (lastAwaitedSpecifier !== specifier) {
356 stderr(`waiting for input ${bold(specifier)}...`);
357 lastAwaitedSpecifier = specifier;
358 }
359 await new Promise(resolve => setTimeout(resolve, 500));
360 continue checkSpecifiers;
361 }
362 }
363 break;
364 }
365 }
366 };
367}
368
369function addCommandPluginsToInputOptions(inputOptions, command) {
370 if (command.stdin !== false) {
371 inputOptions.plugins.push(stdinPlugin(command.stdin));
372 }
373 if (command.waitForBundleInput === true) {
374 inputOptions.plugins.push(waitForInputPlugin());
375 }
376 const commandPlugin = command.plugin;
377 if (commandPlugin) {
378 const plugins = Array.isArray(commandPlugin) ? commandPlugin : [commandPlugin];
379 for (const plugin of plugins) {
380 if (/[={}]/.test(plugin)) {
381 // -p plugin=value
382 // -p "{transform(c,i){...}}"
383 loadAndRegisterPlugin(inputOptions, plugin);
384 }
385 else {
386 // split out plugins joined by commas
387 // -p node-resolve,commonjs,buble
388 plugin.split(',').forEach((plugin) => loadAndRegisterPlugin(inputOptions, plugin));
389 }
390 }
391 }
392}
393function loadAndRegisterPlugin(inputOptions, pluginText) {
394 let plugin = null;
395 let pluginArg = undefined;
396 if (pluginText[0] === '{') {
397 // -p "{transform(c,i){...}}"
398 plugin = new Function('return ' + pluginText);
399 }
400 else {
401 const match = pluginText.match(/^([@.\/\\\w|^{}-]+)(=(.*))?$/);
402 if (match) {
403 // -p plugin
404 // -p plugin=arg
405 pluginText = match[1];
406 pluginArg = new Function('return ' + match[3])();
407 }
408 else {
409 throw new Error(`Invalid --plugin argument format: ${JSON.stringify(pluginText)}`);
410 }
411 if (!/^\.|^rollup-plugin-|[@\/\\]/.test(pluginText)) {
412 // Try using plugin prefix variations first if applicable.
413 // Prefix order is significant - left has higher precedence.
414 for (const prefix of ['@rollup/plugin-', 'rollup-plugin-']) {
415 try {
416 plugin = require(prefix + pluginText);
417 break;
418 }
419 catch (ex) {
420 // if this does not work, we try requiring the actual name below
421 }
422 }
423 }
424 if (!plugin) {
425 try {
426 if (pluginText[0] == '.')
427 pluginText = sysPath.resolve(pluginText);
428 plugin = require(pluginText);
429 }
430 catch (ex) {
431 throw new Error(`Cannot load plugin "${pluginText}": ${ex.message}.`);
432 }
433 }
434 }
435 // some plugins do not use `module.exports` for their entry point,
436 // in which case we try the named default export and the plugin name
437 if (typeof plugin === 'object') {
438 plugin = plugin.default || plugin[getCamelizedPluginBaseName(pluginText)];
439 }
440 if (!plugin) {
441 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.`);
442 }
443 inputOptions.plugins.push(typeof plugin === 'function' ? plugin.call(plugin, pluginArg) : plugin);
444}
445function getCamelizedPluginBaseName(pluginText) {
446 var _a;
447 return (((_a = pluginText.match(/(@rollup\/plugin-|rollup-plugin-)(.+)$/)) === null || _a === void 0 ? void 0 : _a[2]) || pluginText)
448 .split(/[\\/]/)
449 .slice(-1)[0]
450 .split('.')[0]
451 .split('-')
452 .map((part, index) => (index === 0 || !part ? part : part[0].toUpperCase() + part.slice(1)))
453 .join('');
454}
455
456function supportsNativeESM() {
457 return Number(/^v(\d+)/.exec(process.version)[1]) >= 13;
458}
459async function loadAndParseConfigFile(fileName, commandOptions = {}) {
460 const configs = await loadConfigFile(fileName, commandOptions);
461 const warnings = batchWarnings();
462 try {
463 const normalizedConfigs = configs.map(config => {
464 const options = mergeOptions.mergeOptions(config, commandOptions, warnings.add);
465 addCommandPluginsToInputOptions(options, commandOptions);
466 return options;
467 });
468 return { options: normalizedConfigs, warnings };
469 }
470 catch (err) {
471 warnings.flush();
472 throw err;
473 }
474}
475async function loadConfigFile(fileName, commandOptions) {
476 const extension = sysPath.extname(fileName);
477 const configFileExport = extension === '.mjs' && supportsNativeESM()
478 ? (await import(url.pathToFileURL(fileName).href)).default
479 : extension === '.cjs'
480 ? getDefaultFromCjs(require(fileName))
481 : await getDefaultFromTranspiledConfigFile(fileName, commandOptions.silent);
482 return getConfigList(configFileExport, commandOptions);
483}
484function getDefaultFromCjs(namespace) {
485 return namespace.__esModule ? namespace.default : namespace;
486}
487async function getDefaultFromTranspiledConfigFile(fileName, silent) {
488 const warnings = batchWarnings();
489 const bundle = await rollup.rollup({
490 external: (id) => (id[0] !== '.' && !sysPath.isAbsolute(id)) || id.slice(-5, id.length) === '.json',
491 input: fileName,
492 onwarn: warnings.add,
493 treeshake: false
494 });
495 if (!silent && warnings.count > 0) {
496 stderr(bold(`loaded ${rollup.relativeId(fileName)} with warnings`));
497 warnings.flush();
498 }
499 const { output: [{ code }] } = await bundle.generate({
500 exports: 'named',
501 format: 'cjs'
502 });
503 return loadConfigFromBundledFile(fileName, code);
504}
505async function loadConfigFromBundledFile(fileName, bundledCode) {
506 const resolvedFileName = fs.realpathSync(fileName);
507 const extension = sysPath.extname(resolvedFileName);
508 const defaultLoader = require.extensions[extension];
509 require.extensions[extension] = (module, requiredFileName) => {
510 if (requiredFileName === resolvedFileName) {
511 module._compile(bundledCode, requiredFileName);
512 }
513 else {
514 defaultLoader(module, requiredFileName);
515 }
516 };
517 delete require.cache[resolvedFileName];
518 try {
519 const config = getDefaultFromCjs(require(fileName));
520 require.extensions[extension] = defaultLoader;
521 return config;
522 }
523 catch (err) {
524 if (err.code === 'ERR_REQUIRE_ESM') {
525 return rollup.error({
526 code: 'TRANSPILED_ESM_CONFIG',
527 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.`,
528 url: 'https://rollupjs.org/guide/en/#using-untranspiled-config-files'
529 });
530 }
531 throw err;
532 }
533}
534async function getConfigList(configFileExport, commandOptions) {
535 const config = await (typeof configFileExport === 'function'
536 ? configFileExport(commandOptions)
537 : configFileExport);
538 if (Object.keys(config).length === 0) {
539 return rollup.error({
540 code: 'MISSING_CONFIG',
541 message: 'Config file must export an options object, or an array of options objects',
542 url: 'https://rollupjs.org/guide/en/#configuration-files'
543 });
544 }
545 return Array.isArray(config) ? config : [config];
546}
547
548exports.addCommandPluginsToInputOptions = addCommandPluginsToInputOptions;
549exports.batchWarnings = batchWarnings;
550exports.bold = bold;
551exports.cyan = cyan;
552exports.green = green;
553exports.handleError = handleError;
554exports.loadAndParseConfigFile = loadAndParseConfigFile;
555exports.stderr = stderr;
556exports.stdinName = stdinName;
557exports.underline = underline;
558//# sourceMappingURL=loadConfigFile.js.map