UNPKG

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