index.es.js 42 KB

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