loadConfigFile.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  1. /*
  2. @license
  3. Rollup.js v3.7.4
  4. Tue, 13 Dec 2022 05:29:18 GMT - commit bd3522b33f18001372638263aeb704b76edbf48c
  5. https://github.com/rollup/rollup
  6. Released under the MIT License.
  7. */
  8. 'use strict';
  9. const node_fs = require('node:fs');
  10. const node_path = require('node:path');
  11. const process = require('node:process');
  12. const node_url = require('node:url');
  13. const rollup = require('./rollup.js');
  14. function batchWarnings() {
  15. let count = 0;
  16. const deferredWarnings = new Map();
  17. let warningOccurred = false;
  18. return {
  19. add(warning) {
  20. count += 1;
  21. warningOccurred = true;
  22. if (warning.code in deferredHandlers) {
  23. rollup.getOrCreate(deferredWarnings, warning.code, rollup.getNewArray).push(warning);
  24. }
  25. else if (warning.code in immediateHandlers) {
  26. immediateHandlers[warning.code](warning);
  27. }
  28. else {
  29. title(warning.message);
  30. if (warning.url)
  31. info(warning.url);
  32. const id = warning.loc?.file || warning.id;
  33. if (id) {
  34. const loc = warning.loc
  35. ? `${rollup.relativeId(id)} (${warning.loc.line}:${warning.loc.column})`
  36. : rollup.relativeId(id);
  37. rollup.stderr(rollup.bold(rollup.relativeId(loc)));
  38. }
  39. if (warning.frame)
  40. info(warning.frame);
  41. }
  42. },
  43. get count() {
  44. return count;
  45. },
  46. flush() {
  47. if (count === 0)
  48. return;
  49. const codes = [...deferredWarnings.keys()].sort((a, b) => deferredWarnings.get(b).length - deferredWarnings.get(a).length);
  50. for (const code of codes) {
  51. deferredHandlers[code](deferredWarnings.get(code));
  52. }
  53. deferredWarnings.clear();
  54. count = 0;
  55. },
  56. get warningOccurred() {
  57. return warningOccurred;
  58. }
  59. };
  60. }
  61. const immediateHandlers = {
  62. MISSING_NODE_BUILTINS(warning) {
  63. title(`Missing shims for Node.js built-ins`);
  64. rollup.stderr(`Creating a browser bundle that depends on ${rollup.printQuotedStringList(warning.ids)}. You might need to include https://github.com/FredKSchott/rollup-plugin-polyfill-node`);
  65. },
  66. UNKNOWN_OPTION(warning) {
  67. title(`You have passed an unrecognized option`);
  68. rollup.stderr(warning.message);
  69. }
  70. };
  71. const deferredHandlers = {
  72. CIRCULAR_DEPENDENCY(warnings) {
  73. title(`Circular dependenc${warnings.length > 1 ? 'ies' : 'y'}`);
  74. const displayed = warnings.length > 5 ? warnings.slice(0, 3) : warnings;
  75. for (const warning of displayed) {
  76. rollup.stderr(warning.ids.map(rollup.relativeId).join(' -> '));
  77. }
  78. if (warnings.length > displayed.length) {
  79. rollup.stderr(`...and ${warnings.length - displayed.length} more`);
  80. }
  81. },
  82. EMPTY_BUNDLE(warnings) {
  83. title(`Generated${warnings.length === 1 ? ' an' : ''} empty ${warnings.length > 1 ? 'chunks' : 'chunk'}`);
  84. rollup.stderr(rollup.printQuotedStringList(warnings.map(warning => warning.names[0])));
  85. },
  86. EVAL(warnings) {
  87. title('Use of eval is strongly discouraged');
  88. info('https://rollupjs.org/guide/en/#avoiding-eval');
  89. showTruncatedWarnings(warnings);
  90. },
  91. MISSING_EXPORT(warnings) {
  92. title('Missing exports');
  93. info('https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module');
  94. for (const warning of warnings) {
  95. rollup.stderr(rollup.bold(rollup.relativeId(warning.id)));
  96. rollup.stderr(`${warning.binding} is not exported by ${rollup.relativeId(warning.exporter)}`);
  97. rollup.stderr(rollup.gray(warning.frame));
  98. }
  99. },
  100. MISSING_GLOBAL_NAME(warnings) {
  101. title(`Missing global variable ${warnings.length > 1 ? 'names' : 'name'}`);
  102. info('https://rollupjs.org/guide/en/#outputglobals');
  103. rollup.stderr(`Use "output.globals" to specify browser global variable names corresponding to external modules:`);
  104. for (const warning of warnings) {
  105. rollup.stderr(`${rollup.bold(warning.id)} (guessing "${warning.names[0]}")`);
  106. }
  107. },
  108. MIXED_EXPORTS(warnings) {
  109. title('Mixing named and default exports');
  110. info(`https://rollupjs.org/guide/en/#outputexports`);
  111. rollup.stderr(rollup.bold('The following entry modules are using named and default exports together:'));
  112. warnings.sort((a, b) => (a.id < b.id ? -1 : 1));
  113. const displayedWarnings = warnings.length > 5 ? warnings.slice(0, 3) : warnings;
  114. for (const warning of displayedWarnings) {
  115. rollup.stderr(rollup.relativeId(warning.id));
  116. }
  117. if (displayedWarnings.length < warnings.length) {
  118. rollup.stderr(`...and ${warnings.length - displayedWarnings.length} other entry modules`);
  119. }
  120. rollup.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.`);
  121. },
  122. NAMESPACE_CONFLICT(warnings) {
  123. title(`Conflicting re-exports`);
  124. for (const warning of warnings) {
  125. rollup.stderr(`"${rollup.bold(rollup.relativeId(warning.reexporter))}" re-exports "${warning.binding}" from both "${rollup.relativeId(warning.ids[0])}" and "${rollup.relativeId(warning.ids[1])}" (will be ignored).`);
  126. }
  127. },
  128. PLUGIN_WARNING(warnings) {
  129. const nestedByPlugin = nest(warnings, 'plugin');
  130. for (const { key: plugin, items } of nestedByPlugin) {
  131. const nestedByMessage = nest(items, 'message');
  132. let lastUrl = '';
  133. for (const { key: message, items } of nestedByMessage) {
  134. title(`Plugin ${plugin}: ${message}`);
  135. for (const warning of items) {
  136. if (warning.url && warning.url !== lastUrl)
  137. info((lastUrl = warning.url));
  138. const id = warning.id || warning.loc?.file;
  139. if (id) {
  140. let loc = rollup.relativeId(id);
  141. if (warning.loc) {
  142. loc += `: (${warning.loc.line}:${warning.loc.column})`;
  143. }
  144. rollup.stderr(rollup.bold(loc));
  145. }
  146. if (warning.frame)
  147. info(warning.frame);
  148. }
  149. }
  150. }
  151. },
  152. SOURCEMAP_BROKEN(warnings) {
  153. title(`Broken sourcemap`);
  154. info('https://rollupjs.org/guide/en/#warning-sourcemap-is-likely-to-be-incorrect');
  155. const plugins = [...new Set(warnings.map(({ plugin }) => plugin).filter(Boolean))];
  156. rollup.stderr(`Plugins that transform code (such as ${rollup.printQuotedStringList(plugins)}) should generate accompanying sourcemaps.`);
  157. },
  158. THIS_IS_UNDEFINED(warnings) {
  159. title('"this" has been rewritten to "undefined"');
  160. info('https://rollupjs.org/guide/en/#error-this-is-undefined');
  161. showTruncatedWarnings(warnings);
  162. },
  163. UNRESOLVED_IMPORT(warnings) {
  164. title('Unresolved dependencies');
  165. info('https://rollupjs.org/guide/en/#warning-treating-module-as-external-dependency');
  166. const dependencies = new Map();
  167. for (const warning of warnings) {
  168. rollup.getOrCreate(dependencies, rollup.relativeId(warning.exporter), rollup.getNewArray).push(rollup.relativeId(warning.id));
  169. }
  170. for (const [dependency, importers] of dependencies) {
  171. rollup.stderr(`${rollup.bold(dependency)} (imported by ${rollup.printQuotedStringList(importers)})`);
  172. }
  173. },
  174. UNUSED_EXTERNAL_IMPORT(warnings) {
  175. title('Unused external imports');
  176. for (const warning of warnings) {
  177. rollup.stderr(warning.names +
  178. ' imported from external module "' +
  179. warning.exporter +
  180. '" but never used in ' +
  181. rollup.printQuotedStringList(warning.ids.map(rollup.relativeId)) +
  182. '.');
  183. }
  184. }
  185. };
  186. function title(string_) {
  187. rollup.stderr(rollup.bold(rollup.yellow(`(!) ${string_}`)));
  188. }
  189. function info(url) {
  190. rollup.stderr(rollup.gray(url));
  191. }
  192. function nest(array, property) {
  193. const nested = [];
  194. const lookup = new Map();
  195. for (const item of array) {
  196. const key = item[property];
  197. rollup.getOrCreate(lookup, key, () => {
  198. const items = {
  199. items: [],
  200. key
  201. };
  202. nested.push(items);
  203. return items;
  204. }).items.push(item);
  205. }
  206. return nested;
  207. }
  208. function showTruncatedWarnings(warnings) {
  209. const nestedByModule = nest(warnings, 'id');
  210. const displayedByModule = nestedByModule.length > 5 ? nestedByModule.slice(0, 3) : nestedByModule;
  211. for (const { key: id, items } of displayedByModule) {
  212. rollup.stderr(rollup.bold(rollup.relativeId(id)));
  213. rollup.stderr(rollup.gray(items[0].frame));
  214. if (items.length > 1) {
  215. rollup.stderr(`...and ${items.length - 1} other ${items.length > 2 ? 'occurrences' : 'occurrence'}`);
  216. }
  217. }
  218. if (nestedByModule.length > displayedByModule.length) {
  219. rollup.stderr(`\n...and ${nestedByModule.length - displayedByModule.length} other files`);
  220. }
  221. }
  222. const stdinName = '-';
  223. let stdinResult = null;
  224. function stdinPlugin(argument) {
  225. const suffix = typeof argument == 'string' && argument.length > 0 ? '.' + argument : '';
  226. return {
  227. load(id) {
  228. if (id === stdinName || id.startsWith(stdinName + '.')) {
  229. return stdinResult || (stdinResult = readStdin());
  230. }
  231. },
  232. name: 'stdin',
  233. resolveId(id) {
  234. if (id === stdinName) {
  235. return id + suffix;
  236. }
  237. }
  238. };
  239. }
  240. function readStdin() {
  241. return new Promise((resolve, reject) => {
  242. const chunks = [];
  243. process.stdin.setEncoding('utf8');
  244. process.stdin
  245. .on('data', chunk => chunks.push(chunk))
  246. .on('end', () => {
  247. const result = chunks.join('');
  248. resolve(result);
  249. })
  250. .on('error', error => {
  251. reject(error);
  252. });
  253. });
  254. }
  255. function waitForInputPlugin() {
  256. return {
  257. async buildStart(options) {
  258. const inputSpecifiers = Array.isArray(options.input)
  259. ? options.input
  260. : Object.keys(options.input);
  261. let lastAwaitedSpecifier = null;
  262. checkSpecifiers: while (true) {
  263. for (const specifier of inputSpecifiers) {
  264. if ((await this.resolve(specifier)) === null) {
  265. if (lastAwaitedSpecifier !== specifier) {
  266. rollup.stderr(`waiting for input ${rollup.bold(specifier)}...`);
  267. lastAwaitedSpecifier = specifier;
  268. }
  269. await new Promise(resolve => setTimeout(resolve, 500));
  270. continue checkSpecifiers;
  271. }
  272. }
  273. break;
  274. }
  275. },
  276. name: 'wait-for-input'
  277. };
  278. }
  279. async function addCommandPluginsToInputOptions(inputOptions, command) {
  280. if (command.stdin !== false) {
  281. inputOptions.plugins.push(stdinPlugin(command.stdin));
  282. }
  283. if (command.waitForBundleInput === true) {
  284. inputOptions.plugins.push(waitForInputPlugin());
  285. }
  286. await addPluginsFromCommandOption(command.plugin, inputOptions);
  287. }
  288. async function addPluginsFromCommandOption(commandPlugin, inputOptions) {
  289. if (commandPlugin) {
  290. const plugins = await rollup.normalizePluginOption(commandPlugin);
  291. for (const plugin of plugins) {
  292. if (/[={}]/.test(plugin)) {
  293. // -p plugin=value
  294. // -p "{transform(c,i){...}}"
  295. await loadAndRegisterPlugin(inputOptions, plugin);
  296. }
  297. else {
  298. // split out plugins joined by commas
  299. // -p node-resolve,commonjs,buble
  300. for (const p of plugin.split(',')) {
  301. await loadAndRegisterPlugin(inputOptions, p);
  302. }
  303. }
  304. }
  305. }
  306. }
  307. async function loadAndRegisterPlugin(inputOptions, pluginText) {
  308. let plugin = null;
  309. let pluginArgument = undefined;
  310. if (pluginText[0] === '{') {
  311. // -p "{transform(c,i){...}}"
  312. plugin = new Function('return ' + pluginText);
  313. }
  314. else {
  315. const match = pluginText.match(/^([\w./:@\\^{|}-]+)(=(.*))?$/);
  316. if (match) {
  317. // -p plugin
  318. // -p plugin=arg
  319. pluginText = match[1];
  320. pluginArgument = new Function('return ' + match[3])();
  321. }
  322. else {
  323. throw new Error(`Invalid --plugin argument format: ${JSON.stringify(pluginText)}`);
  324. }
  325. if (!/^\.|^rollup-plugin-|[/@\\]/.test(pluginText)) {
  326. // Try using plugin prefix variations first if applicable.
  327. // Prefix order is significant - left has higher precedence.
  328. for (const prefix of ['@rollup/plugin-', 'rollup-plugin-']) {
  329. try {
  330. plugin = await requireOrImport(prefix + pluginText);
  331. break;
  332. }
  333. catch {
  334. // if this does not work, we try requiring the actual name below
  335. }
  336. }
  337. }
  338. if (!plugin) {
  339. try {
  340. if (pluginText[0] == '.')
  341. pluginText = node_path.resolve(pluginText);
  342. // Windows absolute paths must be specified as file:// protocol URL
  343. // Note that we do not have coverage for Windows-only code paths
  344. else if (/^[A-Za-z]:\\/.test(pluginText)) {
  345. pluginText = node_url.pathToFileURL(node_path.resolve(pluginText)).href;
  346. }
  347. plugin = await requireOrImport(pluginText);
  348. }
  349. catch (error) {
  350. throw new Error(`Cannot load plugin "${pluginText}": ${error.message}.`);
  351. }
  352. }
  353. }
  354. // some plugins do not use `module.exports` for their entry point,
  355. // in which case we try the named default export and the plugin name
  356. if (typeof plugin === 'object') {
  357. plugin = plugin.default || plugin[getCamelizedPluginBaseName(pluginText)];
  358. }
  359. if (!plugin) {
  360. 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.`);
  361. }
  362. inputOptions.plugins.push(typeof plugin === 'function' ? plugin.call(plugin, pluginArgument) : plugin);
  363. }
  364. function getCamelizedPluginBaseName(pluginText) {
  365. return (pluginText.match(/(@rollup\/plugin-|rollup-plugin-)(.+)$/)?.[2] || pluginText)
  366. .split(/[/\\]/)
  367. .slice(-1)[0]
  368. .split('.')[0]
  369. .split('-')
  370. .map((part, index) => (index === 0 || !part ? part : part[0].toUpperCase() + part.slice(1)))
  371. .join('');
  372. }
  373. async function requireOrImport(pluginPath) {
  374. try {
  375. // eslint-disable-next-line unicorn/prefer-module
  376. return require(pluginPath);
  377. }
  378. catch {
  379. return import(pluginPath);
  380. }
  381. }
  382. async function loadConfigFile(fileName, commandOptions = {}) {
  383. const configs = await getConfigList(getDefaultFromCjs(await getConfigFileExport(fileName, commandOptions)), commandOptions);
  384. const warnings = batchWarnings();
  385. try {
  386. const normalizedConfigs = [];
  387. for (const config of configs) {
  388. const options = await rollup.mergeOptions(config, commandOptions, warnings.add);
  389. await addCommandPluginsToInputOptions(options, commandOptions);
  390. normalizedConfigs.push(options);
  391. }
  392. return { options: normalizedConfigs, warnings };
  393. }
  394. catch (error_) {
  395. warnings.flush();
  396. throw error_;
  397. }
  398. }
  399. async function getConfigFileExport(fileName, commandOptions) {
  400. if (commandOptions.configPlugin || commandOptions.bundleConfigAsCjs) {
  401. try {
  402. return await loadTranspiledConfigFile(fileName, commandOptions);
  403. }
  404. catch (error_) {
  405. if (error_.message.includes('not defined in ES module scope')) {
  406. return rollup.error(rollup.errorCannotBundleConfigAsEsm(error_));
  407. }
  408. throw error_;
  409. }
  410. }
  411. let cannotLoadEsm = false;
  412. const handleWarning = (warning) => {
  413. if (warning.message.includes('To load an ES module')) {
  414. cannotLoadEsm = true;
  415. }
  416. };
  417. process.on('warning', handleWarning);
  418. try {
  419. const fileUrl = node_url.pathToFileURL(fileName);
  420. if (process.env.ROLLUP_WATCH) {
  421. // We are adding the current date to allow reloads in watch mode
  422. fileUrl.search = `?${Date.now()}`;
  423. }
  424. return (await import(fileUrl.href)).default;
  425. }
  426. catch (error_) {
  427. if (cannotLoadEsm) {
  428. return rollup.error(rollup.errorCannotLoadConfigAsCjs(error_));
  429. }
  430. if (error_.message.includes('not defined in ES module scope')) {
  431. return rollup.error(rollup.errorCannotLoadConfigAsEsm(error_));
  432. }
  433. throw error_;
  434. }
  435. finally {
  436. process.off('warning', handleWarning);
  437. }
  438. }
  439. function getDefaultFromCjs(namespace) {
  440. return namespace.default || namespace;
  441. }
  442. async function loadTranspiledConfigFile(fileName, { bundleConfigAsCjs, configPlugin, silent }) {
  443. const warnings = batchWarnings();
  444. const inputOptions = {
  445. external: (id) => (id[0] !== '.' && !node_path.isAbsolute(id)) || id.slice(-5, id.length) === '.json',
  446. input: fileName,
  447. onwarn: warnings.add,
  448. plugins: [],
  449. treeshake: false
  450. };
  451. await addPluginsFromCommandOption(configPlugin, inputOptions);
  452. const bundle = await rollup.rollup(inputOptions);
  453. if (!silent && warnings.count > 0) {
  454. rollup.stderr(rollup.bold(`loaded ${rollup.relativeId(fileName)} with warnings`));
  455. warnings.flush();
  456. }
  457. const { output: [{ code }] } = await bundle.generate({
  458. exports: 'named',
  459. format: bundleConfigAsCjs ? 'cjs' : 'es',
  460. plugins: [
  461. {
  462. name: 'transpile-import-meta',
  463. resolveImportMeta(property, { moduleId }) {
  464. if (property === 'url') {
  465. return `'${node_url.pathToFileURL(moduleId).href}'`;
  466. }
  467. if (property == null) {
  468. return `{url:'${node_url.pathToFileURL(moduleId).href}'}`;
  469. }
  470. }
  471. }
  472. ]
  473. });
  474. return loadConfigFromWrittenFile(node_path.join(node_path.dirname(fileName), `rollup.config-${Date.now()}.${bundleConfigAsCjs ? 'cjs' : 'mjs'}`), code);
  475. }
  476. async function loadConfigFromWrittenFile(bundledFileName, bundledCode) {
  477. await node_fs.promises.writeFile(bundledFileName, bundledCode);
  478. try {
  479. return (await import(node_url.pathToFileURL(bundledFileName).href)).default;
  480. }
  481. finally {
  482. // Not awaiting here saves some ms while potentially hiding a non-critical error
  483. node_fs.promises.unlink(bundledFileName);
  484. }
  485. }
  486. async function getConfigList(configFileExport, commandOptions) {
  487. const config = await (typeof configFileExport === 'function'
  488. ? configFileExport(commandOptions)
  489. : configFileExport);
  490. if (Object.keys(config).length === 0) {
  491. return rollup.error(rollup.errorMissingConfig());
  492. }
  493. return Array.isArray(config) ? config : [config];
  494. }
  495. exports.addCommandPluginsToInputOptions = addCommandPluginsToInputOptions;
  496. exports.batchWarnings = batchWarnings;
  497. exports.loadConfigFile = loadConfigFile;
  498. exports.stdinName = stdinName;
  499. //# sourceMappingURL=loadConfigFile.js.map