index.js 71 KB

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