@rollup/plugin-commonjs 21.0.1 → 22.0.0-11

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