loadConfigFile.js 21 KB

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