UNPKG

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