index.js 71 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', { value: true });
  3. var path = require('path');
  4. var pluginutils = require('@rollup/pluginutils');
  5. var fs = require('fs');
  6. var getCommonDir = require('commondir');
  7. var glob = require('glob');
  8. var estreeWalker = require('estree-walker');
  9. var MagicString = require('magic-string');
  10. var isReference = require('is-reference');
  11. var version = "24.0.0";
  12. var peerDependencies = {
  13. rollup: "^2.68.0||^3.0.0"
  14. };
  15. function tryParse(parse, code, id) {
  16. try {
  17. return parse(code, { allowReturnOutsideFunction: true });
  18. } catch (err) {
  19. err.message += ` in ${id}`;
  20. throw err;
  21. }
  22. }
  23. const firstpassGlobal = /\b(?:require|module|exports|global)\b/;
  24. const firstpassNoGlobal = /\b(?:require|module|exports)\b/;
  25. function hasCjsKeywords(code, ignoreGlobal) {
  26. const firstpass = ignoreGlobal ? firstpassNoGlobal : firstpassGlobal;
  27. return firstpass.test(code);
  28. }
  29. /* eslint-disable no-underscore-dangle */
  30. function analyzeTopLevelStatements(parse, code, id) {
  31. const ast = tryParse(parse, code, id);
  32. let isEsModule = false;
  33. let hasDefaultExport = false;
  34. let hasNamedExports = false;
  35. for (const node of ast.body) {
  36. switch (node.type) {
  37. case 'ExportDefaultDeclaration':
  38. isEsModule = true;
  39. hasDefaultExport = true;
  40. break;
  41. case 'ExportNamedDeclaration':
  42. isEsModule = true;
  43. if (node.declaration) {
  44. hasNamedExports = true;
  45. } else {
  46. for (const specifier of node.specifiers) {
  47. if (specifier.exported.name === 'default') {
  48. hasDefaultExport = true;
  49. } else {
  50. hasNamedExports = true;
  51. }
  52. }
  53. }
  54. break;
  55. case 'ExportAllDeclaration':
  56. isEsModule = true;
  57. if (node.exported && node.exported.name === 'default') {
  58. hasDefaultExport = true;
  59. } else {
  60. hasNamedExports = true;
  61. }
  62. break;
  63. case 'ImportDeclaration':
  64. isEsModule = true;
  65. break;
  66. }
  67. }
  68. return { isEsModule, hasDefaultExport, hasNamedExports, ast };
  69. }
  70. /* eslint-disable import/prefer-default-export */
  71. function deconflict(scopes, globals, identifier) {
  72. let i = 1;
  73. let deconflicted = pluginutils.makeLegalIdentifier(identifier);
  74. const hasConflicts = () =>
  75. scopes.some((scope) => scope.contains(deconflicted)) || globals.has(deconflicted);
  76. while (hasConflicts()) {
  77. deconflicted = pluginutils.makeLegalIdentifier(`${identifier}_${i}`);
  78. i += 1;
  79. }
  80. for (const scope of scopes) {
  81. scope.declarations[deconflicted] = true;
  82. }
  83. return deconflicted;
  84. }
  85. function getName(id) {
  86. const name = pluginutils.makeLegalIdentifier(path.basename(id, path.extname(id)));
  87. if (name !== 'index') {
  88. return name;
  89. }
  90. return pluginutils.makeLegalIdentifier(path.basename(path.dirname(id)));
  91. }
  92. function normalizePathSlashes(path) {
  93. return path.replace(/\\/g, '/');
  94. }
  95. const getVirtualPathForDynamicRequirePath = (path$1, commonDir) =>
  96. `/${normalizePathSlashes(path.relative(commonDir, path$1))}`;
  97. function capitalize(name) {
  98. return name[0].toUpperCase() + name.slice(1);
  99. }
  100. function getStrictRequiresFilter({ strictRequires }) {
  101. switch (strictRequires) {
  102. case true:
  103. return { strictRequiresFilter: () => true, detectCyclesAndConditional: false };
  104. // eslint-disable-next-line no-undefined
  105. case undefined:
  106. case 'auto':
  107. case 'debug':
  108. case null:
  109. return { strictRequiresFilter: () => false, detectCyclesAndConditional: true };
  110. case false:
  111. return { strictRequiresFilter: () => false, detectCyclesAndConditional: false };
  112. default:
  113. if (typeof strictRequires === 'string' || Array.isArray(strictRequires)) {
  114. return {
  115. strictRequiresFilter: pluginutils.createFilter(strictRequires),
  116. detectCyclesAndConditional: false
  117. };
  118. }
  119. throw new Error('Unexpected value for "strictRequires" option.');
  120. }
  121. }
  122. function getPackageEntryPoint(dirPath) {
  123. let entryPoint = 'index.js';
  124. try {
  125. if (fs.existsSync(path.join(dirPath, 'package.json'))) {
  126. entryPoint =
  127. JSON.parse(fs.readFileSync(path.join(dirPath, 'package.json'), { encoding: 'utf8' })).main ||
  128. entryPoint;
  129. }
  130. } catch (ignored) {
  131. // ignored
  132. }
  133. return entryPoint;
  134. }
  135. function isDirectory(path) {
  136. try {
  137. if (fs.statSync(path).isDirectory()) return true;
  138. } catch (ignored) {
  139. // Nothing to do here
  140. }
  141. return false;
  142. }
  143. function getDynamicRequireModules(patterns, dynamicRequireRoot) {
  144. const dynamicRequireModules = new Map();
  145. const dirNames = new Set();
  146. for (const pattern of !patterns || Array.isArray(patterns) ? patterns || [] : [patterns]) {
  147. const isNegated = pattern.startsWith('!');
  148. const modifyMap = (targetPath, resolvedPath) =>
  149. isNegated
  150. ? dynamicRequireModules.delete(targetPath)
  151. : dynamicRequireModules.set(targetPath, resolvedPath);
  152. for (const path$1 of glob.sync(isNegated ? pattern.substr(1) : pattern)) {
  153. const resolvedPath = path.resolve(path$1);
  154. const requirePath = normalizePathSlashes(resolvedPath);
  155. if (isDirectory(resolvedPath)) {
  156. dirNames.add(resolvedPath);
  157. const modulePath = path.resolve(path.join(resolvedPath, getPackageEntryPoint(path$1)));
  158. modifyMap(requirePath, modulePath);
  159. modifyMap(normalizePathSlashes(modulePath), modulePath);
  160. } else {
  161. dirNames.add(path.dirname(resolvedPath));
  162. modifyMap(requirePath, resolvedPath);
  163. }
  164. }
  165. }
  166. return {
  167. commonDir: dirNames.size ? getCommonDir([...dirNames, dynamicRequireRoot]) : null,
  168. dynamicRequireModules
  169. };
  170. }
  171. const FAILED_REQUIRE_ERROR = `throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');`;
  172. const COMMONJS_REQUIRE_EXPORT = 'commonjsRequire';
  173. const CREATE_COMMONJS_REQUIRE_EXPORT = 'createCommonjsRequire';
  174. function getDynamicModuleRegistry(
  175. isDynamicRequireModulesEnabled,
  176. dynamicRequireModules,
  177. commonDir,
  178. ignoreDynamicRequires
  179. ) {
  180. if (!isDynamicRequireModulesEnabled) {
  181. return `export function ${COMMONJS_REQUIRE_EXPORT}(path) {
  182. ${FAILED_REQUIRE_ERROR}
  183. }`;
  184. }
  185. const dynamicModuleImports = [...dynamicRequireModules.values()]
  186. .map(
  187. (id, index) =>
  188. `import ${
  189. id.endsWith('.json') ? `json${index}` : `{ __require as require${index} }`
  190. } from ${JSON.stringify(id)};`
  191. )
  192. .join('\n');
  193. const dynamicModuleProps = [...dynamicRequireModules.keys()]
  194. .map(
  195. (id, index) =>
  196. `\t\t${JSON.stringify(getVirtualPathForDynamicRequirePath(id, commonDir))}: ${
  197. id.endsWith('.json') ? `function () { return json${index}; }` : `require${index}`
  198. }`
  199. )
  200. .join(',\n');
  201. return `${dynamicModuleImports}
  202. var dynamicModules;
  203. function getDynamicModules() {
  204. return dynamicModules || (dynamicModules = {
  205. ${dynamicModuleProps}
  206. });
  207. }
  208. export function ${CREATE_COMMONJS_REQUIRE_EXPORT}(originalModuleDir) {
  209. function handleRequire(path) {
  210. var resolvedPath = commonjsResolve(path, originalModuleDir);
  211. if (resolvedPath !== null) {
  212. return getDynamicModules()[resolvedPath]();
  213. }
  214. ${ignoreDynamicRequires ? 'return require(path);' : FAILED_REQUIRE_ERROR}
  215. }
  216. handleRequire.resolve = function (path) {
  217. var resolvedPath = commonjsResolve(path, originalModuleDir);
  218. if (resolvedPath !== null) {
  219. return resolvedPath;
  220. }
  221. return require.resolve(path);
  222. }
  223. return handleRequire;
  224. }
  225. function commonjsResolve (path, originalModuleDir) {
  226. var shouldTryNodeModules = isPossibleNodeModulesPath(path);
  227. path = normalize(path);
  228. var relPath;
  229. if (path[0] === '/') {
  230. originalModuleDir = '';
  231. }
  232. var modules = getDynamicModules();
  233. var checkedExtensions = ['', '.js', '.json'];
  234. while (true) {
  235. if (!shouldTryNodeModules) {
  236. relPath = normalize(originalModuleDir + '/' + path);
  237. } else {
  238. relPath = normalize(originalModuleDir + '/node_modules/' + path);
  239. }
  240. if (relPath.endsWith('/..')) {
  241. break; // Travelled too far up, avoid infinite loop
  242. }
  243. for (var extensionIndex = 0; extensionIndex < checkedExtensions.length; extensionIndex++) {
  244. var resolvedPath = relPath + checkedExtensions[extensionIndex];
  245. if (modules[resolvedPath]) {
  246. return resolvedPath;
  247. }
  248. }
  249. if (!shouldTryNodeModules) break;
  250. var nextDir = normalize(originalModuleDir + '/..');
  251. if (nextDir === originalModuleDir) break;
  252. originalModuleDir = nextDir;
  253. }
  254. return null;
  255. }
  256. function isPossibleNodeModulesPath (modulePath) {
  257. var c0 = modulePath[0];
  258. if (c0 === '/' || c0 === '\\\\') return false;
  259. var c1 = modulePath[1], c2 = modulePath[2];
  260. if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\\\')) ||
  261. (c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\\\'))) return false;
  262. if (c1 === ':' && (c2 === '/' || c2 === '\\\\')) return false;
  263. return true;
  264. }
  265. function normalize (path) {
  266. path = path.replace(/\\\\/g, '/');
  267. var parts = path.split('/');
  268. var slashed = parts[0] === '';
  269. for (var i = 1; i < parts.length; i++) {
  270. if (parts[i] === '.' || parts[i] === '') {
  271. parts.splice(i--, 1);
  272. }
  273. }
  274. for (var i = 1; i < parts.length; i++) {
  275. if (parts[i] !== '..') continue;
  276. if (i > 0 && parts[i - 1] !== '..' && parts[i - 1] !== '.') {
  277. parts.splice(--i, 2);
  278. i--;
  279. }
  280. }
  281. path = parts.join('/');
  282. if (slashed && path[0] !== '/') path = '/' + path;
  283. else if (path.length === 0) path = '.';
  284. return path;
  285. }`;
  286. }
  287. const isWrappedId = (id, suffix) => id.endsWith(suffix);
  288. const wrapId = (id, suffix) => `\0${id}${suffix}`;
  289. const unwrapId = (wrappedId, suffix) => wrappedId.slice(1, -suffix.length);
  290. const PROXY_SUFFIX = '?commonjs-proxy';
  291. const WRAPPED_SUFFIX = '?commonjs-wrapped';
  292. const EXTERNAL_SUFFIX = '?commonjs-external';
  293. const EXPORTS_SUFFIX = '?commonjs-exports';
  294. const MODULE_SUFFIX = '?commonjs-module';
  295. const ENTRY_SUFFIX = '?commonjs-entry';
  296. const ES_IMPORT_SUFFIX = '?commonjs-es-import';
  297. const DYNAMIC_MODULES_ID = '\0commonjs-dynamic-modules';
  298. const HELPERS_ID = '\0commonjsHelpers.js';
  299. const IS_WRAPPED_COMMONJS = 'withRequireFunction';
  300. // `x['default']` is used instead of `x.default` for backward compatibility with ES3 browsers.
  301. // Minifiers like uglify will usually transpile it back if compatibility with ES3 is not enabled.
  302. // This could be improved by inspecting Rollup's "generatedCode" option
  303. const HELPERS = `
  304. export var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
  305. export function getDefaultExportFromCjs (x) {
  306. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  307. }
  308. export function getDefaultExportFromNamespaceIfPresent (n) {
  309. return n && Object.prototype.hasOwnProperty.call(n, 'default') ? n['default'] : n;
  310. }
  311. export function getDefaultExportFromNamespaceIfNotNamed (n) {
  312. return n && Object.prototype.hasOwnProperty.call(n, 'default') && Object.keys(n).length === 1 ? n['default'] : n;
  313. }
  314. export function getAugmentedNamespace(n) {
  315. if (n.__esModule) return n;
  316. var f = n.default;
  317. if (typeof f == "function") {
  318. var a = function a () {
  319. if (this instanceof a) {
  320. var args = [null];
  321. args.push.apply(args, arguments);
  322. var Ctor = Function.bind.apply(f, args);
  323. return new Ctor();
  324. }
  325. return f.apply(this, arguments);
  326. };
  327. a.prototype = f.prototype;
  328. } else a = {};
  329. Object.defineProperty(a, '__esModule', {value: true});
  330. Object.keys(n).forEach(function (k) {
  331. var d = Object.getOwnPropertyDescriptor(n, k);
  332. Object.defineProperty(a, k, d.get ? d : {
  333. enumerable: true,
  334. get: function () {
  335. return n[k];
  336. }
  337. });
  338. });
  339. return a;
  340. }
  341. `;
  342. function getHelpersModule() {
  343. return HELPERS;
  344. }
  345. function getUnknownRequireProxy(id, requireReturnsDefault) {
  346. if (requireReturnsDefault === true || id.endsWith('.json')) {
  347. return `export { default } from ${JSON.stringify(id)};`;
  348. }
  349. const name = getName(id);
  350. const exported =
  351. requireReturnsDefault === 'auto'
  352. ? `import { getDefaultExportFromNamespaceIfNotNamed } from "${HELPERS_ID}"; export default /*@__PURE__*/getDefaultExportFromNamespaceIfNotNamed(${name});`
  353. : requireReturnsDefault === 'preferred'
  354. ? `import { getDefaultExportFromNamespaceIfPresent } from "${HELPERS_ID}"; export default /*@__PURE__*/getDefaultExportFromNamespaceIfPresent(${name});`
  355. : !requireReturnsDefault
  356. ? `import { getAugmentedNamespace } from "${HELPERS_ID}"; export default /*@__PURE__*/getAugmentedNamespace(${name});`
  357. : `export default ${name};`;
  358. return `import * as ${name} from ${JSON.stringify(id)}; ${exported}`;
  359. }
  360. async function getStaticRequireProxy(id, requireReturnsDefault, loadModule) {
  361. const name = getName(id);
  362. const {
  363. meta: { commonjs: commonjsMeta }
  364. } = await loadModule({ id });
  365. if (!commonjsMeta) {
  366. return getUnknownRequireProxy(id, requireReturnsDefault);
  367. } else if (commonjsMeta.isCommonJS) {
  368. return `export { __moduleExports as default } from ${JSON.stringify(id)};`;
  369. } else if (!requireReturnsDefault) {
  370. return `import { getAugmentedNamespace } from "${HELPERS_ID}"; import * as ${name} from ${JSON.stringify(
  371. id
  372. )}; export default /*@__PURE__*/getAugmentedNamespace(${name});`;
  373. } else if (
  374. requireReturnsDefault !== true &&
  375. (requireReturnsDefault === 'namespace' ||
  376. !commonjsMeta.hasDefaultExport ||
  377. (requireReturnsDefault === 'auto' && commonjsMeta.hasNamedExports))
  378. ) {
  379. return `import * as ${name} from ${JSON.stringify(id)}; export default ${name};`;
  380. }
  381. return `export { default } from ${JSON.stringify(id)};`;
  382. }
  383. function getEntryProxy(id, defaultIsModuleExports, getModuleInfo) {
  384. const {
  385. meta: { commonjs: commonjsMeta },
  386. hasDefaultExport
  387. } = getModuleInfo(id);
  388. if (!commonjsMeta || commonjsMeta.isCommonJS !== IS_WRAPPED_COMMONJS) {
  389. const stringifiedId = JSON.stringify(id);
  390. let code = `export * from ${stringifiedId};`;
  391. if (hasDefaultExport) {
  392. code += `export { default } from ${stringifiedId};`;
  393. }
  394. return code;
  395. }
  396. return getEsImportProxy(id, defaultIsModuleExports);
  397. }
  398. function getEsImportProxy(id, defaultIsModuleExports) {
  399. const name = getName(id);
  400. const exportsName = `${name}Exports`;
  401. const requireModule = `require${capitalize(name)}`;
  402. let code =
  403. `import { getDefaultExportFromCjs } from "${HELPERS_ID}";\n` +
  404. `import { __require as ${requireModule} } from ${JSON.stringify(id)};\n` +
  405. `var ${exportsName} = ${requireModule}();\n` +
  406. `export { ${exportsName} as __moduleExports };`;
  407. if (defaultIsModuleExports === true) {
  408. code += `\nexport { ${exportsName} as default };`;
  409. } else {
  410. code += `export default /*@__PURE__*/getDefaultExportFromCjs(${exportsName});`;
  411. }
  412. return {
  413. code,
  414. syntheticNamedExports: '__moduleExports'
  415. };
  416. }
  417. /* eslint-disable no-param-reassign, no-undefined */
  418. function getCandidatesForExtension(resolved, extension) {
  419. return [resolved + extension, `${resolved}${path.sep}index${extension}`];
  420. }
  421. function getCandidates(resolved, extensions) {
  422. return extensions.reduce(
  423. (paths, extension) => paths.concat(getCandidatesForExtension(resolved, extension)),
  424. [resolved]
  425. );
  426. }
  427. function resolveExtensions(importee, importer, extensions) {
  428. // not our problem
  429. if (importee[0] !== '.' || !importer) return undefined;
  430. const resolved = path.resolve(path.dirname(importer), importee);
  431. const candidates = getCandidates(resolved, extensions);
  432. for (let i = 0; i < candidates.length; i += 1) {
  433. try {
  434. const stats = fs.statSync(candidates[i]);
  435. if (stats.isFile()) return { id: candidates[i] };
  436. } catch (err) {
  437. /* noop */
  438. }
  439. }
  440. return undefined;
  441. }
  442. function getResolveId(extensions, isPossibleCjsId) {
  443. const currentlyResolving = new Map();
  444. return {
  445. /**
  446. * This is a Maps of importers to Sets of require sources being resolved at
  447. * the moment by resolveRequireSourcesAndUpdateMeta
  448. */
  449. currentlyResolving,
  450. async resolveId(importee, importer, resolveOptions) {
  451. const customOptions = resolveOptions.custom;
  452. // All logic below is specific to ES imports.
  453. // Also, if we do not skip this logic for requires that are resolved while
  454. // transforming a commonjs file, it can easily lead to deadlocks.
  455. if (
  456. customOptions &&
  457. customOptions['node-resolve'] &&
  458. customOptions['node-resolve'].isRequire
  459. ) {
  460. return null;
  461. }
  462. const currentlyResolvingForParent = currentlyResolving.get(importer);
  463. if (currentlyResolvingForParent && currentlyResolvingForParent.has(importee)) {
  464. this.warn({
  465. code: 'THIS_RESOLVE_WITHOUT_OPTIONS',
  466. message:
  467. 'It appears a plugin has implemented a "resolveId" hook that uses "this.resolve" without forwarding the third "options" parameter of "resolveId". This is problematic as it can lead to wrong module resolutions especially for the node-resolve plugin and in certain cases cause early exit errors for the commonjs plugin.\nIn rare cases, this warning can appear if the same file is both imported and required from the same mixed ES/CommonJS module, in which case it can be ignored.',
  468. url: 'https://rollupjs.org/guide/en/#resolveid'
  469. });
  470. return null;
  471. }
  472. if (isWrappedId(importee, WRAPPED_SUFFIX)) {
  473. return unwrapId(importee, WRAPPED_SUFFIX);
  474. }
  475. if (
  476. importee.endsWith(ENTRY_SUFFIX) ||
  477. isWrappedId(importee, MODULE_SUFFIX) ||
  478. isWrappedId(importee, EXPORTS_SUFFIX) ||
  479. isWrappedId(importee, PROXY_SUFFIX) ||
  480. isWrappedId(importee, ES_IMPORT_SUFFIX) ||
  481. isWrappedId(importee, EXTERNAL_SUFFIX) ||
  482. importee.startsWith(HELPERS_ID) ||
  483. importee === DYNAMIC_MODULES_ID
  484. ) {
  485. return importee;
  486. }
  487. if (importer) {
  488. if (
  489. importer === DYNAMIC_MODULES_ID ||
  490. // Proxies are only importing resolved ids, no need to resolve again
  491. isWrappedId(importer, PROXY_SUFFIX) ||
  492. isWrappedId(importer, ES_IMPORT_SUFFIX) ||
  493. importer.endsWith(ENTRY_SUFFIX)
  494. ) {
  495. return importee;
  496. }
  497. if (isWrappedId(importer, EXTERNAL_SUFFIX)) {
  498. // We need to return null for unresolved imports so that the proper warning is shown
  499. if (
  500. !(await this.resolve(
  501. importee,
  502. importer,
  503. Object.assign({ skipSelf: true }, resolveOptions)
  504. ))
  505. ) {
  506. return null;
  507. }
  508. // For other external imports, we need to make sure they are handled as external
  509. return { id: importee, external: true };
  510. }
  511. }
  512. if (importee.startsWith('\0')) {
  513. return null;
  514. }
  515. // If this is an entry point or ESM import, we need to figure out if the importee is wrapped and
  516. // if that is the case, we need to add a proxy.
  517. const resolved =
  518. (await this.resolve(
  519. importee,
  520. importer,
  521. Object.assign({ skipSelf: true }, resolveOptions)
  522. )) || resolveExtensions(importee, importer, extensions);
  523. // Make sure that even if other plugins resolve again, we ignore our own proxies
  524. if (
  525. !resolved ||
  526. resolved.external ||
  527. resolved.id.endsWith(ENTRY_SUFFIX) ||
  528. isWrappedId(resolved.id, ES_IMPORT_SUFFIX) ||
  529. !isPossibleCjsId(resolved.id)
  530. ) {
  531. return resolved;
  532. }
  533. const moduleInfo = await this.load(resolved);
  534. const {
  535. meta: { commonjs: commonjsMeta }
  536. } = moduleInfo;
  537. if (commonjsMeta) {
  538. const { isCommonJS } = commonjsMeta;
  539. if (isCommonJS) {
  540. if (resolveOptions.isEntry) {
  541. moduleInfo.moduleSideEffects = true;
  542. // We must not precede entry proxies with a `\0` as that will mess up relative external resolution
  543. return resolved.id + ENTRY_SUFFIX;
  544. }
  545. if (isCommonJS === IS_WRAPPED_COMMONJS) {
  546. return { id: wrapId(resolved.id, ES_IMPORT_SUFFIX), meta: { commonjs: { resolved } } };
  547. }
  548. }
  549. }
  550. return resolved;
  551. }
  552. };
  553. }
  554. function getRequireResolver(extensions, detectCyclesAndConditional, currentlyResolving) {
  555. const knownCjsModuleTypes = Object.create(null);
  556. const requiredIds = Object.create(null);
  557. const unconditionallyRequiredIds = Object.create(null);
  558. const dependencies = Object.create(null);
  559. const getDependencies = (id) => dependencies[id] || (dependencies[id] = new Set());
  560. const isCyclic = (id) => {
  561. const dependenciesToCheck = new Set(getDependencies(id));
  562. for (const dependency of dependenciesToCheck) {
  563. if (dependency === id) {
  564. return true;
  565. }
  566. for (const childDependency of getDependencies(dependency)) {
  567. dependenciesToCheck.add(childDependency);
  568. }
  569. }
  570. return false;
  571. };
  572. // Once a module is listed here, its type (wrapped or not) is fixed and may
  573. // not change for the rest of the current build, to not break already
  574. // transformed modules.
  575. const fullyAnalyzedModules = Object.create(null);
  576. const getTypeForFullyAnalyzedModule = (id) => {
  577. const knownType = knownCjsModuleTypes[id];
  578. if (knownType !== true || !detectCyclesAndConditional || fullyAnalyzedModules[id]) {
  579. return knownType;
  580. }
  581. if (isCyclic(id)) {
  582. return (knownCjsModuleTypes[id] = IS_WRAPPED_COMMONJS);
  583. }
  584. return knownType;
  585. };
  586. const setInitialParentType = (id, initialCommonJSType) => {
  587. // Fully analyzed modules may never change type
  588. if (fullyAnalyzedModules[id]) {
  589. return;
  590. }
  591. knownCjsModuleTypes[id] = initialCommonJSType;
  592. if (
  593. detectCyclesAndConditional &&
  594. knownCjsModuleTypes[id] === true &&
  595. requiredIds[id] &&
  596. !unconditionallyRequiredIds[id]
  597. ) {
  598. knownCjsModuleTypes[id] = IS_WRAPPED_COMMONJS;
  599. }
  600. };
  601. const analyzeRequiredModule = async (parentId, resolved, isConditional, loadModule) => {
  602. const childId = resolved.id;
  603. requiredIds[childId] = true;
  604. if (!(isConditional || knownCjsModuleTypes[parentId] === IS_WRAPPED_COMMONJS)) {
  605. unconditionallyRequiredIds[childId] = true;
  606. }
  607. getDependencies(parentId).add(childId);
  608. if (!isCyclic(childId)) {
  609. // This makes sure the current transform handler waits for all direct
  610. // dependencies to be loaded and transformed and therefore for all
  611. // transitive CommonJS dependencies to be loaded as well so that all
  612. // cycles have been found and knownCjsModuleTypes is reliable.
  613. await loadModule(resolved);
  614. }
  615. };
  616. const getTypeForImportedModule = async (resolved, loadModule) => {
  617. if (resolved.id in knownCjsModuleTypes) {
  618. // This handles cyclic ES dependencies
  619. return knownCjsModuleTypes[resolved.id];
  620. }
  621. const {
  622. meta: { commonjs }
  623. } = await loadModule(resolved);
  624. return (commonjs && commonjs.isCommonJS) || false;
  625. };
  626. return {
  627. getWrappedIds: () =>
  628. Object.keys(knownCjsModuleTypes).filter(
  629. (id) => knownCjsModuleTypes[id] === IS_WRAPPED_COMMONJS
  630. ),
  631. isRequiredId: (id) => requiredIds[id],
  632. async shouldTransformCachedModule({
  633. id: parentId,
  634. resolvedSources,
  635. meta: { commonjs: parentMeta }
  636. }) {
  637. // We explicitly track ES modules to handle circular imports
  638. if (!(parentMeta && parentMeta.isCommonJS)) knownCjsModuleTypes[parentId] = false;
  639. if (isWrappedId(parentId, ES_IMPORT_SUFFIX)) return false;
  640. const parentRequires = parentMeta && parentMeta.requires;
  641. if (parentRequires) {
  642. setInitialParentType(parentId, parentMeta.initialCommonJSType);
  643. await Promise.all(
  644. parentRequires.map(({ resolved, isConditional }) =>
  645. analyzeRequiredModule(parentId, resolved, isConditional, this.load)
  646. )
  647. );
  648. if (getTypeForFullyAnalyzedModule(parentId) !== parentMeta.isCommonJS) {
  649. return true;
  650. }
  651. for (const {
  652. resolved: { id }
  653. } of parentRequires) {
  654. if (getTypeForFullyAnalyzedModule(id) !== parentMeta.isRequiredCommonJS[id]) {
  655. return true;
  656. }
  657. }
  658. // Now that we decided to go with the cached copy, neither the parent
  659. // module nor any of its children may change types anymore
  660. fullyAnalyzedModules[parentId] = true;
  661. for (const {
  662. resolved: { id }
  663. } of parentRequires) {
  664. fullyAnalyzedModules[id] = true;
  665. }
  666. }
  667. const parentRequireSet = new Set((parentRequires || []).map(({ resolved: { id } }) => id));
  668. return (
  669. await Promise.all(
  670. Object.keys(resolvedSources)
  671. .map((source) => resolvedSources[source])
  672. .filter(({ id, external }) => !(external || parentRequireSet.has(id)))
  673. .map(async (resolved) => {
  674. if (isWrappedId(resolved.id, ES_IMPORT_SUFFIX)) {
  675. return (
  676. (await getTypeForImportedModule(
  677. (
  678. await this.load({ id: resolved.id })
  679. ).meta.commonjs.resolved,
  680. this.load
  681. )) !== IS_WRAPPED_COMMONJS
  682. );
  683. }
  684. return (await getTypeForImportedModule(resolved, this.load)) === IS_WRAPPED_COMMONJS;
  685. })
  686. )
  687. ).some((shouldTransform) => shouldTransform);
  688. },
  689. /* eslint-disable no-param-reassign */
  690. resolveRequireSourcesAndUpdateMeta:
  691. (rollupContext) => async (parentId, isParentCommonJS, parentMeta, sources) => {
  692. parentMeta.initialCommonJSType = isParentCommonJS;
  693. parentMeta.requires = [];
  694. parentMeta.isRequiredCommonJS = Object.create(null);
  695. setInitialParentType(parentId, isParentCommonJS);
  696. const currentlyResolvingForParent = currentlyResolving.get(parentId) || new Set();
  697. currentlyResolving.set(parentId, currentlyResolvingForParent);
  698. const requireTargets = await Promise.all(
  699. sources.map(async ({ source, isConditional }) => {
  700. // Never analyze or proxy internal modules
  701. if (source.startsWith('\0')) {
  702. return { id: source, allowProxy: false };
  703. }
  704. currentlyResolvingForParent.add(source);
  705. const resolved =
  706. (await rollupContext.resolve(source, parentId, {
  707. custom: { 'node-resolve': { isRequire: true } }
  708. })) || resolveExtensions(source, parentId, extensions);
  709. currentlyResolvingForParent.delete(source);
  710. if (!resolved) {
  711. return { id: wrapId(source, EXTERNAL_SUFFIX), allowProxy: false };
  712. }
  713. const childId = resolved.id;
  714. if (resolved.external) {
  715. return { id: wrapId(childId, EXTERNAL_SUFFIX), allowProxy: false };
  716. }
  717. parentMeta.requires.push({ resolved, isConditional });
  718. await analyzeRequiredModule(parentId, resolved, isConditional, rollupContext.load);
  719. return { id: childId, allowProxy: true };
  720. })
  721. );
  722. parentMeta.isCommonJS = getTypeForFullyAnalyzedModule(parentId);
  723. fullyAnalyzedModules[parentId] = true;
  724. return requireTargets.map(({ id: dependencyId, allowProxy }, index) => {
  725. // eslint-disable-next-line no-multi-assign
  726. const isCommonJS = (parentMeta.isRequiredCommonJS[dependencyId] =
  727. getTypeForFullyAnalyzedModule(dependencyId));
  728. fullyAnalyzedModules[dependencyId] = true;
  729. return {
  730. source: sources[index].source,
  731. id: allowProxy
  732. ? isCommonJS === IS_WRAPPED_COMMONJS
  733. ? wrapId(dependencyId, WRAPPED_SUFFIX)
  734. : wrapId(dependencyId, PROXY_SUFFIX)
  735. : dependencyId,
  736. isCommonJS
  737. };
  738. });
  739. },
  740. isCurrentlyResolving(source, parentId) {
  741. const currentlyResolvingForParent = currentlyResolving.get(parentId);
  742. return currentlyResolvingForParent && currentlyResolvingForParent.has(source);
  743. }
  744. };
  745. }
  746. function validateVersion(actualVersion, peerDependencyVersion, name) {
  747. const versionRegexp = /\^(\d+\.\d+\.\d+)/g;
  748. let minMajor = Infinity;
  749. let minMinor = Infinity;
  750. let minPatch = Infinity;
  751. let foundVersion;
  752. // eslint-disable-next-line no-cond-assign
  753. while ((foundVersion = versionRegexp.exec(peerDependencyVersion))) {
  754. const [foundMajor, foundMinor, foundPatch] = foundVersion[1].split('.').map(Number);
  755. if (foundMajor < minMajor) {
  756. minMajor = foundMajor;
  757. minMinor = foundMinor;
  758. minPatch = foundPatch;
  759. }
  760. }
  761. if (!actualVersion) {
  762. throw new Error(
  763. `Insufficient ${name} version: "@rollup/plugin-commonjs" requires at least ${name}@${minMajor}.${minMinor}.${minPatch}.`
  764. );
  765. }
  766. const [major, minor, patch] = actualVersion.split('.').map(Number);
  767. if (
  768. major < minMajor ||
  769. (major === minMajor && (minor < minMinor || (minor === minMinor && patch < minPatch)))
  770. ) {
  771. throw new Error(
  772. `Insufficient ${name} version: "@rollup/plugin-commonjs" requires at least ${name}@${minMajor}.${minMinor}.${minPatch} but found ${name}@${actualVersion}.`
  773. );
  774. }
  775. }
  776. const operators = {
  777. '==': (x) => equals(x.left, x.right, false),
  778. '!=': (x) => not(operators['=='](x)),
  779. '===': (x) => equals(x.left, x.right, true),
  780. '!==': (x) => not(operators['==='](x)),
  781. '!': (x) => isFalsy(x.argument),
  782. '&&': (x) => isTruthy(x.left) && isTruthy(x.right),
  783. '||': (x) => isTruthy(x.left) || isTruthy(x.right)
  784. };
  785. function not(value) {
  786. return value === null ? value : !value;
  787. }
  788. function equals(a, b, strict) {
  789. if (a.type !== b.type) return null;
  790. // eslint-disable-next-line eqeqeq
  791. if (a.type === 'Literal') return strict ? a.value === b.value : a.value == b.value;
  792. return null;
  793. }
  794. function isTruthy(node) {
  795. if (!node) return false;
  796. if (node.type === 'Literal') return !!node.value;
  797. if (node.type === 'ParenthesizedExpression') return isTruthy(node.expression);
  798. if (node.operator in operators) return operators[node.operator](node);
  799. return null;
  800. }
  801. function isFalsy(node) {
  802. return not(isTruthy(node));
  803. }
  804. function getKeypath(node) {
  805. const parts = [];
  806. while (node.type === 'MemberExpression') {
  807. if (node.computed) return null;
  808. parts.unshift(node.property.name);
  809. // eslint-disable-next-line no-param-reassign
  810. node = node.object;
  811. }
  812. if (node.type !== 'Identifier') return null;
  813. const { name } = node;
  814. parts.unshift(name);
  815. return { name, keypath: parts.join('.') };
  816. }
  817. const KEY_COMPILED_ESM = '__esModule';
  818. function isDefineCompiledEsm(node) {
  819. const definedProperty =
  820. getDefinePropertyCallName(node, 'exports') || getDefinePropertyCallName(node, 'module.exports');
  821. if (definedProperty && definedProperty.key === KEY_COMPILED_ESM) {
  822. return isTruthy(definedProperty.value);
  823. }
  824. return false;
  825. }
  826. function getDefinePropertyCallName(node, targetName) {
  827. const {
  828. callee: { object, property }
  829. } = node;
  830. if (!object || object.type !== 'Identifier' || object.name !== 'Object') return;
  831. if (!property || property.type !== 'Identifier' || property.name !== 'defineProperty') return;
  832. if (node.arguments.length !== 3) return;
  833. const targetNames = targetName.split('.');
  834. const [target, key, value] = node.arguments;
  835. if (targetNames.length === 1) {
  836. if (target.type !== 'Identifier' || target.name !== targetNames[0]) {
  837. return;
  838. }
  839. }
  840. if (targetNames.length === 2) {
  841. if (
  842. target.type !== 'MemberExpression' ||
  843. target.object.name !== targetNames[0] ||
  844. target.property.name !== targetNames[1]
  845. ) {
  846. return;
  847. }
  848. }
  849. if (value.type !== 'ObjectExpression' || !value.properties) return;
  850. const valueProperty = value.properties.find((p) => p.key && p.key.name === 'value');
  851. if (!valueProperty || !valueProperty.value) return;
  852. // eslint-disable-next-line consistent-return
  853. return { key: key.value, value: valueProperty.value };
  854. }
  855. function isShorthandProperty(parent) {
  856. return parent && parent.type === 'Property' && parent.shorthand;
  857. }
  858. function hasDefineEsmProperty(node) {
  859. return node.properties.some((property) => {
  860. if (
  861. property.type === 'Property' &&
  862. property.key.type === 'Identifier' &&
  863. property.key.name === '__esModule' &&
  864. isTruthy(property.value)
  865. ) {
  866. return true;
  867. }
  868. return false;
  869. });
  870. }
  871. function wrapCode(magicString, uses, moduleName, exportsName, indentExclusionRanges) {
  872. const args = [];
  873. const passedArgs = [];
  874. if (uses.module) {
  875. args.push('module');
  876. passedArgs.push(moduleName);
  877. }
  878. if (uses.exports) {
  879. args.push('exports');
  880. passedArgs.push(exportsName);
  881. }
  882. magicString
  883. .trim()
  884. .indent('\t', { exclude: indentExclusionRanges })
  885. .prepend(`(function (${args.join(', ')}) {\n`)
  886. .append(`\n} (${passedArgs.join(', ')}));`);
  887. }
  888. function rewriteExportsAndGetExportsBlock(
  889. magicString,
  890. moduleName,
  891. exportsName,
  892. wrapped,
  893. moduleExportsAssignments,
  894. firstTopLevelModuleExportsAssignment,
  895. exportsAssignmentsByName,
  896. topLevelAssignments,
  897. defineCompiledEsmExpressions,
  898. deconflictedExportNames,
  899. code,
  900. HELPERS_NAME,
  901. exportMode,
  902. detectWrappedDefault,
  903. defaultIsModuleExports,
  904. usesRequireWrapper,
  905. requireName
  906. ) {
  907. const exports = [];
  908. const exportDeclarations = [];
  909. if (usesRequireWrapper) {
  910. getExportsWhenUsingRequireWrapper(
  911. magicString,
  912. wrapped,
  913. exportMode,
  914. exports,
  915. moduleExportsAssignments,
  916. exportsAssignmentsByName,
  917. moduleName,
  918. exportsName,
  919. requireName,
  920. defineCompiledEsmExpressions
  921. );
  922. } else if (exportMode === 'replace') {
  923. getExportsForReplacedModuleExports(
  924. magicString,
  925. exports,
  926. exportDeclarations,
  927. moduleExportsAssignments,
  928. firstTopLevelModuleExportsAssignment,
  929. exportsName
  930. );
  931. } else {
  932. exports.push(`${exportsName} as __moduleExports`);
  933. if (wrapped) {
  934. getExportsWhenWrapping(
  935. exportDeclarations,
  936. exportsName,
  937. detectWrappedDefault,
  938. HELPERS_NAME,
  939. defaultIsModuleExports
  940. );
  941. } else {
  942. getExports(
  943. magicString,
  944. exports,
  945. exportDeclarations,
  946. moduleExportsAssignments,
  947. exportsAssignmentsByName,
  948. deconflictedExportNames,
  949. topLevelAssignments,
  950. moduleName,
  951. exportsName,
  952. defineCompiledEsmExpressions,
  953. HELPERS_NAME,
  954. defaultIsModuleExports
  955. );
  956. }
  957. }
  958. if (exports.length) {
  959. exportDeclarations.push(`export { ${exports.join(', ')} };`);
  960. }
  961. return `\n\n${exportDeclarations.join('\n')}`;
  962. }
  963. function getExportsWhenUsingRequireWrapper(
  964. magicString,
  965. wrapped,
  966. exportMode,
  967. exports,
  968. moduleExportsAssignments,
  969. exportsAssignmentsByName,
  970. moduleName,
  971. exportsName,
  972. requireName,
  973. defineCompiledEsmExpressions
  974. ) {
  975. if (!wrapped) {
  976. if (exportMode === 'replace') {
  977. for (const { left } of moduleExportsAssignments) {
  978. magicString.overwrite(left.start, left.end, exportsName);
  979. }
  980. } else {
  981. // Collect and rewrite module.exports assignments
  982. for (const { left } of moduleExportsAssignments) {
  983. magicString.overwrite(left.start, left.end, `${moduleName}.exports`);
  984. }
  985. // Collect and rewrite named exports
  986. for (const [exportName, { nodes }] of exportsAssignmentsByName) {
  987. for (const node of nodes) {
  988. magicString.overwrite(node.start, node.left.end, `${exportsName}.${exportName}`);
  989. }
  990. }
  991. // Collect and rewrite exports.__esModule assignments
  992. for (const expression of defineCompiledEsmExpressions) {
  993. const moduleExportsExpression =
  994. expression.type === 'CallExpression' ? expression.arguments[0] : expression.left.object;
  995. magicString.overwrite(
  996. moduleExportsExpression.start,
  997. moduleExportsExpression.end,
  998. exportsName
  999. );
  1000. }
  1001. }
  1002. }
  1003. exports.push(`${requireName} as __require`);
  1004. }
  1005. function getExportsForReplacedModuleExports(
  1006. magicString,
  1007. exports,
  1008. exportDeclarations,
  1009. moduleExportsAssignments,
  1010. firstTopLevelModuleExportsAssignment,
  1011. exportsName
  1012. ) {
  1013. for (const { left } of moduleExportsAssignments) {
  1014. magicString.overwrite(left.start, left.end, exportsName);
  1015. }
  1016. magicString.prependRight(firstTopLevelModuleExportsAssignment.left.start, 'var ');
  1017. exports.push(`${exportsName} as __moduleExports`);
  1018. exportDeclarations.push(`export default ${exportsName};`);
  1019. }
  1020. function getExportsWhenWrapping(
  1021. exportDeclarations,
  1022. exportsName,
  1023. detectWrappedDefault,
  1024. HELPERS_NAME,
  1025. defaultIsModuleExports
  1026. ) {
  1027. exportDeclarations.push(
  1028. `export default ${
  1029. detectWrappedDefault && defaultIsModuleExports === 'auto'
  1030. ? `/*@__PURE__*/${HELPERS_NAME}.getDefaultExportFromCjs(${exportsName})`
  1031. : defaultIsModuleExports === false
  1032. ? `${exportsName}.default`
  1033. : exportsName
  1034. };`
  1035. );
  1036. }
  1037. function getExports(
  1038. magicString,
  1039. exports,
  1040. exportDeclarations,
  1041. moduleExportsAssignments,
  1042. exportsAssignmentsByName,
  1043. deconflictedExportNames,
  1044. topLevelAssignments,
  1045. moduleName,
  1046. exportsName,
  1047. defineCompiledEsmExpressions,
  1048. HELPERS_NAME,
  1049. defaultIsModuleExports
  1050. ) {
  1051. let deconflictedDefaultExportName;
  1052. // Collect and rewrite module.exports assignments
  1053. for (const { left } of moduleExportsAssignments) {
  1054. magicString.overwrite(left.start, left.end, `${moduleName}.exports`);
  1055. }
  1056. // Collect and rewrite named exports
  1057. for (const [exportName, { nodes }] of exportsAssignmentsByName) {
  1058. const deconflicted = deconflictedExportNames[exportName];
  1059. let needsDeclaration = true;
  1060. for (const node of nodes) {
  1061. let replacement = `${deconflicted} = ${exportsName}.${exportName}`;
  1062. if (needsDeclaration && topLevelAssignments.has(node)) {
  1063. replacement = `var ${replacement}`;
  1064. needsDeclaration = false;
  1065. }
  1066. magicString.overwrite(node.start, node.left.end, replacement);
  1067. }
  1068. if (needsDeclaration) {
  1069. magicString.prepend(`var ${deconflicted};\n`);
  1070. }
  1071. if (exportName === 'default') {
  1072. deconflictedDefaultExportName = deconflicted;
  1073. } else {
  1074. exports.push(exportName === deconflicted ? exportName : `${deconflicted} as ${exportName}`);
  1075. }
  1076. }
  1077. // Collect and rewrite exports.__esModule assignments
  1078. let isRestorableCompiledEsm = false;
  1079. for (const expression of defineCompiledEsmExpressions) {
  1080. isRestorableCompiledEsm = true;
  1081. const moduleExportsExpression =
  1082. expression.type === 'CallExpression' ? expression.arguments[0] : expression.left.object;
  1083. magicString.overwrite(moduleExportsExpression.start, moduleExportsExpression.end, exportsName);
  1084. }
  1085. if (!isRestorableCompiledEsm || defaultIsModuleExports === true) {
  1086. exports.push(`${exportsName} as default`);
  1087. } else if (moduleExportsAssignments.length === 0 || defaultIsModuleExports === false) {
  1088. exports.push(`${deconflictedDefaultExportName || exportsName} as default`);
  1089. } else {
  1090. exportDeclarations.push(
  1091. `export default /*@__PURE__*/${HELPERS_NAME}.getDefaultExportFromCjs(${exportsName});`
  1092. );
  1093. }
  1094. }
  1095. function isRequireExpression(node, scope) {
  1096. if (!node) return false;
  1097. if (node.type !== 'CallExpression') return false;
  1098. // Weird case of `require()` or `module.require()` without arguments
  1099. if (node.arguments.length === 0) return false;
  1100. return isRequire(node.callee, scope);
  1101. }
  1102. function isRequire(node, scope) {
  1103. return (
  1104. (node.type === 'Identifier' && node.name === 'require' && !scope.contains('require')) ||
  1105. (node.type === 'MemberExpression' && isModuleRequire(node, scope))
  1106. );
  1107. }
  1108. function isModuleRequire({ object, property }, scope) {
  1109. return (
  1110. object.type === 'Identifier' &&
  1111. object.name === 'module' &&
  1112. property.type === 'Identifier' &&
  1113. property.name === 'require' &&
  1114. !scope.contains('module')
  1115. );
  1116. }
  1117. function hasDynamicArguments(node) {
  1118. return (
  1119. node.arguments.length > 1 ||
  1120. (node.arguments[0].type !== 'Literal' &&
  1121. (node.arguments[0].type !== 'TemplateLiteral' || node.arguments[0].expressions.length > 0))
  1122. );
  1123. }
  1124. const reservedMethod = { resolve: true, cache: true, main: true };
  1125. function isNodeRequirePropertyAccess(parent) {
  1126. return parent && parent.property && reservedMethod[parent.property.name];
  1127. }
  1128. function getRequireStringArg(node) {
  1129. return node.arguments[0].type === 'Literal'
  1130. ? node.arguments[0].value
  1131. : node.arguments[0].quasis[0].value.cooked;
  1132. }
  1133. function getRequireHandlers() {
  1134. const requireExpressions = [];
  1135. function addRequireExpression(
  1136. sourceId,
  1137. node,
  1138. scope,
  1139. usesReturnValue,
  1140. isInsideTryBlock,
  1141. isInsideConditional,
  1142. toBeRemoved
  1143. ) {
  1144. requireExpressions.push({
  1145. sourceId,
  1146. node,
  1147. scope,
  1148. usesReturnValue,
  1149. isInsideTryBlock,
  1150. isInsideConditional,
  1151. toBeRemoved
  1152. });
  1153. }
  1154. async function rewriteRequireExpressionsAndGetImportBlock(
  1155. magicString,
  1156. topLevelDeclarations,
  1157. reassignedNames,
  1158. helpersName,
  1159. dynamicRequireName,
  1160. moduleName,
  1161. exportsName,
  1162. id,
  1163. exportMode,
  1164. resolveRequireSourcesAndUpdateMeta,
  1165. needsRequireWrapper,
  1166. isEsModule,
  1167. isDynamicRequireModulesEnabled,
  1168. getIgnoreTryCatchRequireStatementMode,
  1169. commonjsMeta
  1170. ) {
  1171. const imports = [];
  1172. imports.push(`import * as ${helpersName} from "${HELPERS_ID}";`);
  1173. if (dynamicRequireName) {
  1174. imports.push(
  1175. `import { ${
  1176. isDynamicRequireModulesEnabled ? CREATE_COMMONJS_REQUIRE_EXPORT : COMMONJS_REQUIRE_EXPORT
  1177. } as ${dynamicRequireName} } from "${DYNAMIC_MODULES_ID}";`
  1178. );
  1179. }
  1180. if (exportMode === 'module') {
  1181. imports.push(
  1182. `import { __module as ${moduleName}, exports as ${exportsName} } from ${JSON.stringify(
  1183. wrapId(id, MODULE_SUFFIX)
  1184. )}`
  1185. );
  1186. } else if (exportMode === 'exports') {
  1187. imports.push(
  1188. `import { __exports as ${exportsName} } from ${JSON.stringify(wrapId(id, EXPORTS_SUFFIX))}`
  1189. );
  1190. }
  1191. const requiresBySource = collectSources(requireExpressions);
  1192. const requireTargets = await resolveRequireSourcesAndUpdateMeta(
  1193. id,
  1194. needsRequireWrapper ? IS_WRAPPED_COMMONJS : !isEsModule,
  1195. commonjsMeta,
  1196. Object.keys(requiresBySource).map((source) => {
  1197. return {
  1198. source,
  1199. isConditional: requiresBySource[source].every((require) => require.isInsideConditional)
  1200. };
  1201. })
  1202. );
  1203. processRequireExpressions(
  1204. imports,
  1205. requireTargets,
  1206. requiresBySource,
  1207. getIgnoreTryCatchRequireStatementMode,
  1208. magicString
  1209. );
  1210. return imports.length ? `${imports.join('\n')}\n\n` : '';
  1211. }
  1212. return {
  1213. addRequireExpression,
  1214. rewriteRequireExpressionsAndGetImportBlock
  1215. };
  1216. }
  1217. function collectSources(requireExpressions) {
  1218. const requiresBySource = Object.create(null);
  1219. for (const requireExpression of requireExpressions) {
  1220. const { sourceId } = requireExpression;
  1221. if (!requiresBySource[sourceId]) {
  1222. requiresBySource[sourceId] = [];
  1223. }
  1224. const requires = requiresBySource[sourceId];
  1225. requires.push(requireExpression);
  1226. }
  1227. return requiresBySource;
  1228. }
  1229. function processRequireExpressions(
  1230. imports,
  1231. requireTargets,
  1232. requiresBySource,
  1233. getIgnoreTryCatchRequireStatementMode,
  1234. magicString
  1235. ) {
  1236. const generateRequireName = getGenerateRequireName();
  1237. for (const { source, id: resolvedId, isCommonJS } of requireTargets) {
  1238. const requires = requiresBySource[source];
  1239. const name = generateRequireName(requires);
  1240. let usesRequired = false;
  1241. let needsImport = false;
  1242. for (const { node, usesReturnValue, toBeRemoved, isInsideTryBlock } of requires) {
  1243. const { canConvertRequire, shouldRemoveRequire } =
  1244. isInsideTryBlock && isWrappedId(resolvedId, EXTERNAL_SUFFIX)
  1245. ? getIgnoreTryCatchRequireStatementMode(source)
  1246. : { canConvertRequire: true, shouldRemoveRequire: false };
  1247. if (shouldRemoveRequire) {
  1248. if (usesReturnValue) {
  1249. magicString.overwrite(node.start, node.end, 'undefined');
  1250. } else {
  1251. magicString.remove(toBeRemoved.start, toBeRemoved.end);
  1252. }
  1253. } else if (canConvertRequire) {
  1254. needsImport = true;
  1255. if (isCommonJS === IS_WRAPPED_COMMONJS) {
  1256. magicString.overwrite(node.start, node.end, `${name}()`);
  1257. } else if (usesReturnValue) {
  1258. usesRequired = true;
  1259. magicString.overwrite(node.start, node.end, name);
  1260. } else {
  1261. magicString.remove(toBeRemoved.start, toBeRemoved.end);
  1262. }
  1263. }
  1264. }
  1265. if (needsImport) {
  1266. if (isCommonJS === IS_WRAPPED_COMMONJS) {
  1267. imports.push(`import { __require as ${name} } from ${JSON.stringify(resolvedId)};`);
  1268. } else {
  1269. imports.push(`import ${usesRequired ? `${name} from ` : ''}${JSON.stringify(resolvedId)};`);
  1270. }
  1271. }
  1272. }
  1273. }
  1274. function getGenerateRequireName() {
  1275. let uid = 0;
  1276. return (requires) => {
  1277. let name;
  1278. const hasNameConflict = ({ scope }) => scope.contains(name);
  1279. do {
  1280. name = `require$$${uid}`;
  1281. uid += 1;
  1282. } while (requires.some(hasNameConflict));
  1283. return name;
  1284. };
  1285. }
  1286. /* eslint-disable no-param-reassign, no-shadow, no-underscore-dangle, no-continue */
  1287. const exportsPattern = /^(?:module\.)?exports(?:\.([a-zA-Z_$][a-zA-Z_$0-9]*))?$/;
  1288. const functionType = /^(?:FunctionDeclaration|FunctionExpression|ArrowFunctionExpression)$/;
  1289. async function transformCommonjs(
  1290. parse,
  1291. code,
  1292. id,
  1293. isEsModule,
  1294. ignoreGlobal,
  1295. ignoreRequire,
  1296. ignoreDynamicRequires,
  1297. getIgnoreTryCatchRequireStatementMode,
  1298. sourceMap,
  1299. isDynamicRequireModulesEnabled,
  1300. dynamicRequireModules,
  1301. commonDir,
  1302. astCache,
  1303. defaultIsModuleExports,
  1304. needsRequireWrapper,
  1305. resolveRequireSourcesAndUpdateMeta,
  1306. isRequired,
  1307. checkDynamicRequire,
  1308. commonjsMeta
  1309. ) {
  1310. const ast = astCache || tryParse(parse, code, id);
  1311. const magicString = new MagicString(code);
  1312. const uses = {
  1313. module: false,
  1314. exports: false,
  1315. global: false,
  1316. require: false
  1317. };
  1318. const virtualDynamicRequirePath =
  1319. isDynamicRequireModulesEnabled && getVirtualPathForDynamicRequirePath(path.dirname(id), commonDir);
  1320. let scope = pluginutils.attachScopes(ast, 'scope');
  1321. let lexicalDepth = 0;
  1322. let programDepth = 0;
  1323. let currentTryBlockEnd = null;
  1324. let shouldWrap = false;
  1325. let reexports = false;
  1326. const globals = new Set();
  1327. // A conditionalNode is a node for which execution is not guaranteed. If such a node is a require
  1328. // or contains nested requires, those should be handled as function calls unless there is an
  1329. // unconditional require elsewhere.
  1330. let currentConditionalNodeEnd = null;
  1331. const conditionalNodes = new Set();
  1332. const { addRequireExpression, rewriteRequireExpressionsAndGetImportBlock } = getRequireHandlers();
  1333. // See which names are assigned to. This is necessary to prevent
  1334. // illegally replacing `var foo = require('foo')` with `import foo from 'foo'`,
  1335. // where `foo` is later reassigned. (This happens in the wild. CommonJS, sigh)
  1336. const reassignedNames = new Set();
  1337. const topLevelDeclarations = [];
  1338. const skippedNodes = new Set();
  1339. const moduleAccessScopes = new Set([scope]);
  1340. const exportsAccessScopes = new Set([scope]);
  1341. const moduleExportsAssignments = [];
  1342. let firstTopLevelModuleExportsAssignment = null;
  1343. const exportsAssignmentsByName = new Map();
  1344. const topLevelAssignments = new Set();
  1345. const topLevelDefineCompiledEsmExpressions = [];
  1346. const replacedGlobal = [];
  1347. const replacedDynamicRequires = [];
  1348. const importedVariables = new Set();
  1349. const indentExclusionRanges = [];
  1350. estreeWalker.walk(ast, {
  1351. enter(node, parent) {
  1352. if (skippedNodes.has(node)) {
  1353. this.skip();
  1354. return;
  1355. }
  1356. if (currentTryBlockEnd !== null && node.start > currentTryBlockEnd) {
  1357. currentTryBlockEnd = null;
  1358. }
  1359. if (currentConditionalNodeEnd !== null && node.start > currentConditionalNodeEnd) {
  1360. currentConditionalNodeEnd = null;
  1361. }
  1362. if (currentConditionalNodeEnd === null && conditionalNodes.has(node)) {
  1363. currentConditionalNodeEnd = node.end;
  1364. }
  1365. programDepth += 1;
  1366. if (node.scope) ({ scope } = node);
  1367. if (functionType.test(node.type)) lexicalDepth += 1;
  1368. if (sourceMap) {
  1369. magicString.addSourcemapLocation(node.start);
  1370. magicString.addSourcemapLocation(node.end);
  1371. }
  1372. // eslint-disable-next-line default-case
  1373. switch (node.type) {
  1374. case 'AssignmentExpression':
  1375. if (node.left.type === 'MemberExpression') {
  1376. const flattened = getKeypath(node.left);
  1377. if (!flattened || scope.contains(flattened.name)) return;
  1378. const exportsPatternMatch = exportsPattern.exec(flattened.keypath);
  1379. if (!exportsPatternMatch || flattened.keypath === 'exports') return;
  1380. const [, exportName] = exportsPatternMatch;
  1381. uses[flattened.name] = true;
  1382. // we're dealing with `module.exports = ...` or `[module.]exports.foo = ...` –
  1383. if (flattened.keypath === 'module.exports') {
  1384. moduleExportsAssignments.push(node);
  1385. if (programDepth > 3) {
  1386. moduleAccessScopes.add(scope);
  1387. } else if (!firstTopLevelModuleExportsAssignment) {
  1388. firstTopLevelModuleExportsAssignment = node;
  1389. }
  1390. if (defaultIsModuleExports === false) {
  1391. shouldWrap = true;
  1392. } else if (defaultIsModuleExports === 'auto') {
  1393. if (node.right.type === 'ObjectExpression') {
  1394. if (hasDefineEsmProperty(node.right)) {
  1395. shouldWrap = true;
  1396. }
  1397. } else if (isRequireExpression(node.right, scope)) {
  1398. shouldWrap = true;
  1399. reexports = true;
  1400. }
  1401. }
  1402. } else if (exportName === KEY_COMPILED_ESM) {
  1403. if (programDepth > 3) {
  1404. shouldWrap = true;
  1405. } else {
  1406. topLevelDefineCompiledEsmExpressions.push(node);
  1407. }
  1408. } else {
  1409. const exportsAssignments = exportsAssignmentsByName.get(exportName) || {
  1410. nodes: [],
  1411. scopes: new Set()
  1412. };
  1413. exportsAssignments.nodes.push(node);
  1414. exportsAssignments.scopes.add(scope);
  1415. exportsAccessScopes.add(scope);
  1416. exportsAssignmentsByName.set(exportName, exportsAssignments);
  1417. if (programDepth <= 3) {
  1418. topLevelAssignments.add(node);
  1419. }
  1420. }
  1421. skippedNodes.add(node.left);
  1422. } else {
  1423. for (const name of pluginutils.extractAssignedNames(node.left)) {
  1424. reassignedNames.add(name);
  1425. }
  1426. }
  1427. return;
  1428. case 'CallExpression': {
  1429. if (isDefineCompiledEsm(node)) {
  1430. if (programDepth === 3 && parent.type === 'ExpressionStatement') {
  1431. // skip special handling for [module.]exports until we know we render this
  1432. skippedNodes.add(node.arguments[0]);
  1433. topLevelDefineCompiledEsmExpressions.push(node);
  1434. } else {
  1435. shouldWrap = true;
  1436. }
  1437. return;
  1438. }
  1439. // Transform require.resolve
  1440. if (
  1441. isDynamicRequireModulesEnabled &&
  1442. node.callee.object &&
  1443. isRequire(node.callee.object, scope) &&
  1444. node.callee.property.name === 'resolve'
  1445. ) {
  1446. checkDynamicRequire(node.start);
  1447. uses.require = true;
  1448. const requireNode = node.callee.object;
  1449. replacedDynamicRequires.push(requireNode);
  1450. return;
  1451. }
  1452. if (!isRequireExpression(node, scope)) {
  1453. const keypath = getKeypath(node.callee);
  1454. if (keypath && importedVariables.has(keypath.name)) {
  1455. // Heuristic to deoptimize requires after a required function has been called
  1456. currentConditionalNodeEnd = Infinity;
  1457. }
  1458. return;
  1459. }
  1460. skippedNodes.add(node.callee);
  1461. uses.require = true;
  1462. if (hasDynamicArguments(node)) {
  1463. if (isDynamicRequireModulesEnabled) {
  1464. checkDynamicRequire(node.start);
  1465. }
  1466. if (!ignoreDynamicRequires) {
  1467. replacedDynamicRequires.push(node.callee);
  1468. }
  1469. return;
  1470. }
  1471. const requireStringArg = getRequireStringArg(node);
  1472. if (!ignoreRequire(requireStringArg)) {
  1473. const usesReturnValue = parent.type !== 'ExpressionStatement';
  1474. const toBeRemoved =
  1475. parent.type === 'ExpressionStatement' &&
  1476. (!currentConditionalNodeEnd ||
  1477. // We should completely remove requires directly in a try-catch
  1478. // so that Rollup can remove up the try-catch
  1479. (currentTryBlockEnd !== null && currentTryBlockEnd < currentConditionalNodeEnd))
  1480. ? parent
  1481. : node;
  1482. addRequireExpression(
  1483. requireStringArg,
  1484. node,
  1485. scope,
  1486. usesReturnValue,
  1487. currentTryBlockEnd !== null,
  1488. currentConditionalNodeEnd !== null,
  1489. toBeRemoved
  1490. );
  1491. if (parent.type === 'VariableDeclarator' && parent.id.type === 'Identifier') {
  1492. for (const name of pluginutils.extractAssignedNames(parent.id)) {
  1493. importedVariables.add(name);
  1494. }
  1495. }
  1496. }
  1497. return;
  1498. }
  1499. case 'ConditionalExpression':
  1500. case 'IfStatement':
  1501. // skip dead branches
  1502. if (isFalsy(node.test)) {
  1503. skippedNodes.add(node.consequent);
  1504. } else if (isTruthy(node.test)) {
  1505. if (node.alternate) {
  1506. skippedNodes.add(node.alternate);
  1507. }
  1508. } else {
  1509. conditionalNodes.add(node.consequent);
  1510. if (node.alternate) {
  1511. conditionalNodes.add(node.alternate);
  1512. }
  1513. }
  1514. return;
  1515. case 'ArrowFunctionExpression':
  1516. case 'FunctionDeclaration':
  1517. case 'FunctionExpression':
  1518. // requires in functions should be conditional unless it is an IIFE
  1519. if (
  1520. currentConditionalNodeEnd === null &&
  1521. !(parent.type === 'CallExpression' && parent.callee === node)
  1522. ) {
  1523. currentConditionalNodeEnd = node.end;
  1524. }
  1525. return;
  1526. case 'Identifier': {
  1527. const { name } = node;
  1528. if (!isReference(node, parent) || scope.contains(name)) return;
  1529. switch (name) {
  1530. case 'require':
  1531. uses.require = true;
  1532. if (isNodeRequirePropertyAccess(parent)) {
  1533. return;
  1534. }
  1535. if (!ignoreDynamicRequires) {
  1536. if (isShorthandProperty(parent)) {
  1537. magicString.prependRight(node.start, 'require: ');
  1538. }
  1539. replacedDynamicRequires.push(node);
  1540. }
  1541. return;
  1542. case 'module':
  1543. case 'exports':
  1544. shouldWrap = true;
  1545. uses[name] = true;
  1546. return;
  1547. case 'global':
  1548. uses.global = true;
  1549. if (!ignoreGlobal) {
  1550. replacedGlobal.push(node);
  1551. }
  1552. return;
  1553. case 'define':
  1554. magicString.overwrite(node.start, node.end, 'undefined', {
  1555. storeName: true
  1556. });
  1557. return;
  1558. default:
  1559. globals.add(name);
  1560. return;
  1561. }
  1562. }
  1563. case 'LogicalExpression':
  1564. // skip dead branches
  1565. if (node.operator === '&&') {
  1566. if (isFalsy(node.left)) {
  1567. skippedNodes.add(node.right);
  1568. } else if (!isTruthy(node.left)) {
  1569. conditionalNodes.add(node.right);
  1570. }
  1571. } else if (node.operator === '||') {
  1572. if (isTruthy(node.left)) {
  1573. skippedNodes.add(node.right);
  1574. } else if (!isFalsy(node.left)) {
  1575. conditionalNodes.add(node.right);
  1576. }
  1577. }
  1578. return;
  1579. case 'MemberExpression':
  1580. if (!isDynamicRequireModulesEnabled && isModuleRequire(node, scope)) {
  1581. uses.require = true;
  1582. replacedDynamicRequires.push(node);
  1583. skippedNodes.add(node.object);
  1584. skippedNodes.add(node.property);
  1585. }
  1586. return;
  1587. case 'ReturnStatement':
  1588. // if top-level return, we need to wrap it
  1589. if (lexicalDepth === 0) {
  1590. shouldWrap = true;
  1591. }
  1592. return;
  1593. case 'ThisExpression':
  1594. // rewrite top-level `this` as `commonjsHelpers.commonjsGlobal`
  1595. if (lexicalDepth === 0) {
  1596. uses.global = true;
  1597. if (!ignoreGlobal) {
  1598. replacedGlobal.push(node);
  1599. }
  1600. }
  1601. return;
  1602. case 'TryStatement':
  1603. if (currentTryBlockEnd === null) {
  1604. currentTryBlockEnd = node.block.end;
  1605. }
  1606. if (currentConditionalNodeEnd === null) {
  1607. currentConditionalNodeEnd = node.end;
  1608. }
  1609. return;
  1610. case 'UnaryExpression':
  1611. // rewrite `typeof module`, `typeof module.exports` and `typeof exports` (https://github.com/rollup/rollup-plugin-commonjs/issues/151)
  1612. if (node.operator === 'typeof') {
  1613. const flattened = getKeypath(node.argument);
  1614. if (!flattened) return;
  1615. if (scope.contains(flattened.name)) return;
  1616. if (
  1617. !isEsModule &&
  1618. (flattened.keypath === 'module.exports' ||
  1619. flattened.keypath === 'module' ||
  1620. flattened.keypath === 'exports')
  1621. ) {
  1622. magicString.overwrite(node.start, node.end, `'object'`, {
  1623. storeName: false
  1624. });
  1625. }
  1626. }
  1627. return;
  1628. case 'VariableDeclaration':
  1629. if (!scope.parent) {
  1630. topLevelDeclarations.push(node);
  1631. }
  1632. return;
  1633. case 'TemplateElement':
  1634. if (node.value.raw.includes('\n')) {
  1635. indentExclusionRanges.push([node.start, node.end]);
  1636. }
  1637. }
  1638. },
  1639. leave(node) {
  1640. programDepth -= 1;
  1641. if (node.scope) scope = scope.parent;
  1642. if (functionType.test(node.type)) lexicalDepth -= 1;
  1643. }
  1644. });
  1645. const nameBase = getName(id);
  1646. const exportsName = deconflict([...exportsAccessScopes], globals, nameBase);
  1647. const moduleName = deconflict([...moduleAccessScopes], globals, `${nameBase}Module`);
  1648. const requireName = deconflict([scope], globals, `require${capitalize(nameBase)}`);
  1649. const isRequiredName = deconflict([scope], globals, `hasRequired${capitalize(nameBase)}`);
  1650. const helpersName = deconflict([scope], globals, 'commonjsHelpers');
  1651. const dynamicRequireName =
  1652. replacedDynamicRequires.length > 0 &&
  1653. deconflict(
  1654. [scope],
  1655. globals,
  1656. isDynamicRequireModulesEnabled ? CREATE_COMMONJS_REQUIRE_EXPORT : COMMONJS_REQUIRE_EXPORT
  1657. );
  1658. const deconflictedExportNames = Object.create(null);
  1659. for (const [exportName, { scopes }] of exportsAssignmentsByName) {
  1660. deconflictedExportNames[exportName] = deconflict([...scopes], globals, exportName);
  1661. }
  1662. for (const node of replacedGlobal) {
  1663. magicString.overwrite(node.start, node.end, `${helpersName}.commonjsGlobal`, {
  1664. storeName: true
  1665. });
  1666. }
  1667. for (const node of replacedDynamicRequires) {
  1668. magicString.overwrite(
  1669. node.start,
  1670. node.end,
  1671. isDynamicRequireModulesEnabled
  1672. ? `${dynamicRequireName}(${JSON.stringify(virtualDynamicRequirePath)})`
  1673. : dynamicRequireName,
  1674. {
  1675. contentOnly: true,
  1676. storeName: true
  1677. }
  1678. );
  1679. }
  1680. // We cannot wrap ES/mixed modules
  1681. shouldWrap = !isEsModule && (shouldWrap || (uses.exports && moduleExportsAssignments.length > 0));
  1682. const detectWrappedDefault =
  1683. shouldWrap &&
  1684. (reexports ||
  1685. topLevelDefineCompiledEsmExpressions.length > 0 ||
  1686. code.indexOf('__esModule') >= 0);
  1687. if (
  1688. !(
  1689. shouldWrap ||
  1690. isRequired ||
  1691. needsRequireWrapper ||
  1692. uses.module ||
  1693. uses.exports ||
  1694. uses.require ||
  1695. topLevelDefineCompiledEsmExpressions.length > 0
  1696. ) &&
  1697. (ignoreGlobal || !uses.global)
  1698. ) {
  1699. return { meta: { commonjs: { isCommonJS: false } } };
  1700. }
  1701. let leadingComment = '';
  1702. if (code.startsWith('/*')) {
  1703. const commentEnd = code.indexOf('*/', 2) + 2;
  1704. leadingComment = `${code.slice(0, commentEnd)}\n`;
  1705. magicString.remove(0, commentEnd).trim();
  1706. }
  1707. const exportMode = isEsModule
  1708. ? 'none'
  1709. : shouldWrap
  1710. ? uses.module
  1711. ? 'module'
  1712. : 'exports'
  1713. : firstTopLevelModuleExportsAssignment
  1714. ? exportsAssignmentsByName.size === 0 && topLevelDefineCompiledEsmExpressions.length === 0
  1715. ? 'replace'
  1716. : 'module'
  1717. : moduleExportsAssignments.length === 0
  1718. ? 'exports'
  1719. : 'module';
  1720. const importBlock = await rewriteRequireExpressionsAndGetImportBlock(
  1721. magicString,
  1722. topLevelDeclarations,
  1723. reassignedNames,
  1724. helpersName,
  1725. dynamicRequireName,
  1726. moduleName,
  1727. exportsName,
  1728. id,
  1729. exportMode,
  1730. resolveRequireSourcesAndUpdateMeta,
  1731. needsRequireWrapper,
  1732. isEsModule,
  1733. isDynamicRequireModulesEnabled,
  1734. getIgnoreTryCatchRequireStatementMode,
  1735. commonjsMeta
  1736. );
  1737. const usesRequireWrapper = commonjsMeta.isCommonJS === IS_WRAPPED_COMMONJS;
  1738. const exportBlock = isEsModule
  1739. ? ''
  1740. : rewriteExportsAndGetExportsBlock(
  1741. magicString,
  1742. moduleName,
  1743. exportsName,
  1744. shouldWrap,
  1745. moduleExportsAssignments,
  1746. firstTopLevelModuleExportsAssignment,
  1747. exportsAssignmentsByName,
  1748. topLevelAssignments,
  1749. topLevelDefineCompiledEsmExpressions,
  1750. deconflictedExportNames,
  1751. code,
  1752. helpersName,
  1753. exportMode,
  1754. detectWrappedDefault,
  1755. defaultIsModuleExports,
  1756. usesRequireWrapper,
  1757. requireName
  1758. );
  1759. if (shouldWrap) {
  1760. wrapCode(magicString, uses, moduleName, exportsName, indentExclusionRanges);
  1761. }
  1762. if (usesRequireWrapper) {
  1763. magicString.trim().indent('\t', {
  1764. exclude: indentExclusionRanges
  1765. });
  1766. magicString.prepend(
  1767. `var ${isRequiredName};
  1768. function ${requireName} () {
  1769. \tif (${isRequiredName}) return ${exportsName};
  1770. \t${isRequiredName} = 1;
  1771. `
  1772. ).append(`
  1773. \treturn ${exportsName};
  1774. }`);
  1775. if (exportMode === 'replace') {
  1776. magicString.prepend(`var ${exportsName};\n`);
  1777. }
  1778. }
  1779. magicString
  1780. .trim()
  1781. .prepend(leadingComment + importBlock)
  1782. .append(exportBlock);
  1783. return {
  1784. code: magicString.toString(),
  1785. map: sourceMap ? magicString.generateMap() : null,
  1786. syntheticNamedExports: isEsModule || usesRequireWrapper ? false : '__moduleExports',
  1787. meta: { commonjs: commonjsMeta }
  1788. };
  1789. }
  1790. const PLUGIN_NAME = 'commonjs';
  1791. function commonjs(options = {}) {
  1792. const {
  1793. ignoreGlobal,
  1794. ignoreDynamicRequires,
  1795. requireReturnsDefault: requireReturnsDefaultOption,
  1796. defaultIsModuleExports: defaultIsModuleExportsOption,
  1797. esmExternals
  1798. } = options;
  1799. const extensions = options.extensions || ['.js'];
  1800. const filter = pluginutils.createFilter(options.include, options.exclude);
  1801. const isPossibleCjsId = (id) => {
  1802. const extName = path.extname(id);
  1803. return extName === '.cjs' || (extensions.includes(extName) && filter(id));
  1804. };
  1805. const { strictRequiresFilter, detectCyclesAndConditional } = getStrictRequiresFilter(options);
  1806. const getRequireReturnsDefault =
  1807. typeof requireReturnsDefaultOption === 'function'
  1808. ? requireReturnsDefaultOption
  1809. : () => requireReturnsDefaultOption;
  1810. let esmExternalIds;
  1811. const isEsmExternal =
  1812. typeof esmExternals === 'function'
  1813. ? esmExternals
  1814. : Array.isArray(esmExternals)
  1815. ? ((esmExternalIds = new Set(esmExternals)), (id) => esmExternalIds.has(id))
  1816. : () => esmExternals;
  1817. const getDefaultIsModuleExports =
  1818. typeof defaultIsModuleExportsOption === 'function'
  1819. ? defaultIsModuleExportsOption
  1820. : () =>
  1821. typeof defaultIsModuleExportsOption === 'boolean' ? defaultIsModuleExportsOption : 'auto';
  1822. const dynamicRequireRoot =
  1823. typeof options.dynamicRequireRoot === 'string'
  1824. ? path.resolve(options.dynamicRequireRoot)
  1825. : process.cwd();
  1826. const { commonDir, dynamicRequireModules } = getDynamicRequireModules(
  1827. options.dynamicRequireTargets,
  1828. dynamicRequireRoot
  1829. );
  1830. const isDynamicRequireModulesEnabled = dynamicRequireModules.size > 0;
  1831. const ignoreRequire =
  1832. typeof options.ignore === 'function'
  1833. ? options.ignore
  1834. : Array.isArray(options.ignore)
  1835. ? (id) => options.ignore.includes(id)
  1836. : () => false;
  1837. const getIgnoreTryCatchRequireStatementMode = (id) => {
  1838. const mode =
  1839. typeof options.ignoreTryCatch === 'function'
  1840. ? options.ignoreTryCatch(id)
  1841. : Array.isArray(options.ignoreTryCatch)
  1842. ? options.ignoreTryCatch.includes(id)
  1843. : typeof options.ignoreTryCatch !== 'undefined'
  1844. ? options.ignoreTryCatch
  1845. : true;
  1846. return {
  1847. canConvertRequire: mode !== 'remove' && mode !== true,
  1848. shouldRemoveRequire: mode === 'remove'
  1849. };
  1850. };
  1851. const { currentlyResolving, resolveId } = getResolveId(extensions, isPossibleCjsId);
  1852. const sourceMap = options.sourceMap !== false;
  1853. // Initialized in buildStart
  1854. let requireResolver;
  1855. function transformAndCheckExports(code, id) {
  1856. const { isEsModule, hasDefaultExport, hasNamedExports, ast } = analyzeTopLevelStatements(
  1857. this.parse,
  1858. code,
  1859. id
  1860. );
  1861. const commonjsMeta = this.getModuleInfo(id).meta.commonjs || {};
  1862. if (hasDefaultExport) {
  1863. commonjsMeta.hasDefaultExport = true;
  1864. }
  1865. if (hasNamedExports) {
  1866. commonjsMeta.hasNamedExports = true;
  1867. }
  1868. if (
  1869. !dynamicRequireModules.has(normalizePathSlashes(id)) &&
  1870. (!(hasCjsKeywords(code, ignoreGlobal) || requireResolver.isRequiredId(id)) ||
  1871. (isEsModule && !options.transformMixedEsModules))
  1872. ) {
  1873. commonjsMeta.isCommonJS = false;
  1874. return { meta: { commonjs: commonjsMeta } };
  1875. }
  1876. const needsRequireWrapper =
  1877. !isEsModule &&
  1878. (dynamicRequireModules.has(normalizePathSlashes(id)) || strictRequiresFilter(id));
  1879. const checkDynamicRequire = (position) => {
  1880. if (id.indexOf(dynamicRequireRoot) !== 0) {
  1881. this.error(
  1882. {
  1883. code: 'DYNAMIC_REQUIRE_OUTSIDE_ROOT',
  1884. id,
  1885. dynamicRequireRoot,
  1886. message: `"${id}" contains dynamic require statements but it is not within the current dynamicRequireRoot "${dynamicRequireRoot}". You should set dynamicRequireRoot to "${path.dirname(
  1887. id
  1888. )}" or one of its parent directories.`
  1889. },
  1890. position
  1891. );
  1892. }
  1893. };
  1894. return transformCommonjs(
  1895. this.parse,
  1896. code,
  1897. id,
  1898. isEsModule,
  1899. ignoreGlobal || isEsModule,
  1900. ignoreRequire,
  1901. ignoreDynamicRequires && !isDynamicRequireModulesEnabled,
  1902. getIgnoreTryCatchRequireStatementMode,
  1903. sourceMap,
  1904. isDynamicRequireModulesEnabled,
  1905. dynamicRequireModules,
  1906. commonDir,
  1907. ast,
  1908. getDefaultIsModuleExports(id),
  1909. needsRequireWrapper,
  1910. requireResolver.resolveRequireSourcesAndUpdateMeta(this),
  1911. requireResolver.isRequiredId(id),
  1912. checkDynamicRequire,
  1913. commonjsMeta
  1914. );
  1915. }
  1916. return {
  1917. name: PLUGIN_NAME,
  1918. version,
  1919. options(rawOptions) {
  1920. // We inject the resolver in the beginning so that "catch-all-resolver" like node-resolver
  1921. // do not prevent our plugin from resolving entry points ot proxies.
  1922. const plugins = Array.isArray(rawOptions.plugins)
  1923. ? [...rawOptions.plugins]
  1924. : rawOptions.plugins
  1925. ? [rawOptions.plugins]
  1926. : [];
  1927. plugins.unshift({
  1928. name: 'commonjs--resolver',
  1929. resolveId
  1930. });
  1931. return { ...rawOptions, plugins };
  1932. },
  1933. buildStart({ plugins }) {
  1934. validateVersion(this.meta.rollupVersion, peerDependencies.rollup, 'rollup');
  1935. const nodeResolve = plugins.find(({ name }) => name === 'node-resolve');
  1936. if (nodeResolve) {
  1937. validateVersion(nodeResolve.version, '^13.0.6', '@rollup/plugin-node-resolve');
  1938. }
  1939. if (options.namedExports != null) {
  1940. this.warn(
  1941. 'The namedExports option from "@rollup/plugin-commonjs" is deprecated. Named exports are now handled automatically.'
  1942. );
  1943. }
  1944. requireResolver = getRequireResolver(
  1945. extensions,
  1946. detectCyclesAndConditional,
  1947. currentlyResolving
  1948. );
  1949. },
  1950. buildEnd() {
  1951. if (options.strictRequires === 'debug') {
  1952. const wrappedIds = requireResolver.getWrappedIds();
  1953. if (wrappedIds.length) {
  1954. this.warn({
  1955. code: 'WRAPPED_IDS',
  1956. ids: wrappedIds,
  1957. message: `The commonjs plugin automatically wrapped the following files:\n[\n${wrappedIds
  1958. .map((id) => `\t${JSON.stringify(path.relative(process.cwd(), id))}`)
  1959. .join(',\n')}\n]`
  1960. });
  1961. } else {
  1962. this.warn({
  1963. code: 'WRAPPED_IDS',
  1964. ids: wrappedIds,
  1965. message: 'The commonjs plugin did not wrap any files.'
  1966. });
  1967. }
  1968. }
  1969. },
  1970. load(id) {
  1971. if (id === HELPERS_ID) {
  1972. return getHelpersModule();
  1973. }
  1974. if (isWrappedId(id, MODULE_SUFFIX)) {
  1975. const module = getName(unwrapId(id, MODULE_SUFFIX));
  1976. const moduleExports = `${module}Exports`;
  1977. return {
  1978. code: `var ${moduleExports} = {};
  1979. var ${module} = {
  1980. get exports(){ return ${moduleExports}; },
  1981. set exports(v){ ${moduleExports} = v; },
  1982. };
  1983. export {${module} as __module, ${moduleExports} as exports}`,
  1984. meta: { commonjs: { isCommonJS: false } }
  1985. };
  1986. }
  1987. if (isWrappedId(id, EXPORTS_SUFFIX)) {
  1988. const name = getName(unwrapId(id, EXPORTS_SUFFIX));
  1989. return {
  1990. code: `var ${name} = {}; export {${name} as __exports}`,
  1991. meta: { commonjs: { isCommonJS: false } }
  1992. };
  1993. }
  1994. if (isWrappedId(id, EXTERNAL_SUFFIX)) {
  1995. const actualId = unwrapId(id, EXTERNAL_SUFFIX);
  1996. return getUnknownRequireProxy(
  1997. actualId,
  1998. isEsmExternal(actualId) ? getRequireReturnsDefault(actualId) : true
  1999. );
  2000. }
  2001. // entry suffix is just appended to not mess up relative external resolution
  2002. if (id.endsWith(ENTRY_SUFFIX)) {
  2003. const acutalId = id.slice(0, -ENTRY_SUFFIX.length);
  2004. return getEntryProxy(acutalId, getDefaultIsModuleExports(acutalId), this.getModuleInfo);
  2005. }
  2006. if (isWrappedId(id, ES_IMPORT_SUFFIX)) {
  2007. const actualId = unwrapId(id, ES_IMPORT_SUFFIX);
  2008. return getEsImportProxy(actualId, getDefaultIsModuleExports(actualId));
  2009. }
  2010. if (id === DYNAMIC_MODULES_ID) {
  2011. return getDynamicModuleRegistry(
  2012. isDynamicRequireModulesEnabled,
  2013. dynamicRequireModules,
  2014. commonDir,
  2015. ignoreDynamicRequires
  2016. );
  2017. }
  2018. if (isWrappedId(id, PROXY_SUFFIX)) {
  2019. const actualId = unwrapId(id, PROXY_SUFFIX);
  2020. return getStaticRequireProxy(actualId, getRequireReturnsDefault(actualId), this.load);
  2021. }
  2022. return null;
  2023. },
  2024. shouldTransformCachedModule(...args) {
  2025. return requireResolver.shouldTransformCachedModule.call(this, ...args);
  2026. },
  2027. transform(code, id) {
  2028. if (!isPossibleCjsId(id)) return null;
  2029. try {
  2030. return transformAndCheckExports.call(this, code, id);
  2031. } catch (err) {
  2032. return this.error(err, err.loc);
  2033. }
  2034. }
  2035. };
  2036. }
  2037. exports.default = commonjs;
  2038. module.exports = Object.assign(exports.default, exports);
  2039. //# sourceMappingURL=index.js.map