index.js 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410
  1. 'use strict';
  2. function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
  3. var path = require('path');
  4. var pluginutils = require('@rollup/pluginutils');
  5. var getCommonDir = _interopDefault(require('commondir'));
  6. var fs = require('fs');
  7. var estreeWalker = require('estree-walker');
  8. var MagicString = _interopDefault(require('magic-string'));
  9. var resolve = require('resolve');
  10. var isReference = _interopDefault(require('is-reference'));
  11. var glob = _interopDefault(require('glob'));
  12. var peerDependencies = {
  13. rollup: "^2.22.0"
  14. };
  15. const PROXY_SUFFIX = '?commonjs-proxy';
  16. const getProxyId = (id) => `\0${id}${PROXY_SUFFIX}`;
  17. const getIdFromProxyId = (proxyId) => proxyId.slice(1, -PROXY_SUFFIX.length);
  18. const EXTERNAL_SUFFIX = '?commonjs-external';
  19. const getExternalProxyId = (id) => `\0${id}${EXTERNAL_SUFFIX}`;
  20. const getIdFromExternalProxyId = (proxyId) => proxyId.slice(1, -EXTERNAL_SUFFIX.length);
  21. const VIRTUAL_PATH_BASE = '/$$rollup_base$$';
  22. const getVirtualPathForDynamicRequirePath = (path, commonDir) => {
  23. if (path.startsWith(commonDir)) return VIRTUAL_PATH_BASE + path.slice(commonDir.length);
  24. return path;
  25. };
  26. const DYNAMIC_REGISTER_PREFIX = '\0commonjs-dynamic-register:';
  27. const DYNAMIC_JSON_PREFIX = '\0commonjs-dynamic-json:';
  28. const DYNAMIC_PACKAGES_ID = '\0commonjs-dynamic-packages';
  29. const HELPERS_ID = '\0commonjsHelpers.js';
  30. // `x['default']` is used instead of `x.default` for backward compatibility with ES3 browsers.
  31. // Minifiers like uglify will usually transpile it back if compatibility with ES3 is not enabled.
  32. // This will no longer be necessary once Rollup switches to ES6 output, likely
  33. // in Rollup 3
  34. // The "hasOwnProperty" call in "getDefaultExportFromCjs" is technically not
  35. // needed, but for consumers that use Rollup's old interop pattern, it will fix
  36. // rollup/rollup-plugin-commonjs#224
  37. // We should remove it once Rollup core and this plugin are updated to not use
  38. // this pattern any more
  39. const HELPERS = `
  40. export var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
  41. export function getDefaultExportFromCjs (x) {
  42. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  43. }
  44. export function createCommonjsModule(fn, basedir, module) {
  45. return module = {
  46. path: basedir,
  47. exports: {},
  48. require: function (path, base) {
  49. return commonjsRequire(path, (base === undefined || base === null) ? module.path : base);
  50. }
  51. }, fn(module, module.exports), module.exports;
  52. }
  53. export function getDefaultExportFromNamespaceIfPresent (n) {
  54. return n && Object.prototype.hasOwnProperty.call(n, 'default') ? n['default'] : n;
  55. }
  56. export function getDefaultExportFromNamespaceIfNotNamed (n) {
  57. return n && Object.prototype.hasOwnProperty.call(n, 'default') && Object.keys(n).length === 1 ? n['default'] : n;
  58. }
  59. export function getAugmentedNamespace(n) {
  60. if (n.__esModule) return n;
  61. var a = Object.defineProperty({}, '__esModule', {value: true});
  62. Object.keys(n).forEach(function (k) {
  63. var d = Object.getOwnPropertyDescriptor(n, k);
  64. Object.defineProperty(a, k, d.get ? d : {
  65. enumerable: true,
  66. get: function () {
  67. return n[k];
  68. }
  69. });
  70. });
  71. return a;
  72. }
  73. `;
  74. const HELPER_NON_DYNAMIC = `
  75. export function commonjsRequire () {
  76. throw new Error('Dynamic requires are not currently supported by @rollup/plugin-commonjs');
  77. }
  78. `;
  79. const HELPERS_DYNAMIC = `
  80. export function commonjsRegister (path, loader) {
  81. DYNAMIC_REQUIRE_LOADERS[path] = loader;
  82. }
  83. const DYNAMIC_REQUIRE_LOADERS = Object.create(null);
  84. const DYNAMIC_REQUIRE_CACHE = Object.create(null);
  85. const DEFAULT_PARENT_MODULE = {
  86. id: '<' + 'rollup>', exports: {}, parent: undefined, filename: null, loaded: false, children: [], paths: []
  87. };
  88. const CHECKED_EXTENSIONS = ['', '.js', '.json'];
  89. function normalize (path) {
  90. path = path.replace(/\\\\/g, '/');
  91. const parts = path.split('/');
  92. const slashed = parts[0] === '';
  93. for (let i = 1; i < parts.length; i++) {
  94. if (parts[i] === '.' || parts[i] === '') {
  95. parts.splice(i--, 1);
  96. }
  97. }
  98. for (let i = 1; i < parts.length; i++) {
  99. if (parts[i] !== '..') continue;
  100. if (i > 0 && parts[i - 1] !== '..' && parts[i - 1] !== '.') {
  101. parts.splice(--i, 2);
  102. i--;
  103. }
  104. }
  105. path = parts.join('/');
  106. if (slashed && path[0] !== '/')
  107. path = '/' + path;
  108. else if (path.length === 0)
  109. path = '.';
  110. return path;
  111. }
  112. function join () {
  113. if (arguments.length === 0)
  114. return '.';
  115. let joined;
  116. for (let i = 0; i < arguments.length; ++i) {
  117. let arg = arguments[i];
  118. if (arg.length > 0) {
  119. if (joined === undefined)
  120. joined = arg;
  121. else
  122. joined += '/' + arg;
  123. }
  124. }
  125. if (joined === undefined)
  126. return '.';
  127. return joined;
  128. }
  129. function isPossibleNodeModulesPath (modulePath) {
  130. let c0 = modulePath[0];
  131. if (c0 === '/' || c0 === '\\\\') return false;
  132. let c1 = modulePath[1], c2 = modulePath[2];
  133. if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\\\')) ||
  134. (c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\\\'))) return false;
  135. if (c1 === ':' && (c2 === '/' || c2 === '\\\\'))
  136. return false;
  137. return true;
  138. }
  139. function dirname (path) {
  140. if (path.length === 0)
  141. return '.';
  142. let i = path.length - 1;
  143. while (i > 0) {
  144. const c = path.charCodeAt(i);
  145. if ((c === 47 || c === 92) && i !== path.length - 1)
  146. break;
  147. i--;
  148. }
  149. if (i > 0)
  150. return path.substr(0, i);
  151. if (path.chartCodeAt(0) === 47 || path.chartCodeAt(0) === 92)
  152. return path.charAt(0);
  153. return '.';
  154. }
  155. export function commonjsRequire (path, originalModuleDir) {
  156. const shouldTryNodeModules = isPossibleNodeModulesPath(path);
  157. path = normalize(path);
  158. let relPath;
  159. while (true) {
  160. if (!shouldTryNodeModules) {
  161. relPath = originalModuleDir ? normalize(originalModuleDir + '/' + path) : path;
  162. } else if (originalModuleDir) {
  163. relPath = normalize(originalModuleDir + '/node_modules/' + path);
  164. } else {
  165. relPath = normalize(join('node_modules', path));
  166. }
  167. for (let extensionIndex = 0; extensionIndex < CHECKED_EXTENSIONS.length; extensionIndex++) {
  168. const resolvedPath = relPath + CHECKED_EXTENSIONS[extensionIndex];
  169. let cachedModule = DYNAMIC_REQUIRE_CACHE[resolvedPath];
  170. if (cachedModule) return cachedModule.exports;
  171. const loader = DYNAMIC_REQUIRE_LOADERS[resolvedPath];
  172. if (loader) {
  173. DYNAMIC_REQUIRE_CACHE[resolvedPath] = cachedModule = {
  174. id: resolvedPath,
  175. filename: resolvedPath,
  176. path: dirname(resolvedPath),
  177. exports: {},
  178. parent: DEFAULT_PARENT_MODULE,
  179. loaded: false,
  180. children: [],
  181. paths: [],
  182. require: function (path, base) {
  183. return commonjsRequire(path, (base === undefined || base === null) ? cachedModule.path : base);
  184. }
  185. };
  186. try {
  187. loader.call(commonjsGlobal, cachedModule, cachedModule.exports);
  188. } catch (error) {
  189. delete DYNAMIC_REQUIRE_CACHE[resolvedPath];
  190. throw error;
  191. }
  192. cachedModule.loaded = true;
  193. return cachedModule.exports;
  194. };
  195. }
  196. if (!shouldTryNodeModules) break;
  197. const nextDir = normalize(originalModuleDir + '/..');
  198. if (nextDir === originalModuleDir) break;
  199. originalModuleDir = nextDir;
  200. }
  201. return require(path);
  202. }
  203. commonjsRequire.cache = DYNAMIC_REQUIRE_CACHE;
  204. `;
  205. function getHelpersModule(isDynamicRequireModulesEnabled) {
  206. return `${HELPERS}${isDynamicRequireModulesEnabled ? HELPERS_DYNAMIC : HELPER_NON_DYNAMIC}`;
  207. }
  208. /* eslint-disable no-undefined */
  209. const operators = {
  210. '==': (x) => equals(x.left, x.right, false),
  211. '!=': (x) => not(operators['=='](x)),
  212. '===': (x) => equals(x.left, x.right, true),
  213. '!==': (x) => not(operators['==='](x)),
  214. '!': (x) => isFalsy(x.argument),
  215. '&&': (x) => isTruthy(x.left) && isTruthy(x.right),
  216. '||': (x) => isTruthy(x.left) || isTruthy(x.right)
  217. };
  218. function flatten(node) {
  219. const parts = [];
  220. while (node.type === 'MemberExpression') {
  221. if (node.computed) return null;
  222. parts.unshift(node.property.name);
  223. // eslint-disable-next-line no-param-reassign
  224. node = node.object;
  225. }
  226. if (node.type !== 'Identifier') return null;
  227. const { name } = node;
  228. parts.unshift(name);
  229. return { name, keypath: parts.join('.') };
  230. }
  231. function isTruthy(node) {
  232. if (node.type === 'Literal') return !!node.value;
  233. if (node.type === 'ParenthesizedExpression') return isTruthy(node.expression);
  234. if (node.operator in operators) return operators[node.operator](node);
  235. return undefined;
  236. }
  237. function isFalsy(node) {
  238. return not(isTruthy(node));
  239. }
  240. function not(value) {
  241. return value === undefined ? value : !value;
  242. }
  243. function equals(a, b, strict) {
  244. if (a.type !== b.type) return undefined;
  245. // eslint-disable-next-line eqeqeq
  246. if (a.type === 'Literal') return strict ? a.value === b.value : a.value == b.value;
  247. return undefined;
  248. }
  249. /* eslint-disable import/prefer-default-export */
  250. function getName(id) {
  251. const name = pluginutils.makeLegalIdentifier(path.basename(id, path.extname(id)));
  252. if (name !== 'index') {
  253. return name;
  254. }
  255. const segments = path.dirname(id).split(path.sep);
  256. return pluginutils.makeLegalIdentifier(segments[segments.length - 1]);
  257. }
  258. /* eslint-disable no-param-reassign, no-shadow, no-underscore-dangle, no-continue */
  259. const reserved = 'process location abstract arguments boolean break byte case catch char class const continue debugger default delete do double else enum eval export extends false final finally float for from function goto if implements import in instanceof int interface let long native new null package private protected public return short static super switch synchronized this throw throws transient true try typeof var void volatile while with yield'.split(
  260. ' '
  261. );
  262. const blacklist = { __esModule: true };
  263. reserved.forEach((word) => (blacklist[word] = true));
  264. const exportsPattern = /^(?:module\.)?exports(?:\.([a-zA-Z_$][a-zA-Z_$0-9]*))?$/;
  265. const firstpassGlobal = /\b(?:require|module|exports|global)\b/;
  266. const firstpassNoGlobal = /\b(?:require|module|exports)\b/;
  267. const functionType = /^(?:FunctionDeclaration|FunctionExpression|ArrowFunctionExpression)$/;
  268. function deconflict(scope, globals, identifier) {
  269. let i = 1;
  270. let deconflicted = pluginutils.makeLegalIdentifier(identifier);
  271. while (scope.contains(deconflicted) || globals.has(deconflicted) || deconflicted in blacklist) {
  272. deconflicted = `${identifier}_${i}`;
  273. i += 1;
  274. }
  275. scope.declarations[deconflicted] = true;
  276. return deconflicted;
  277. }
  278. function tryParse(parse, code, id) {
  279. try {
  280. return parse(code, { allowReturnOutsideFunction: true });
  281. } catch (err) {
  282. err.message += ` in ${id}`;
  283. throw err;
  284. }
  285. }
  286. function normalizePathSlashes(path) {
  287. return path.replace(/\\/g, '/');
  288. }
  289. function hasCjsKeywords(code, ignoreGlobal) {
  290. const firstpass = ignoreGlobal ? firstpassNoGlobal : firstpassGlobal;
  291. return firstpass.test(code);
  292. }
  293. function checkEsModule(parse, code, id) {
  294. const ast = tryParse(parse, code, id);
  295. let isEsModule = false;
  296. let hasDefaultExport = false;
  297. let hasNamedExports = false;
  298. for (const node of ast.body) {
  299. if (node.type === 'ExportDefaultDeclaration') {
  300. isEsModule = true;
  301. hasDefaultExport = true;
  302. } else if (node.type === 'ExportNamedDeclaration') {
  303. isEsModule = true;
  304. if (node.declaration) {
  305. hasNamedExports = true;
  306. } else {
  307. for (const specifier of node.specifiers) {
  308. if (specifier.exported.name === 'default') {
  309. hasDefaultExport = true;
  310. } else {
  311. hasNamedExports = true;
  312. }
  313. }
  314. }
  315. } else if (node.type === 'ExportAllDeclaration') {
  316. isEsModule = true;
  317. if (node.exported && node.exported.name === 'default') {
  318. hasDefaultExport = true;
  319. } else {
  320. hasNamedExports = true;
  321. }
  322. } else if (node.type === 'ImportDeclaration') {
  323. isEsModule = true;
  324. }
  325. }
  326. return { isEsModule, hasDefaultExport, hasNamedExports, ast };
  327. }
  328. function getDefinePropertyCallName(node, targetName) {
  329. if (node.type !== 'CallExpression') return;
  330. const {
  331. callee: { object, property }
  332. } = node;
  333. if (!object || object.type !== 'Identifier' || object.name !== 'Object') return;
  334. if (!property || property.type !== 'Identifier' || property.name !== 'defineProperty') return;
  335. if (node.arguments.length !== 3) return;
  336. const [target, val] = node.arguments;
  337. if (target.type !== 'Identifier' || target.name !== targetName) return;
  338. // eslint-disable-next-line consistent-return
  339. return val.value;
  340. }
  341. function transformCommonjs(
  342. parse,
  343. code,
  344. id,
  345. isEsModule,
  346. ignoreGlobal,
  347. ignoreRequire,
  348. sourceMap,
  349. isDynamicRequireModulesEnabled,
  350. dynamicRequireModuleSet,
  351. commonDir,
  352. astCache
  353. ) {
  354. const ast = astCache || tryParse(parse, code, id);
  355. const magicString = new MagicString(code);
  356. const required = {};
  357. // Because objects have no guaranteed ordering, yet we need it,
  358. // we need to keep track of the order in a array
  359. const sources = [];
  360. let uid = 0;
  361. let scope = pluginutils.attachScopes(ast, 'scope');
  362. const uses = { module: false, exports: false, global: false, require: false };
  363. let lexicalDepth = 0;
  364. let programDepth = 0;
  365. const globals = new Set();
  366. // TODO technically wrong since globals isn't populated yet, but ¯\_(ツ)_/¯
  367. const HELPERS_NAME = deconflict(scope, globals, 'commonjsHelpers');
  368. const namedExports = {};
  369. // TODO handle transpiled modules
  370. let shouldWrap = /__esModule/.test(code);
  371. let usesCommonjsHelpers = false;
  372. function isRequireStatement(node) {
  373. if (!node) return false;
  374. if (node.type !== 'CallExpression') return false;
  375. // Weird case of `require()` or `module.require()` without arguments
  376. if (node.arguments.length === 0) return false;
  377. return isRequireIdentifier(node.callee);
  378. }
  379. function isRequireIdentifier(node) {
  380. if (!node) return false;
  381. if (node.type === 'Identifier' && node.name === 'require' /* `require` */) {
  382. // `require` is hidden by a variable in local scope
  383. if (scope.contains('require')) return false;
  384. return true;
  385. } else if (node.type === 'MemberExpression' /* `[something].[something]` */) {
  386. // `module.[something]`
  387. if (node.object.type !== 'Identifier' || node.object.name !== 'module') return false;
  388. // `module` is hidden by a variable in local scope
  389. if (scope.contains('module')) return false;
  390. // `module.require(...)`
  391. if (node.property.type !== 'Identifier' || node.property.name !== 'require') return false;
  392. return true;
  393. }
  394. return false;
  395. }
  396. function hasDynamicArguments(node) {
  397. return (
  398. node.arguments.length > 1 ||
  399. (node.arguments[0].type !== 'Literal' &&
  400. (node.arguments[0].type !== 'TemplateLiteral' || node.arguments[0].expressions.length > 0))
  401. );
  402. }
  403. function isStaticRequireStatement(node) {
  404. if (!isRequireStatement(node)) return false;
  405. return !hasDynamicArguments(node);
  406. }
  407. function isNodeRequireStatement(parent) {
  408. const reservedMethod = ['resolve', 'cache', 'main'];
  409. return !!(parent && parent.property && reservedMethod.indexOf(parent.property.name) > -1);
  410. }
  411. function isIgnoredRequireStatement(requiredNode) {
  412. return ignoreRequire(requiredNode.arguments[0].value);
  413. }
  414. function getRequireStringArg(node) {
  415. return node.arguments[0].type === 'Literal'
  416. ? node.arguments[0].value
  417. : node.arguments[0].quasis[0].value.cooked;
  418. }
  419. function getRequired(node, name) {
  420. let sourceId = getRequireStringArg(node);
  421. const isDynamicRegister = sourceId.startsWith(DYNAMIC_REGISTER_PREFIX);
  422. if (isDynamicRegister) {
  423. sourceId = sourceId.substr(DYNAMIC_REGISTER_PREFIX.length);
  424. }
  425. const existing = required[sourceId];
  426. // eslint-disable-next-line no-undefined
  427. if (existing === undefined) {
  428. const isDynamic = hasDynamicModuleForPath(sourceId);
  429. if (!name) {
  430. do {
  431. name = `require$$${uid}`;
  432. uid += 1;
  433. } while (scope.contains(name));
  434. }
  435. if (isDynamicRegister && sourceId.endsWith('.json')) {
  436. sourceId = DYNAMIC_JSON_PREFIX + sourceId;
  437. }
  438. if (isDynamicRegister || !isDynamic || sourceId.endsWith('.json')) {
  439. sources.push([sourceId, !isDynamicRegister]);
  440. }
  441. required[sourceId] = { source: sourceId, name, importsDefault: false, isDynamic };
  442. }
  443. return required[sourceId];
  444. }
  445. function hasDynamicModuleForPath(source) {
  446. if (!/[/\\]/.test(source)) {
  447. try {
  448. const resolvedPath = normalizePathSlashes(
  449. resolve.sync(source, { basedir: path.dirname(id) })
  450. );
  451. if (dynamicRequireModuleSet.has(resolvedPath)) {
  452. return true;
  453. }
  454. } catch (ex) {
  455. // Probably a node.js internal module
  456. return false;
  457. }
  458. return false;
  459. }
  460. for (const attemptExt of ['', '.js', '.json']) {
  461. const resolvedPath = normalizePathSlashes(path.resolve(path.dirname(id), source + attemptExt));
  462. if (dynamicRequireModuleSet.has(resolvedPath)) {
  463. return true;
  464. }
  465. }
  466. return false;
  467. }
  468. function shouldUseSimulatedRequire(required) {
  469. return (
  470. hasDynamicModuleForPath(required.source) &&
  471. // We only do `commonjsRequire` for json if it's the `commonjsRegister` call.
  472. (required.source.startsWith(DYNAMIC_REGISTER_PREFIX) || !required.source.endsWith('.json'))
  473. );
  474. }
  475. // do a first pass, see which names are assigned to. This is necessary to prevent
  476. // illegally replacing `var foo = require('foo')` with `import foo from 'foo'`,
  477. // where `foo` is later reassigned. (This happens in the wild. CommonJS, sigh)
  478. const assignedTo = new Set();
  479. estreeWalker.walk(ast, {
  480. enter(node) {
  481. if (node.type !== 'AssignmentExpression') return;
  482. if (node.left.type === 'MemberExpression') return;
  483. pluginutils.extractAssignedNames(node.left).forEach((name) => {
  484. assignedTo.add(name);
  485. });
  486. }
  487. });
  488. estreeWalker.walk(ast, {
  489. enter(node, parent) {
  490. if (sourceMap) {
  491. magicString.addSourcemapLocation(node.start);
  492. magicString.addSourcemapLocation(node.end);
  493. }
  494. // skip dead branches
  495. if (parent && (parent.type === 'IfStatement' || parent.type === 'ConditionalExpression')) {
  496. if (node === parent.consequent && isFalsy(parent.test)) {
  497. this.skip();
  498. return;
  499. }
  500. if (node === parent.alternate && isTruthy(parent.test)) {
  501. this.skip();
  502. return;
  503. }
  504. }
  505. if (node._skip) {
  506. this.skip();
  507. return;
  508. }
  509. programDepth += 1;
  510. if (node.scope) ({ scope } = node);
  511. if (functionType.test(node.type)) lexicalDepth += 1;
  512. // if toplevel return, we need to wrap it
  513. if (node.type === 'ReturnStatement' && lexicalDepth === 0) {
  514. shouldWrap = true;
  515. }
  516. // rewrite `this` as `commonjsHelpers.commonjsGlobal`
  517. if (node.type === 'ThisExpression' && lexicalDepth === 0) {
  518. uses.global = true;
  519. if (!ignoreGlobal) {
  520. magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsGlobal`, {
  521. storeName: true
  522. });
  523. usesCommonjsHelpers = true;
  524. }
  525. return;
  526. }
  527. // rewrite `typeof module`, `typeof module.exports` and `typeof exports` (https://github.com/rollup/rollup-plugin-commonjs/issues/151)
  528. if (node.type === 'UnaryExpression' && node.operator === 'typeof') {
  529. const flattened = flatten(node.argument);
  530. if (!flattened) return;
  531. if (scope.contains(flattened.name)) return;
  532. if (
  533. flattened.keypath === 'module.exports' ||
  534. flattened.keypath === 'module' ||
  535. flattened.keypath === 'exports'
  536. ) {
  537. magicString.overwrite(node.start, node.end, `'object'`, { storeName: false });
  538. }
  539. }
  540. // rewrite `require` (if not already handled) `global` and `define`, and handle free references to
  541. // `module` and `exports` as these mean we need to wrap the module in commonjsHelpers.createCommonjsModule
  542. if (node.type === 'Identifier') {
  543. if (isReference(node, parent) && !scope.contains(node.name)) {
  544. if (node.name in uses) {
  545. if (isRequireIdentifier(node)) {
  546. if (isNodeRequireStatement(parent)) {
  547. return;
  548. }
  549. if (!isDynamicRequireModulesEnabled && isStaticRequireStatement(parent)) {
  550. return;
  551. }
  552. if (isDynamicRequireModulesEnabled && isRequireStatement(parent)) {
  553. magicString.appendLeft(
  554. parent.end - 1,
  555. `,${JSON.stringify(
  556. path.dirname(id) === '.'
  557. ? null /* default behavior */
  558. : getVirtualPathForDynamicRequirePath(
  559. normalizePathSlashes(path.dirname(id)),
  560. commonDir
  561. )
  562. )}`
  563. );
  564. }
  565. magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsRequire`, {
  566. storeName: true
  567. });
  568. usesCommonjsHelpers = true;
  569. }
  570. uses[node.name] = true;
  571. if (node.name === 'global' && !ignoreGlobal) {
  572. magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsGlobal`, {
  573. storeName: true
  574. });
  575. usesCommonjsHelpers = true;
  576. }
  577. // if module or exports are used outside the context of an assignment
  578. // expression, we need to wrap the module
  579. if (node.name === 'module' || node.name === 'exports') {
  580. shouldWrap = true;
  581. }
  582. }
  583. if (node.name === 'define') {
  584. magicString.overwrite(node.start, node.end, 'undefined', { storeName: true });
  585. }
  586. globals.add(node.name);
  587. }
  588. return;
  589. }
  590. // Is this an assignment to exports or module.exports?
  591. if (node.type === 'AssignmentExpression') {
  592. if (node.left.type !== 'MemberExpression') return;
  593. const flattened = flatten(node.left);
  594. if (!flattened) return;
  595. if (scope.contains(flattened.name)) return;
  596. const match = exportsPattern.exec(flattened.keypath);
  597. if (!match || flattened.keypath === 'exports') return;
  598. uses[flattened.name] = true;
  599. // we're dealing with `module.exports = ...` or `[module.]exports.foo = ...` –
  600. // if this isn't top-level, we'll need to wrap the module
  601. if (programDepth > 3) shouldWrap = true;
  602. node.left._skip = true;
  603. if (flattened.keypath === 'module.exports' && node.right.type === 'ObjectExpression') {
  604. node.right.properties.forEach((prop) => {
  605. if (prop.computed || !('key' in prop) || prop.key.type !== 'Identifier') return;
  606. const { name } = prop.key;
  607. if (name === pluginutils.makeLegalIdentifier(name)) namedExports[name] = true;
  608. });
  609. return;
  610. }
  611. if (match[1]) namedExports[match[1]] = true;
  612. return;
  613. }
  614. const name = getDefinePropertyCallName(node, 'exports');
  615. if (name && name === pluginutils.makeLegalIdentifier(name)) namedExports[name] = true;
  616. // if this is `var x = require('x')`, we can do `import x from 'x'`
  617. if (
  618. node.type === 'VariableDeclarator' &&
  619. node.id.type === 'Identifier' &&
  620. isStaticRequireStatement(node.init) &&
  621. !isIgnoredRequireStatement(node.init)
  622. ) {
  623. // for now, only do this for top-level requires. maybe fix this in future
  624. if (scope.parent) return;
  625. // edge case — CJS allows you to assign to imports. ES doesn't
  626. if (assignedTo.has(node.id.name)) return;
  627. const required = getRequired(node.init, node.id.name);
  628. required.importsDefault = true;
  629. if (required.name === node.id.name && !required.isDynamic) {
  630. node._shouldRemove = true;
  631. }
  632. }
  633. if (!isStaticRequireStatement(node) || isIgnoredRequireStatement(node)) {
  634. return;
  635. }
  636. const required = getRequired(node);
  637. if (parent.type === 'ExpressionStatement') {
  638. // is a bare import, e.g. `require('foo');`
  639. magicString.remove(parent.start, parent.end);
  640. } else {
  641. required.importsDefault = true;
  642. if (shouldUseSimulatedRequire(required)) {
  643. magicString.overwrite(
  644. node.start,
  645. node.end,
  646. `${HELPERS_NAME}.commonjsRequire(${JSON.stringify(
  647. getVirtualPathForDynamicRequirePath(normalizePathSlashes(required.source), commonDir)
  648. )}, ${JSON.stringify(
  649. path.dirname(id) === '.'
  650. ? null /* default behavior */
  651. : getVirtualPathForDynamicRequirePath(normalizePathSlashes(path.dirname(id)), commonDir)
  652. )})`
  653. );
  654. usesCommonjsHelpers = true;
  655. } else {
  656. magicString.overwrite(node.start, node.end, required.name);
  657. }
  658. }
  659. node.callee._skip = true;
  660. },
  661. leave(node) {
  662. programDepth -= 1;
  663. if (node.scope) scope = scope.parent;
  664. if (functionType.test(node.type)) lexicalDepth -= 1;
  665. if (node.type === 'VariableDeclaration') {
  666. let keepDeclaration = false;
  667. let c = node.declarations[0].start;
  668. for (let i = 0; i < node.declarations.length; i += 1) {
  669. const declarator = node.declarations[i];
  670. if (declarator._shouldRemove) {
  671. magicString.remove(c, declarator.end);
  672. } else {
  673. if (!keepDeclaration) {
  674. magicString.remove(c, declarator.start);
  675. keepDeclaration = true;
  676. }
  677. c = declarator.end;
  678. }
  679. }
  680. if (!keepDeclaration) {
  681. magicString.remove(node.start, node.end);
  682. }
  683. }
  684. }
  685. });
  686. if (
  687. !sources.length &&
  688. !uses.module &&
  689. !uses.exports &&
  690. !uses.require &&
  691. (ignoreGlobal || !uses.global)
  692. ) {
  693. // not a CommonJS module
  694. return null;
  695. }
  696. // If `isEsModule` is on, it means it has ES6 import/export statements,
  697. // which just can't be wrapped in a function.
  698. if (isEsModule) shouldWrap = false;
  699. usesCommonjsHelpers = usesCommonjsHelpers || shouldWrap;
  700. const importBlock = `${(usesCommonjsHelpers
  701. ? [`import * as ${HELPERS_NAME} from '${HELPERS_ID}';`]
  702. : []
  703. )
  704. .concat(
  705. sources.map(
  706. ([source]) =>
  707. // import the actual module before the proxy, so that we know
  708. // what kind of proxy to build
  709. `import '${source}';`
  710. ),
  711. sources
  712. .filter(([, importProxy]) => importProxy)
  713. .map(([source]) => {
  714. const { name, importsDefault } = required[source];
  715. return `import ${importsDefault ? `${name} from ` : ``}'${
  716. source.startsWith('\0') ? source : getProxyId(source)
  717. }';`;
  718. })
  719. )
  720. .join('\n')}\n\n`;
  721. const namedExportDeclarations = [];
  722. let wrapperStart = '';
  723. let wrapperEnd = '';
  724. const moduleName = deconflict(scope, globals, getName(id));
  725. if (!isEsModule) {
  726. const exportModuleExports = {
  727. str: `export { ${moduleName} as __moduleExports };`,
  728. name: '__moduleExports'
  729. };
  730. namedExportDeclarations.push(exportModuleExports);
  731. }
  732. const defaultExportPropertyAssignments = [];
  733. let hasDefaultExport = false;
  734. if (shouldWrap) {
  735. const args = `module${uses.exports ? ', exports' : ''}`;
  736. wrapperStart = `var ${moduleName} = ${HELPERS_NAME}.createCommonjsModule(function (${args}) {\n`;
  737. wrapperEnd = `\n}`;
  738. if (isDynamicRequireModulesEnabled) {
  739. wrapperEnd += `, ${JSON.stringify(
  740. getVirtualPathForDynamicRequirePath(normalizePathSlashes(path.dirname(id)), commonDir)
  741. )}`;
  742. }
  743. wrapperEnd += `);`;
  744. } else {
  745. const names = [];
  746. for (const node of ast.body) {
  747. if (node.type === 'ExpressionStatement' && node.expression.type === 'AssignmentExpression') {
  748. const { left } = node.expression;
  749. const flattened = flatten(left);
  750. if (!flattened) {
  751. continue;
  752. }
  753. const match = exportsPattern.exec(flattened.keypath);
  754. if (!match) {
  755. continue;
  756. }
  757. if (flattened.keypath === 'module.exports') {
  758. hasDefaultExport = true;
  759. magicString.overwrite(left.start, left.end, `var ${moduleName}`);
  760. } else {
  761. const [, name] = match;
  762. const deconflicted = deconflict(scope, globals, name);
  763. names.push({ name, deconflicted });
  764. magicString.overwrite(node.start, left.end, `var ${deconflicted}`);
  765. const declaration =
  766. name === deconflicted
  767. ? `export { ${name} };`
  768. : `export { ${deconflicted} as ${name} };`;
  769. if (name !== 'default') {
  770. namedExportDeclarations.push({
  771. str: declaration,
  772. name
  773. });
  774. }
  775. defaultExportPropertyAssignments.push(`${moduleName}.${name} = ${deconflicted};`);
  776. }
  777. }
  778. }
  779. if (!(isEsModule || hasDefaultExport)) {
  780. wrapperEnd = `\n\nvar ${moduleName} = {\n${names
  781. .map(({ name, deconflicted }) => `\t${name}: ${deconflicted}`)
  782. .join(',\n')}\n};`;
  783. }
  784. }
  785. magicString
  786. .trim()
  787. .prepend(importBlock + wrapperStart)
  788. .trim()
  789. .append(wrapperEnd);
  790. const defaultExport =
  791. code.indexOf('__esModule') >= 0
  792. ? `export default /*@__PURE__*/${HELPERS_NAME}.getDefaultExportFromCjs(${moduleName});`
  793. : `export default ${moduleName};`;
  794. const named = namedExportDeclarations
  795. .filter((x) => x.name !== 'default' || !hasDefaultExport)
  796. .map((x) => x.str);
  797. magicString.append(
  798. `\n\n${(isEsModule ? [] : [defaultExport])
  799. .concat(named)
  800. .concat(hasDefaultExport ? defaultExportPropertyAssignments : [])
  801. .join('\n')}`
  802. );
  803. code = magicString.toString();
  804. const map = sourceMap ? magicString.generateMap() : null;
  805. return { code, map, syntheticNamedExports: isEsModule ? false : '__moduleExports' };
  806. }
  807. function getDynamicPackagesModule(dynamicRequireModuleDirPaths, commonDir) {
  808. let code = `const commonjsRegister = require('${HELPERS_ID}?commonjsRegister');`;
  809. for (const dir of dynamicRequireModuleDirPaths) {
  810. let entryPoint = 'index.js';
  811. try {
  812. if (fs.existsSync(path.join(dir, 'package.json'))) {
  813. entryPoint =
  814. JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), { encoding: 'utf8' })).main ||
  815. entryPoint;
  816. }
  817. } catch (ignored) {
  818. // ignored
  819. }
  820. code += `\ncommonjsRegister(${JSON.stringify(
  821. getVirtualPathForDynamicRequirePath(dir, commonDir)
  822. )}, function (module, exports) {
  823. module.exports = require(${JSON.stringify(normalizePathSlashes(path.join(dir, entryPoint)))});
  824. });`;
  825. }
  826. return code;
  827. }
  828. function getDynamicPackagesEntryIntro(
  829. id,
  830. dynamicRequireModuleDirPaths,
  831. dynamicRequireModuleSet
  832. ) {
  833. try {
  834. const code = fs.readFileSync(id, { encoding: 'utf8' });
  835. let dynamicImports = Array.from(
  836. dynamicRequireModuleSet,
  837. (dynamicId) => `require(${JSON.stringify(DYNAMIC_REGISTER_PREFIX + dynamicId)});`
  838. ).join('\n');
  839. if (dynamicRequireModuleDirPaths.length) {
  840. dynamicImports += `require(${JSON.stringify(
  841. DYNAMIC_REGISTER_PREFIX + DYNAMIC_PACKAGES_ID
  842. )});`;
  843. }
  844. return `${dynamicImports}\n${code}`;
  845. } catch (ex) {
  846. this.warn(`Failed to read file ${id}, dynamic modules might not work correctly`);
  847. return null;
  848. }
  849. }
  850. function getDynamicRequirePaths(patterns) {
  851. const dynamicRequireModuleSet = new Set();
  852. for (const pattern of !patterns || Array.isArray(patterns) ? patterns || [] : [patterns]) {
  853. const isNegated = pattern.startsWith('!');
  854. const modifySet = Set.prototype[isNegated ? 'delete' : 'add'].bind(dynamicRequireModuleSet);
  855. for (const path$1 of glob.sync(isNegated ? pattern.substr(1) : pattern)) {
  856. modifySet(normalizePathSlashes(path.resolve(path$1)));
  857. }
  858. }
  859. const dynamicRequireModuleDirPaths = Array.from(dynamicRequireModuleSet.values()).filter(
  860. (path) => {
  861. try {
  862. if (fs.statSync(path).isDirectory()) return true;
  863. } catch (ignored) {
  864. // Nothing to do here
  865. }
  866. return false;
  867. }
  868. );
  869. return { dynamicRequireModuleSet, dynamicRequireModuleDirPaths };
  870. }
  871. /* eslint-disable no-undefined */
  872. const isCjsPromises = new Map();
  873. function getIsCjsPromise(id) {
  874. let isCjsPromise = isCjsPromises.get(id);
  875. if (isCjsPromise) return isCjsPromise.promise;
  876. const promise = new Promise((resolve) => {
  877. isCjsPromise = {
  878. resolve,
  879. promise: undefined
  880. };
  881. isCjsPromises.set(id, isCjsPromise);
  882. });
  883. isCjsPromise.promise = promise;
  884. return promise;
  885. }
  886. function setIsCjsPromise(id, resolution) {
  887. const isCjsPromise = isCjsPromises.get(id);
  888. if (isCjsPromise) {
  889. if (isCjsPromise.resolve) {
  890. isCjsPromise.resolve(resolution);
  891. isCjsPromise.resolve = undefined;
  892. }
  893. } else {
  894. isCjsPromises.set(id, { promise: Promise.resolve(resolution), resolve: undefined });
  895. }
  896. }
  897. // e.g. id === "commonjsHelpers?commonjsRegister"
  898. function getSpecificHelperProxy(id) {
  899. return `export {${id.split('?')[1]} as default} from '${HELPERS_ID}';`;
  900. }
  901. function getUnknownRequireProxy(id, requireReturnsDefault) {
  902. if (requireReturnsDefault === true || id.endsWith('.json')) {
  903. return `export {default} from ${JSON.stringify(id)};`;
  904. }
  905. const name = getName(id);
  906. const exported =
  907. requireReturnsDefault === 'auto'
  908. ? `import {getDefaultExportFromNamespaceIfNotNamed} from "${HELPERS_ID}"; export default /*@__PURE__*/getDefaultExportFromNamespaceIfNotNamed(${name});`
  909. : requireReturnsDefault === 'preferred'
  910. ? `import {getDefaultExportFromNamespaceIfPresent} from "${HELPERS_ID}"; export default /*@__PURE__*/getDefaultExportFromNamespaceIfPresent(${name});`
  911. : !requireReturnsDefault
  912. ? `import {getAugmentedNamespace} from "${HELPERS_ID}"; export default /*@__PURE__*/getAugmentedNamespace(${name});`
  913. : `export default ${name};`;
  914. return `import * as ${name} from ${JSON.stringify(id)}; ${exported}`;
  915. }
  916. function getDynamicJsonProxy(id, commonDir) {
  917. const normalizedPath = normalizePathSlashes(id.slice(DYNAMIC_JSON_PREFIX.length));
  918. return `const commonjsRegister = require('${HELPERS_ID}?commonjsRegister');\ncommonjsRegister(${JSON.stringify(
  919. getVirtualPathForDynamicRequirePath(normalizedPath, commonDir)
  920. )}, function (module, exports) {
  921. module.exports = require(${JSON.stringify(normalizedPath)});
  922. });`;
  923. }
  924. function getDynamicRequireProxy(normalizedPath, commonDir) {
  925. return `const commonjsRegister = require('${HELPERS_ID}?commonjsRegister');\ncommonjsRegister(${JSON.stringify(
  926. getVirtualPathForDynamicRequirePath(normalizedPath, commonDir)
  927. )}, function (module, exports) {
  928. ${fs.readFileSync(normalizedPath, { encoding: 'utf8' })}
  929. });`;
  930. }
  931. async function getStaticRequireProxy(
  932. id,
  933. requireReturnsDefault,
  934. esModulesWithDefaultExport,
  935. esModulesWithNamedExports
  936. ) {
  937. const name = getName(id);
  938. const isCjs = await getIsCjsPromise(id);
  939. if (isCjs) {
  940. return `import { __moduleExports } from ${JSON.stringify(id)}; export default __moduleExports;`;
  941. } else if (isCjs === null) {
  942. return getUnknownRequireProxy(id, requireReturnsDefault);
  943. } else if (!requireReturnsDefault) {
  944. return `import {getAugmentedNamespace} from "${HELPERS_ID}"; import * as ${name} from ${JSON.stringify(
  945. id
  946. )}; export default /*@__PURE__*/getAugmentedNamespace(${name});`;
  947. } else if (
  948. requireReturnsDefault !== true &&
  949. (requireReturnsDefault === 'namespace' ||
  950. !esModulesWithDefaultExport.has(id) ||
  951. (requireReturnsDefault === 'auto' && esModulesWithNamedExports.has(id)))
  952. ) {
  953. return `import * as ${name} from ${JSON.stringify(id)}; export default ${name};`;
  954. }
  955. return `export {default} from ${JSON.stringify(id)};`;
  956. }
  957. /* eslint-disable no-param-reassign, no-undefined */
  958. function getCandidatesForExtension(resolved, extension) {
  959. return [resolved + extension, `${resolved}${path.sep}index${extension}`];
  960. }
  961. function getCandidates(resolved, extensions) {
  962. return extensions.reduce(
  963. (paths, extension) => paths.concat(getCandidatesForExtension(resolved, extension)),
  964. [resolved]
  965. );
  966. }
  967. function getResolveId(extensions) {
  968. function resolveExtensions(importee, importer) {
  969. // not our problem
  970. if (importee[0] !== '.' || !importer) return undefined;
  971. const resolved = path.resolve(path.dirname(importer), importee);
  972. const candidates = getCandidates(resolved, extensions);
  973. for (let i = 0; i < candidates.length; i += 1) {
  974. try {
  975. const stats = fs.statSync(candidates[i]);
  976. if (stats.isFile()) return { id: candidates[i] };
  977. } catch (err) {
  978. /* noop */
  979. }
  980. }
  981. return undefined;
  982. }
  983. function resolveId(importee, importer) {
  984. const isProxyModule = importee.endsWith(PROXY_SUFFIX);
  985. if (isProxyModule) {
  986. importee = getIdFromProxyId(importee);
  987. }
  988. if (importee.startsWith('\0')) {
  989. if (
  990. importee.startsWith(HELPERS_ID) ||
  991. importee === DYNAMIC_PACKAGES_ID ||
  992. importee.startsWith(DYNAMIC_JSON_PREFIX)
  993. ) {
  994. return importee;
  995. }
  996. if (!isProxyModule) {
  997. return null;
  998. }
  999. }
  1000. if (importer && importer.endsWith(PROXY_SUFFIX)) {
  1001. importer = getIdFromProxyId(importer);
  1002. }
  1003. return this.resolve(importee, importer, { skipSelf: true }).then((resolved) => {
  1004. if (!resolved) {
  1005. resolved = resolveExtensions(importee, importer);
  1006. }
  1007. if (isProxyModule) {
  1008. if (!resolved) {
  1009. return { id: getExternalProxyId(importee), external: false };
  1010. }
  1011. resolved.id = (resolved.external ? getExternalProxyId : getProxyId)(resolved.id);
  1012. resolved.external = false;
  1013. return resolved;
  1014. }
  1015. return resolved;
  1016. });
  1017. }
  1018. return resolveId;
  1019. }
  1020. function commonjs(options = {}) {
  1021. const extensions = options.extensions || ['.js'];
  1022. const filter = pluginutils.createFilter(options.include, options.exclude);
  1023. const {
  1024. ignoreGlobal,
  1025. requireReturnsDefault: requireReturnsDefaultOption,
  1026. esmExternals
  1027. } = options;
  1028. const getRequireReturnsDefault =
  1029. typeof requireReturnsDefaultOption === 'function'
  1030. ? requireReturnsDefaultOption
  1031. : () => requireReturnsDefaultOption;
  1032. let esmExternalIds;
  1033. const isEsmExternal =
  1034. typeof esmExternals === 'function'
  1035. ? esmExternals
  1036. : Array.isArray(esmExternals)
  1037. ? ((esmExternalIds = new Set(esmExternals)), (id) => esmExternalIds.has(id))
  1038. : () => esmExternals;
  1039. const { dynamicRequireModuleSet, dynamicRequireModuleDirPaths } = getDynamicRequirePaths(
  1040. options.dynamicRequireTargets
  1041. );
  1042. const isDynamicRequireModulesEnabled = dynamicRequireModuleSet.size > 0;
  1043. const commonDir = isDynamicRequireModulesEnabled
  1044. ? getCommonDir(null, Array.from(dynamicRequireModuleSet).concat(process.cwd()))
  1045. : null;
  1046. const esModulesWithDefaultExport = new Set();
  1047. const esModulesWithNamedExports = new Set();
  1048. const ignoreRequire =
  1049. typeof options.ignore === 'function'
  1050. ? options.ignore
  1051. : Array.isArray(options.ignore)
  1052. ? (id) => options.ignore.includes(id)
  1053. : () => false;
  1054. const resolveId = getResolveId(extensions);
  1055. const sourceMap = options.sourceMap !== false;
  1056. function transformAndCheckExports(code, id) {
  1057. const { isEsModule, hasDefaultExport, hasNamedExports, ast } = checkEsModule(
  1058. this.parse,
  1059. code,
  1060. id
  1061. );
  1062. if (hasDefaultExport) {
  1063. esModulesWithDefaultExport.add(id);
  1064. }
  1065. if (hasNamedExports) {
  1066. esModulesWithNamedExports.add(id);
  1067. }
  1068. if (
  1069. !dynamicRequireModuleSet.has(normalizePathSlashes(id)) &&
  1070. (!hasCjsKeywords(code, ignoreGlobal) || (isEsModule && !options.transformMixedEsModules))
  1071. ) {
  1072. setIsCjsPromise(id, false);
  1073. return null;
  1074. }
  1075. const transformed = transformCommonjs(
  1076. this.parse,
  1077. code,
  1078. id,
  1079. isEsModule,
  1080. ignoreGlobal || isEsModule,
  1081. ignoreRequire,
  1082. sourceMap,
  1083. isDynamicRequireModulesEnabled,
  1084. dynamicRequireModuleSet,
  1085. commonDir,
  1086. ast
  1087. );
  1088. setIsCjsPromise(id, isEsModule ? false : Boolean(transformed));
  1089. return transformed;
  1090. }
  1091. return {
  1092. name: 'commonjs',
  1093. buildStart() {
  1094. if (options.namedExports != null) {
  1095. this.warn(
  1096. 'The namedExports option from "@rollup/plugin-commonjs" is deprecated. Named exports are now handled automatically.'
  1097. );
  1098. }
  1099. const [major, minor] = this.meta.rollupVersion.split('.').map(Number);
  1100. const minVersion = peerDependencies.rollup.slice(2);
  1101. const [minMajor, minMinor] = minVersion.split('.').map(Number);
  1102. if (major < minMajor || (major === minMajor && minor < minMinor)) {
  1103. this.error(
  1104. `Insufficient Rollup version: "@rollup/plugin-commonjs" requires at least rollup@${minVersion} but found rollup@${this.meta.rollupVersion}.`
  1105. );
  1106. }
  1107. },
  1108. resolveId,
  1109. load(id) {
  1110. if (id === HELPERS_ID) {
  1111. return getHelpersModule(isDynamicRequireModulesEnabled);
  1112. }
  1113. if (id.startsWith(HELPERS_ID)) {
  1114. return getSpecificHelperProxy(id);
  1115. }
  1116. if (id.endsWith(EXTERNAL_SUFFIX)) {
  1117. const actualId = getIdFromExternalProxyId(id);
  1118. return getUnknownRequireProxy(
  1119. actualId,
  1120. isEsmExternal(actualId) ? getRequireReturnsDefault(actualId) : true
  1121. );
  1122. }
  1123. if (id === DYNAMIC_PACKAGES_ID) {
  1124. return getDynamicPackagesModule(dynamicRequireModuleDirPaths, commonDir);
  1125. }
  1126. if (id.startsWith(DYNAMIC_JSON_PREFIX)) {
  1127. return getDynamicJsonProxy(id, commonDir);
  1128. }
  1129. const normalizedPath = normalizePathSlashes(id);
  1130. if (dynamicRequireModuleSet.has(normalizedPath) && !normalizedPath.endsWith('.json')) {
  1131. return getDynamicRequireProxy(normalizedPath, commonDir);
  1132. }
  1133. if (id.endsWith(PROXY_SUFFIX)) {
  1134. const actualId = getIdFromProxyId(id);
  1135. return getStaticRequireProxy(
  1136. actualId,
  1137. getRequireReturnsDefault(actualId),
  1138. esModulesWithDefaultExport,
  1139. esModulesWithNamedExports
  1140. );
  1141. }
  1142. if (isDynamicRequireModulesEnabled && this.getModuleInfo(id).isEntry) {
  1143. return getDynamicPackagesEntryIntro(
  1144. id,
  1145. dynamicRequireModuleDirPaths,
  1146. dynamicRequireModuleSet
  1147. );
  1148. }
  1149. return null;
  1150. },
  1151. transform(code, id) {
  1152. const extName = path.extname(id);
  1153. if (
  1154. extName !== '.cjs' &&
  1155. id !== DYNAMIC_PACKAGES_ID &&
  1156. !id.startsWith(DYNAMIC_JSON_PREFIX) &&
  1157. (!filter(id) || !extensions.includes(extName))
  1158. ) {
  1159. setIsCjsPromise(id, null);
  1160. return null;
  1161. }
  1162. let transformed;
  1163. try {
  1164. transformed = transformAndCheckExports.call(this, code, id);
  1165. } catch (err) {
  1166. transformed = null;
  1167. setIsCjsPromise(id, false);
  1168. this.error(err, err.loc);
  1169. }
  1170. return transformed;
  1171. }
  1172. };
  1173. }
  1174. module.exports = commonjs;
  1175. //# sourceMappingURL=index.js.map