/* eslint-disable line-comment-position, no-new-func, no-undefined */ const os = require('os'); const path = require('path'); const { nodeResolve } = require('@rollup/plugin-node-resolve'); const { getLocator } = require('locate-character'); const { rollup } = require('rollup'); const { install } = require('source-map-support'); const { testBundle } = require('../../../util/test'); const { peerDependencies } = require('../package.json'); const { commonjs, executeBundle, getCodeFromBundle, normalizePathSlashes } = require('./helpers/util.js'); const avaAssertions = { is(actual, expected, message) { expect(actual, message).toBe(expected); }, deepEqual(actual, expected, message) { expect(actual, message).toEqual(expected); }, truthy(value, message) { expect(value, message).toBeTruthy(); }, throws(fn, expectation) { try { fn(); } catch (error) { if (expectation?.message instanceof RegExp) { expect(error.message).toMatch(expectation.message); } else if (expectation?.message) { expect(error.message).toBe(expectation.message); } return error; } return expect.unreachable('Expected function to throw'); } }; const expectNoError = (valueOrFactory) => typeof valueOrFactory === 'function' ? valueOrFactory() : valueOrFactory; install(); beforeEach(() => process.chdir(__dirname)); const loader = (modules) => { return { load(id) { if (Object.hasOwnProperty.call(modules, id)) { return modules[id]; } return null; }, resolveId(id) { if (Object.hasOwnProperty.call(modules, id)) { return id; } return null; } }; }; test('Rollup peer dependency has correct format', () => { expect(peerDependencies.rollup).toMatch(/^\^\d+\.\d+\.\d+(\|\|\^\d+\.\d+\.\d+)*$/); }); test('exposes plugin version', () => { const plugin = commonjs(); expect(plugin.version).toMatch(/^\d+\.\d+\.\d+/); }); // most of these should be moved over to function... test('generates a sourcemap', async () => { const bundle = await rollup({ input: 'fixtures/samples/sourcemap/main.js', plugins: [ commonjs({ sourceMap: true }) ] }); const { output: [{ code, map }] } = await bundle.generate({ exports: 'auto', format: 'cjs', sourcemap: true, sourcemapFile: path.resolve('bundle.js') }); // source-map uses the presence of fetch to detect browser environments which // breaks in Node 18 const { fetch } = global; delete global.fetch; const { SourceMapConsumer } = await import('source-map'); const smc = await new SourceMapConsumer(map); global.fetch = fetch; const locator = getLocator(code, { offsetLine: 1 }); let generatedLoc = locator('42'); let loc = smc.originalPositionFor(generatedLoc); // 42 expect(loc.source).toBe('fixtures/samples/sourcemap/foo.js'); expect(loc.line).toBe(1); expect(loc.column).toBe(15); generatedLoc = locator('log'); loc = smc.originalPositionFor(generatedLoc); // log expect(loc.source).toBe('fixtures/samples/sourcemap/main.js'); expect(loc.line).toBe(3); expect(loc.column).toBe(8); }); test('supports an array of multiple entry points', async () => { const bundle = await rollup({ input: [ 'fixtures/samples/multiple-entry-points/b.js', 'fixtures/samples/multiple-entry-points/c.js' ], plugins: [commonjs()] }); const { output } = await bundle.generate({ exports: 'auto', format: 'cjs', chunkFileNames: '[name].js' }); if (Array.isArray(output)) { expect(output.length).toBe(3); expect(output.find(({ fileName }) => fileName === 'b.js')).toBeTruthy(); expect(output.find(({ fileName }) => fileName === 'c.js')).toBeTruthy(); } else { expect(Object.keys(output).length).toBe(3); expect('b.js' in output).toBe(true); expect('c.js' in output).toBe(true); } }); test('supports an object of multiple entry points', async () => { const bundle = await rollup({ input: { b: require.resolve('./fixtures/samples/multiple-entry-points/b.js'), c: require.resolve('./fixtures/samples/multiple-entry-points/c.js') }, plugins: [nodeResolve(), commonjs()] }); const { output } = await bundle.generate({ exports: 'auto', format: 'cjs', chunkFileNames: '[name].js' }); if (Array.isArray(output)) { expect(output.length).toBe(3); expect(output.find(({ fileName }) => fileName === 'b.js')).toBeTruthy(); expect(output.find(({ fileName }) => fileName === 'c.js')).toBeTruthy(); } else { expect(Object.keys(output).length).toBe(3); expect('b.js' in output).toBe(true); expect('c.js' in output).toBe(true); } }); test('handles references to `global`', async () => { const bundle = await rollup({ input: 'fixtures/samples/global/main.js', plugins: [commonjs()] }); const code = await getCodeFromBundle(bundle); const mockWindow = {}; const mockGlobal = {}; const mockSelf = {}; const fn = new Function('module', 'globalThis', 'window', 'global', 'self', code); fn({}, undefined, mockWindow, mockGlobal, mockSelf); expect(mockWindow.foo, code).toBe('bar'); expect(mockGlobal.foo, code).toBe(undefined); expect(mockSelf.foo, code).toBe(undefined); fn({}, undefined, undefined, mockGlobal, mockSelf); expect(mockGlobal.foo, code).toBe('bar'); expect(mockSelf.foo, code).toBe(undefined); fn({}, undefined, undefined, undefined, mockSelf); expect(mockSelf.foo, code).toBe('bar'); }); test('handles multiple references to `global`', async () => { const bundle = await rollup({ input: 'fixtures/samples/global-in-if-block/main.js', plugins: [commonjs()] }); const code = await getCodeFromBundle(bundle); const fn = new Function('module', 'exports', 'globalThis', code); const module = { exports: {} }; const globalThis = {}; fn(module, module.exports, globalThis); expect(globalThis.count).toBe(1); fn(module, module.exports, globalThis); expect(globalThis.count).toBe(2); }); test('handles transpiled CommonJS modules', async () => { const bundle = await rollup({ input: 'fixtures/samples/corejs/literal-with-default.js', plugins: [commonjs()] }); const code = await getCodeFromBundle(bundle); const module = { exports: {} }; const fn = new Function('module', 'exports', code); fn(module, module.exports); expect(module.exports, code).toBe('foobar'); }); test('handles successive builds', async () => { const plugin = commonjs(); let bundle = await rollup({ input: 'fixtures/samples/corejs/literal-with-default.js', plugins: [plugin] }); await bundle.generate({ exports: 'auto', format: 'cjs' }); bundle = await rollup({ input: 'fixtures/samples/corejs/literal-with-default.js', plugins: [plugin] }); const code = await getCodeFromBundle(bundle); const module = { exports: {} }; const fn = new Function('module', 'exports', code); fn(module, module.exports); expect(module.exports, code).toBe('foobar'); }); test.sequential('handles symlinked node_modules with preserveSymlinks: false', () => { const cwd = process.cwd(); // ensure we resolve starting from a directory with // symlinks in node_modules. process.chdir(path.join(__dirname, 'fixtures/samples/symlinked-node-modules')); return expectNoError( rollup({ input: './index.js', onwarn(warning) { // should not get a warning about unknown export 'foo' throw new Error(`Unexpected warning: ${warning.message}`); }, plugins: [ nodeResolve({ preserveSymlinks: false, preferBuiltins: false }), commonjs() ] }) .then((v) => { process.chdir(cwd); return v; }) .catch((err) => { process.chdir(cwd); throw err; }) ); }); test('converts a CommonJS module with custom file extension', async () => { const bundle = await rollup({ input: 'fixtures/samples/extension/main.coffee', plugins: [ commonjs({ extensions: ['.coffee'] }) ] }); expect((await executeBundle(bundle, avaAssertions)).exports).toBe(42); }); test('import CommonJS module with esm property should get default export ', async () => { const bundle = await rollup({ input: 'fixtures/samples/cjs-with-esm-property/main.js', plugins: [ commonjs({ defaultIsModuleExports: 'auto' }) ] }); const result = await executeBundle(bundle, avaAssertions); expect(result.error).toBe(undefined); const bundle2 = await rollup({ input: 'fixtures/samples/cjs-with-esm-property/main.js', plugins: [ commonjs({ defaultIsModuleExports: true }) ] }); const result2 = await executeBundle(bundle2, avaAssertions); expect(result2.error.message).toBe('libExports is not a function'); }); test('identifies named exports from object literals', async () => { const bundle = await rollup({ input: 'fixtures/samples/named-exports-from-object-literal/main.js', plugins: [commonjs()] }); expect.assertions(3); await testBundle(avaAssertions, bundle); }); test('can ignore references to `global`', async () => { const bundle = await rollup({ input: 'fixtures/samples/ignore-global/main.js', plugins: [ commonjs({ ignoreGlobal: true }) ], onwarn: (warning) => { if (warning.code === 'THIS_IS_UNDEFINED') return; // eslint-disable-next-line no-console console.warn(warning.message); } }); const code = await getCodeFromBundle(bundle); const { exports, global } = await executeBundle(bundle, avaAssertions); expect(exports.immediate1, code).toBe(global.setImmediate); expect(exports.immediate2, code).toBe(global.setImmediate); expect(exports.immediate3, code).toBe(null); }); test('can handle parens around right have node while producing default export', async () => { const bundle = await rollup({ input: 'fixtures/samples/paren-expression/index.js', plugins: [commonjs()] }); expect( ( await executeBundle(bundle, avaAssertions, { testEntry: 'index.js' }) ).exports ).toBe(42); }); test('typeof transforms: correct-scoping', async () => { const bundle = await rollup({ input: 'fixtures/samples/umd/correct-scoping.js', plugins: [commonjs()] }); expect( ( await executeBundle(bundle, avaAssertions, { testEntry: 'correct-scoping.js' }) ).exports ).toBe('object'); }); test('typeof transforms: protobuf', async () => { const bundle = await rollup({ input: 'fixtures/samples/umd/protobuf.js', external: ['bytebuffer', 'foo'], plugins: [commonjs()] }); expect( ( await executeBundle(bundle, avaAssertions, { testEntry: 'protobuf.js' }) ).exports ).toBe(true); }); test('typeof transforms: sinon', async () => { const bundle = await rollup({ input: 'fixtures/samples/umd/sinon.js', plugins: [commonjs()] }); const { output: [{ code }] } = await bundle.generate({ format: 'es' }); expect(code.indexOf('typeof require'), code).toBe(-1); expect(code.indexOf('typeof module'), code).toBe(-1); expect(code.indexOf('typeof define'), code).toBe(-1); }); test('deconflicts helper name', async () => { const bundle = await rollup({ input: 'fixtures/samples/deconflict-helpers/main.js', plugins: [commonjs()] }); const { exports } = await executeBundle(bundle, avaAssertions); expect(exports).not.toBe('nope'); }); test('deconflicts reserved keywords', async () => { const bundle = await rollup({ input: 'fixtures/samples/reserved-as-property/main.js', plugins: [commonjs()] }); const reservedProp = ( await executeBundle(bundle, avaAssertions, { exports: 'default' }) ).exports.delete; expect(reservedProp).toBe('foo'); }); test('does not process the entry file when it has a leading "." (issue #63)', async () => { const bundle = await rollup({ input: './fixtures/function/basic/main.js', plugins: [commonjs()] }); await expectNoError(executeBundle(bundle, avaAssertions)); }); test('respects other plugins', async () => { const bundle = await rollup({ input: 'fixtures/samples/other-transforms/main.js', plugins: [ { transform(code, id) { if (id[0] === '\0') return null; return code.replace('40', '41'); } }, commonjs() ] }); await expectNoError(executeBundle(bundle, avaAssertions)); }); test('rewrites top-level defines', async () => { const bundle = await rollup({ input: 'fixtures/samples/define-is-undefined/main.js', plugins: [commonjs()] }); function define() { throw new Error('nope'); } define.amd = true; const { exports } = await executeBundle(bundle, avaAssertions, { context: { define } }); expect(exports).toBe(42); }); test('respects options.external', async () => { const bundle = await rollup({ input: 'fixtures/samples/external/main.js', plugins: [nodeResolve(), commonjs()], external: ['baz'] }); const code = await getCodeFromBundle(bundle); expect(code.indexOf('hello')).toBe(-1); const { exports } = await executeBundle(bundle, avaAssertions); expect(exports).toBe('HELLO'); }); test('prefers to set name using directory for index files', async () => { const bundle = await rollup({ input: 'fixtures/samples/rename-index/main.js', plugins: [commonjs()] }); const code = await getCodeFromBundle(bundle); expect(code.indexOf('var index'), 'does not contain index').toBe(-1); expect(code.indexOf('var invalidVar'), 'contains invalidVar').not.toBe(-1); expect(code.indexOf('var validVar'), 'contains validVar').not.toBe(-1); expect(code.indexOf('var nonIndex'), 'contains nonIndex').not.toBe(-1); }); test('correctly wraps the default export from a CommonJS module when it is a class', async () => { const bundle = await rollup({ input: 'fixtures/samples/es-module-with-class-as-default-export/main.js', plugins: [commonjs()] }); const result = await executeBundle(bundle, avaAssertions); expect(result.error).toBe(undefined); }); test('does not warn even if the ES module does not export "default"', async () => { const warns = []; await rollup({ input: 'fixtures/samples/es-modules-without-default-export/main.js', plugins: [commonjs()], onwarn: (warn) => warns.push(warn) }); expect(warns.length).toBe(0); await rollup({ input: 'fixtures/function/bare-import/bar.js', plugins: [commonjs()], onwarn: (warn) => warns.push(warn) }); expect(warns.length).toBe(0); await rollup({ input: 'fixtures/function/bare-import-comment/main.js', plugins: [commonjs()], onwarn: (warn) => warns.push(warn) }); expect(warns.length).toBe(0); }); test('compiles with cache', async () => { const plugin = commonjs(); const { cache } = await rollup({ input: 'fixtures/function/index/main.js', plugins: [plugin] }); await expectNoError( rollup({ input: 'fixtures/function/index/main.js', plugins: [plugin], cache }) ); }); test('creates an error with a code frame when parsing fails', async () => { try { await rollup({ input: 'fixtures/samples/invalid-syntax/main.js', plugins: [commonjs()] }); } catch (error) { expect(error.frame).toBe(`1: /* eslint-disable */ 2: export const foo = 2, ^`); } }); // Virtual modules are treated as "requireReturnsDefault: 'always'" to avoid interop test('ignores virtual modules', async () => { const bundle = await rollup({ input: 'fixtures/samples/ignore-virtual-modules/main.js', plugins: [ commonjs(), { resolveId(id) { if (id === '\0virtual' || id === '\0resolved-virtual') { return '\0resolved-virtual'; } return null; }, load(id) { if (id === '\0resolved-virtual') { return 'export default "Virtual export"'; } return null; } } ] }); expect((await executeBundle(bundle, avaAssertions)).exports).toBe('Virtual export'); }); test('does not produce warnings when importing .mjs without default export', async () => { const bundle = await rollup({ input: 'main.mjs', onwarn(warning) { // The interop should not trigger a "default is not exported" warning throw new Error(`Unexpected warning: ${warning.message}`); }, plugins: [ commonjs(), { load(id) { if (id === 'main.mjs') { return 'import cjs from "cjs.js"; export default cjs;'; } if (id === 'cjs.js') { // CJS libraries expect to receive a CJS file here return 'module.exports = require("fromNodeModules");'; } if (id === 'fromNodeModules.mjs') { return 'export const result = "from esm";'; } return null; }, resolveId(id) { // rollup-plugin-node-resolve usually prefers ESM versions if (id === 'fromNodeModules') { return 'fromNodeModules.mjs'; } return id; } } ] }); expect((await executeBundle(bundle, avaAssertions)).exports).toEqual({ result: 'from esm' }); }); test('produces optimized code when importing esm with a known default export', async () => { const bundle = await rollup({ input: 'main.js', plugins: [ commonjs({ requireReturnsDefault: true }), loader({ 'main.js': 'module.exports = require("esm.js")', 'esm.js': 'export const ignored = "ignored"; export default "default"' }) ] }); expect(await getCodeFromBundle(bundle)).toMatchSnapshot(); }); test('produces optimized code when importing esm without a default export', async () => { const bundle = await rollup({ input: 'main.js', plugins: [ commonjs(), loader({ 'main.js': 'module.exports = require("esm.js")', 'esm.js': 'export const value = "value";' }) ] }); expect(await getCodeFromBundle(bundle)).toMatchSnapshot(); }); test('handles array destructuring assignment', async () => { const bundle = await rollup({ input: 'fixtures/samples/array-destructuring-assignment/main.js', plugins: [ commonjs({ sourceMap: true }) ] }); expect( await getCodeFromBundle(bundle, { exports: 'named' }) ).toMatchSnapshot(); }); test('can spread an object into module.exports', async () => { const bundle = await rollup({ input: 'fixtures/samples/module-exports-spread/main.js', plugins: [commonjs()] }); expect(await getCodeFromBundle(bundle)).toMatchSnapshot(); }); test('logs a warning when the deprecated namedExports option is used', async () => { let message; const bundle = await rollup({ onwarn(warning) { ({ message } = warning); }, input: 'fixtures/samples/sourcemap/main.js', plugins: [ commonjs({ namedExports: { foo: ['bar'] } }) ] }); await getCodeFromBundle(bundle); expect(message).toBe( 'The namedExports option from "@rollup/plugin-commonjs" is deprecated. Named exports are now handled automatically.' ); }); // This test uses worker threads to simulate an empty internal cache and needs at least Node 12 if (Number(/^v(\d+)/.exec(process.version)[1]) >= 12) { test('can be cached across instances', async () => { const bundle = await rollup({ input: 'fixtures/samples/caching/main.js', plugins: [commonjs()] }); const { cache } = bundle; const code = await getCodeFromBundle(bundle); // We do a second run in a worker so that all internal state is cleared const { Worker } = await import('worker_threads'); const getRollupUpCodeWithCache = new Worker( path.join(__dirname, 'fixtures/samples/caching/rollupWorker.js'), { workerData: cache } ); expect(code).toBe(await new Promise((done) => getRollupUpCodeWithCache.on('message', done))); }); } test('does not affect subsequently created instances when called with `requireReturnsDefault: "preferred"`', async () => { const input = 'fixtures/function/import-esm-require-returns-default-preferred/main.js'; const options = { requireReturnsDefault: 'preferred' }; const instance1 = commonjs(options); const bundle1 = await rollup({ input, plugins: [instance1] }); const code1 = (await bundle1.generate({})).output[0].code; const instance2 = commonjs(options); const bundle2 = await rollup({ input, plugins: [instance2] }); const code2 = (await bundle2.generate({})).output[0].code; expect(code1).toBe(code2); }); // This test works only on Windows, which treats both forward and backward // slashes as path separators if (os.platform() === 'win32') { test('supports both forward and backward slash as path separator in directory-based modules', async () => { const bundle = await rollup({ input: 'fixtures/samples/module-path-separator/main.js', plugins: [ // Ad-hoc plugin that reverses the path separator of foo/index.js { name: 'test-path-separator-reverser', async resolveId(source, importer) { if (source.endsWith('foo')) { const fullPath = path.resolve(path.dirname(importer), source, 'index.js'); // Ensure that the module ID uses a non-default path separator return fullPath.replace(/[\\/]/g, (sep) => (sep === '/' ? '\\' : '/')); } return null; } }, commonjs() ] }); const code = await getCodeFromBundle(bundle); expect(code).toMatch(/var foo(\$\d+)? = {}/); }); } test('throws when there is a dynamic require from outside dynamicRequireRoot', async () => { let error = null; try { await rollup({ input: 'fixtures/samples/dynamic-require-outside-root/main.js', plugins: [ commonjs({ dynamicRequireRoot: 'fixtures/samples/dynamic-require-outside-root/nested', dynamicRequireTargets: ['fixtures/samples/dynamic-require-outside-root/nested/target.js'] }) ] }); } catch (err) { error = err; } const cwd = process.cwd(); const id = normalizePathSlashes( path.join(cwd, 'fixtures/samples/dynamic-require-outside-root/main.js') ); const dynamicRequireRoot = normalizePathSlashes( path.join(cwd, 'fixtures/samples/dynamic-require-outside-root/nested') ); const minimalDynamicRequireRoot = normalizePathSlashes( path.join(cwd, 'fixtures/samples/dynamic-require-outside-root') ); expect(error).toMatchObject({ message: `"${id}" contains dynamic require statements but it is not within the current dynamicRequireRoot "${dynamicRequireRoot}". You should set dynamicRequireRoot to "${minimalDynamicRequireRoot}" or one of its parent directories.`, pluginCode: 'DYNAMIC_REQUIRE_OUTSIDE_ROOT', normalizedId: id, normalizedDynamicRequireRoot: dynamicRequireRoot }); }); test('does not throw when a dynamic require uses different slashes than dynamicRequireRoot', async () => { let error = null; try { await rollup({ input: 'fixtures/samples/dynamic-require-outside-root/main.js', plugins: [ commonjs({ dynamicRequireRoot: 'fixtures\\samples\\dynamic-require-outside-root', dynamicRequireTargets: [ 'fixtures\\samples\\dynamic-require-outside-root\\nested\\target.js' ] }) ] }); } catch (err) { error = err; } expect(error).toBe(null); }); // On Windows, avoid a false error about a module not being in the dynamic require root due to // incoherent slashes/backslashes in the paths. if (os.platform() === 'win32') { test('correctly asserts dynamicRequireRoot on Windows', async () => { let error = null; try { await rollup({ input: 'fixtures/samples/dynamic-require-outside-root/main.js', plugins: [ commonjs({ dynamicRequireRoot: 'fixtures/samples/dynamic-require-outside-root', dynamicRequireTargets: [ 'fixtures/samples/dynamic-require-outside-root/nested/target.js' ] }) ] }); } catch (err) { error = err; } expect(error).toBe(null); }); } test('does not transform typeof exports for mixed modules', async () => { const bundle = await rollup({ input: 'fixtures/samples/mixed-module-typeof-exports/main.js', plugins: [ commonjs({ transformMixedEsModules: true }) ] }); const { output: [{ code }] } = await bundle.generate({ format: 'es' }); expect(code.includes('typeof exports'), '"typeof exports" not found in the code').toBe(true); expect(code).toMatchSnapshot(); }); test('throws when using an old node_resolve version', async () => { let error = null; try { await rollup({ input: 'ignored', plugins: [ commonjs(), { name: nodeResolve().name } ] }); } catch (err) { error = err; } expect(error).toMatchObject({ message: 'Insufficient @rollup/plugin-node-resolve version: "@rollup/plugin-commonjs" requires at least @rollup/plugin-node-resolve@13.0.6.' }); }); test('throws when using an inadequate node_resolve version', async () => { let error = null; try { await rollup({ input: 'ignored', plugins: [ commonjs(), { name: nodeResolve().name, version: '13.0.5' } ] }); } catch (err) { error = err; } expect(error).toMatchObject({ message: 'Insufficient @rollup/plugin-node-resolve version: "@rollup/plugin-commonjs" requires at least @rollup/plugin-node-resolve@13.0.6 but found @rollup/plugin-node-resolve@13.0.5.' }); }); const onwarn = (warning) => { if (warning.code !== 'CIRCULAR_DEPENDENCY') { throw new Error(warning.message); } }; const getTransformTracker = (trackedId) => { const trackedTransforms = []; const meta = {}; return { meta, trackedTransforms, tracker: { name: 'transform-tracker', transform(code, id) { trackedTransforms.push(id); }, moduleParsed({ id, meta: { commonjs: commonjsMeta } }) { if (id === trackedId) { Object.assign(meta, commonjsMeta); } } } }; }; test('handles when an imported dependency of an ES module changes type', async () => { const { meta, tracker, trackedTransforms } = getTransformTracker('dep.js'); const modules = {}; const resetModules = () => { modules['main.js'] = "import {dep} from 'dep.js';export default dep;"; modules['dep.js'] = "export const dep = 'esm';"; }; const options = { input: 'main.js', plugins: [commonjs(), loader(modules), tracker], onwarn }; resetModules(); let bundle = await rollup(options); expect(meta.isCommonJS).toBe(false); expect((await executeBundle(bundle, avaAssertions)).exports).toEqual('esm'); expect(trackedTransforms).toEqual(['main.js', 'dep.js']); trackedTransforms.length = 0; const esCode = await getCodeFromBundle(bundle); expect(esCode).toMatchSnapshot(); modules['dep.js'] = "exports.dep = 'cjs';"; options.cache = bundle.cache; bundle = await rollup(options); expect(meta.isCommonJS).toBe('withRequireFunction'); expect((await executeBundle(bundle, avaAssertions)).exports).toEqual('cjs'); expect(trackedTransforms).toEqual([ 'dep.js', 'main.js', '\0dep.js?commonjs-es-import', '\0commonjsHelpers.js', '\0dep.js?commonjs-exports' ]); trackedTransforms.length = 0; const cjsCode = await getCodeFromBundle(bundle); expect(cjsCode).toMatchSnapshot(); modules['dep.js'] = "exports.dep = 'cjs'; exports.dep += require('dep.js').dep;"; options.cache = bundle.cache; bundle = await rollup(options); expect(meta.isCommonJS).toBe('withRequireFunction'); expect((await executeBundle(bundle, avaAssertions)).exports).toEqual('cjscjs'); expect(trackedTransforms).toEqual(['dep.js']); trackedTransforms.length = 0; const wrappedCode = await getCodeFromBundle(bundle); expect(wrappedCode).toMatchSnapshot(); resetModules(); options.cache = bundle.cache; bundle = await rollup(options); expect(meta.isCommonJS).toBe(false); expect((await executeBundle(bundle, avaAssertions)).exports).toEqual('esm'); expect(trackedTransforms).toEqual(['dep.js', 'main.js']); trackedTransforms.length = 0; expect(await getCodeFromBundle(bundle)).toBe(esCode); modules['dep.js'] = "exports.dep = 'cjs'; exports.dep += require('dep.js').dep;"; options.cache = bundle.cache; bundle = await rollup(options); expect(meta.isCommonJS).toBe('withRequireFunction'); expect((await executeBundle(bundle, avaAssertions)).exports).toEqual('cjscjs'); expect(trackedTransforms).toEqual([ 'dep.js', 'main.js', '\0dep.js?commonjs-es-import', '\0commonjsHelpers.js', '\0dep.js?commonjs-exports' ]); trackedTransforms.length = 0; expect(await getCodeFromBundle(bundle)).toBe(wrappedCode); modules['dep.js'] = "exports.dep = 'cjs';"; options.cache = bundle.cache; bundle = await rollup(options); expect(meta.isCommonJS).toBe('withRequireFunction'); expect((await executeBundle(bundle, avaAssertions)).exports).toEqual('cjs'); expect(trackedTransforms).toEqual(['dep.js']); trackedTransforms.length = 0; expect(await getCodeFromBundle(bundle)).toBe(cjsCode); resetModules(); options.cache = bundle.cache; bundle = await rollup(options); expect(meta.isCommonJS).toBe(false); expect((await executeBundle(bundle, avaAssertions)).exports).toEqual('esm'); expect(trackedTransforms).toEqual(['dep.js', 'main.js']); trackedTransforms.length = 0; expect(await getCodeFromBundle(bundle)).toBe(esCode); }); test('handles when a dynamically imported dependency of an ES module changes type', async () => { const { meta, tracker, trackedTransforms } = getTransformTracker('dep.js'); const modules = {}; const resetModules = () => { modules['main.js'] = "export default import('dep.js').then(({dep}) => dep);"; modules['dep.js'] = "export const dep = 'esm';"; }; const options = { input: 'main.js', plugins: [commonjs(), loader(modules), tracker], onwarn }; resetModules(); let bundle = await rollup(options); expect(meta.isCommonJS).toBe(false); expect(await (await executeBundle(bundle, avaAssertions)).exports).toEqual('esm'); expect(trackedTransforms).toEqual(['main.js', 'dep.js']); trackedTransforms.length = 0; modules['dep.js'] = "exports.dep = 'cjs';"; options.cache = bundle.cache; bundle = await rollup(options); expect(meta.isCommonJS).toBe('withRequireFunction'); expect(await (await executeBundle(bundle, avaAssertions)).exports).toEqual('cjs'); expect(trackedTransforms).toEqual([ 'dep.js', 'main.js', '\0dep.js?commonjs-es-import', '\0commonjsHelpers.js', '\0dep.js?commonjs-exports' ]); trackedTransforms.length = 0; modules['dep.js'] = "exports.dep = 'cjs'; exports.dep += require('dep.js').dep;"; options.cache = bundle.cache; bundle = await rollup(options); expect(meta.isCommonJS).toBe('withRequireFunction'); expect(await (await executeBundle(bundle, avaAssertions)).exports).toEqual('cjscjs'); expect(trackedTransforms).toEqual(['dep.js']); trackedTransforms.length = 0; resetModules(); options.cache = bundle.cache; bundle = await rollup(options); expect(meta.isCommonJS).toBe(false); expect(await (await executeBundle(bundle, avaAssertions)).exports).toEqual('esm'); expect(trackedTransforms).toEqual(['dep.js', 'main.js']); trackedTransforms.length = 0; modules['dep.js'] = "exports.dep = 'cjs'; exports.dep += require('dep.js').dep;"; options.cache = bundle.cache; bundle = await rollup(options); expect(meta.isCommonJS).toBe('withRequireFunction'); expect(await (await executeBundle(bundle, avaAssertions)).exports).toEqual('cjscjs'); expect(trackedTransforms).toEqual([ 'dep.js', 'main.js', '\0dep.js?commonjs-es-import', '\0commonjsHelpers.js', '\0dep.js?commonjs-exports' ]); trackedTransforms.length = 0; modules['dep.js'] = "exports.dep = 'cjs';"; options.cache = bundle.cache; bundle = await rollup(options); expect(meta.isCommonJS).toBe('withRequireFunction'); expect(await (await executeBundle(bundle, avaAssertions)).exports).toEqual('cjs'); expect(trackedTransforms).toEqual(['dep.js']); trackedTransforms.length = 0; resetModules(); options.cache = bundle.cache; bundle = await rollup(options); expect(meta.isCommonJS).toBe(false); expect(await (await executeBundle(bundle, avaAssertions)).exports).toEqual('esm'); expect(trackedTransforms).toEqual(['dep.js', 'main.js']); trackedTransforms.length = 0; }); test('handles when a required dependency of a CJS module changes type', async () => { const { meta, tracker, trackedTransforms } = getTransformTracker('dep.js'); const modules = {}; const resetModules = () => { modules['main.js'] = "module.exports = require('dep.js').dep;"; modules['dep.js'] = "export const dep = 'esm';"; }; const options = { input: 'main.js', plugins: [commonjs(), loader(modules), tracker], onwarn }; resetModules(); let bundle = await rollup(options); expect(meta.isCommonJS).toBe(false); expect((await executeBundle(bundle, avaAssertions)).exports).toEqual('esm'); expect(trackedTransforms).toEqual([ 'dep.js', 'main.js', 'main.js?commonjs-entry', '\0commonjsHelpers.js', '\0dep.js?commonjs-proxy' ]); trackedTransforms.length = 0; const esCode = await getCodeFromBundle(bundle); expect(esCode).toMatchSnapshot(); modules['dep.js'] = "exports.dep = 'cjs';"; options.cache = bundle.cache; bundle = await rollup(options); expect(meta.isCommonJS).toBe('withRequireFunction'); expect((await executeBundle(bundle, avaAssertions)).exports).toEqual('cjs'); expect(trackedTransforms).toEqual([ 'dep.js', 'main.js', 'main.js?commonjs-entry', '\0dep.js?commonjs-exports' ]); trackedTransforms.length = 0; const cjsCode = await getCodeFromBundle(bundle); expect(cjsCode).toMatchSnapshot(); modules['dep.js'] = "exports.dep = 'cjs'; exports.dep += require('dep.js').dep;"; options.cache = bundle.cache; bundle = await rollup(options); expect(meta.isCommonJS).toBe('withRequireFunction'); expect((await executeBundle(bundle, avaAssertions)).exports).toEqual('cjscjs'); expect(trackedTransforms).toEqual(['dep.js', 'main.js?commonjs-entry']); trackedTransforms.length = 0; const wrappedCode = await getCodeFromBundle(bundle); expect(wrappedCode).toMatchSnapshot(); resetModules(); options.cache = bundle.cache; bundle = await rollup(options); expect(meta.isCommonJS).toBe(false); expect((await executeBundle(bundle, avaAssertions)).exports).toEqual('esm'); expect(trackedTransforms).toEqual([ 'dep.js', 'main.js', 'main.js?commonjs-entry', '\0dep.js?commonjs-proxy' ]); trackedTransforms.length = 0; expect(await getCodeFromBundle(bundle)).toBe(esCode); modules['dep.js'] = "exports.dep = 'cjs'; exports.dep += require('dep.js').dep;"; options.cache = bundle.cache; bundle = await rollup(options); expect(meta.isCommonJS).toBe('withRequireFunction'); expect((await executeBundle(bundle, avaAssertions)).exports).toEqual('cjscjs'); expect(trackedTransforms).toEqual([ 'dep.js', 'main.js', 'main.js?commonjs-entry', '\0dep.js?commonjs-exports' ]); trackedTransforms.length = 0; expect(await getCodeFromBundle(bundle)).toBe(wrappedCode); modules['dep.js'] = "exports.dep = 'cjs';"; options.cache = bundle.cache; bundle = await rollup(options); expect(meta.isCommonJS).toBe('withRequireFunction'); expect((await executeBundle(bundle, avaAssertions)).exports).toEqual('cjs'); expect(trackedTransforms).toEqual(['dep.js', 'main.js?commonjs-entry']); trackedTransforms.length = 0; expect(await getCodeFromBundle(bundle)).toBe(cjsCode); resetModules(); options.cache = bundle.cache; bundle = await rollup(options); expect(meta.isCommonJS).toBe(false); expect((await executeBundle(bundle, avaAssertions)).exports).toEqual('esm'); expect(trackedTransforms).toEqual([ 'dep.js', 'main.js', 'main.js?commonjs-entry', '\0dep.js?commonjs-proxy' ]); trackedTransforms.length = 0; expect(await getCodeFromBundle(bundle)).toBe(esCode); }); test('handles when a required dependency of a mixed ES module changes type', async () => { const { meta, tracker, trackedTransforms } = getTransformTracker('dep.js'); const modules = {}; const resetModules = () => { modules['main.js'] = "export default require('dep.js').dep;"; modules['dep.js'] = "export const dep = 'esm';"; }; const options = { input: 'main.js', plugins: [ commonjs({ transformMixedEsModules: true }), loader(modules), tracker ], onwarn }; resetModules(); let bundle = await rollup(options); expect(meta.isCommonJS).toBe(false); expect((await executeBundle(bundle, avaAssertions)).exports).toEqual('esm'); expect(trackedTransforms).toEqual([ 'dep.js', 'main.js', '\0commonjsHelpers.js', '\0dep.js?commonjs-proxy' ]); trackedTransforms.length = 0; const esCode = await getCodeFromBundle(bundle); expect(esCode).toMatchSnapshot(); modules['dep.js'] = "exports.dep = 'cjs';"; options.cache = bundle.cache; bundle = await rollup(options); expect(meta.isCommonJS).toBe('withRequireFunction'); expect((await executeBundle(bundle, avaAssertions)).exports).toEqual('cjs'); expect(trackedTransforms).toEqual(['dep.js', 'main.js', '\0dep.js?commonjs-exports']); trackedTransforms.length = 0; const cjsCode = await getCodeFromBundle(bundle); expect(cjsCode).toMatchSnapshot(); modules['dep.js'] = "exports.dep = 'cjs'; exports.dep += require('dep.js').dep;"; options.cache = bundle.cache; bundle = await rollup(options); expect(meta.isCommonJS).toBe('withRequireFunction'); expect((await executeBundle(bundle, avaAssertions)).exports).toEqual('cjscjs'); expect(trackedTransforms).toEqual(['dep.js']); trackedTransforms.length = 0; const wrappedCode = await getCodeFromBundle(bundle); expect(wrappedCode).toMatchSnapshot(); resetModules(); options.cache = bundle.cache; bundle = await rollup(options); expect(meta.isCommonJS).toBe(false); expect((await executeBundle(bundle, avaAssertions)).exports).toEqual('esm'); expect(trackedTransforms).toEqual(['dep.js', 'main.js', '\0dep.js?commonjs-proxy']); trackedTransforms.length = 0; expect(await getCodeFromBundle(bundle)).toBe(esCode); modules['dep.js'] = "exports.dep = 'cjs'; exports.dep += require('dep.js').dep;"; options.cache = bundle.cache; bundle = await rollup(options); expect(meta.isCommonJS).toBe('withRequireFunction'); expect((await executeBundle(bundle, avaAssertions)).exports).toEqual('cjscjs'); expect(trackedTransforms).toEqual(['dep.js', 'main.js', '\0dep.js?commonjs-exports']); trackedTransforms.length = 0; expect(await getCodeFromBundle(bundle)).toBe(wrappedCode); modules['dep.js'] = "exports.dep = 'cjs';"; options.cache = bundle.cache; bundle = await rollup(options); expect(meta.isCommonJS).toBe('withRequireFunction'); expect((await executeBundle(bundle, avaAssertions)).exports).toEqual('cjs'); expect(trackedTransforms).toEqual(['dep.js']); trackedTransforms.length = 0; expect(await getCodeFromBundle(bundle)).toBe(cjsCode); resetModules(); options.cache = bundle.cache; bundle = await rollup(options); expect(meta.isCommonJS).toBe(false); expect((await executeBundle(bundle, avaAssertions)).exports).toEqual('esm'); expect(trackedTransforms).toEqual(['dep.js', 'main.js', '\0dep.js?commonjs-proxy']); trackedTransforms.length = 0; expect(await getCodeFromBundle(bundle)).toBe(esCode); }); test('handles ESM cycles when using the cache', async () => { const modules = {}; const resetModules = () => { modules['main.js'] = "import 'dep.js';console.log('main');"; modules['dep.js'] = "import 'main.js';console.log('dep');"; }; const options = { input: 'main.js', plugins: [commonjs(), loader(modules)], onwarn }; resetModules(); let bundle = await rollup(options); options.cache = bundle.cache; bundle = await rollup(options); expect(await getCodeFromBundle(bundle)).toMatchSnapshot(); }); test('handles external dependencies when using the cache', async () => { const modules = {}; const resetModules = () => { modules['main.js'] = "import first from 'first.js';import second from 'second.js';export default first + second;"; modules['first.js'] = "export {first as default} from 'external';"; modules['second.js'] = "module.exports = require('external').second;"; }; const options = { input: 'main.js', external: ['external'], plugins: [commonjs(), loader(modules)], onwarn }; resetModules(); let bundle = await rollup(options); expect( ( await executeBundle(bundle, avaAssertions, { context: { require(id) { if (id === 'external') { return { first: 'first', second: 'second' }; } throw new Error(`Unexpected require "${id}"`); } } }) ).exports ).toBe('firstsecond'); const code = await getCodeFromBundle(bundle); expect(code).toMatchSnapshot(); options.cache = bundle.cache; bundle = await rollup(options); expect(await getCodeFromBundle(bundle)).toBe(code); }); test('Correctly processes meta data when using the cache but invalidating proxy modules', async () => { const modules = {}; const resetModules = () => { modules['main.js'] = "import first from 'first.js';export default first;"; modules['first.js'] = "import second from 'second.js';export default second;"; modules['second.js'] = 'module.exports = 42;'; }; const options = { input: 'main.js', external: ['external'], plugins: [ { name: 'test', shouldTransformCachedModule({ id }) { if (id.endsWith('?commonjs-es-import')) { return true; } return null; }, transform(code, id) { if (id.endsWith('?commonjs-es-import')) { return `${code}\n//${Date.now()}`; } return null; } }, commonjs(), loader(modules) ], onwarn }; resetModules(); let bundle = await rollup(options); expect((await executeBundle(bundle, avaAssertions)).exports).toBe(42); options.cache = bundle.cache; modules['main.js'] = "import first from 'first.js';export default first + 1;"; bundle = await rollup(options); expect((await executeBundle(bundle, avaAssertions)).exports).toBe(43); }); test('allows the config to be reused', async () => { const config = { preserveModules: true, plugins: [ commonjs({ requireReturnsDefault: true }), loader({ 'foo.js': "console.log('foo')", 'bar.js': "console.log('bar')" }) ] }; let bundle = await rollup({ input: 'foo.js', ...config }); expect(bundle.cache.modules.map(({ id }) => id)).toEqual(['foo.js']); bundle = await rollup({ input: 'bar.js', ...config }); expect(bundle.cache.modules.map(({ id }) => id)).toEqual(['bar.js']); }); test('keep the shebang at the top of the file content', async () => { const bundle = await rollup({ input: ['fixtures/samples/shebang/main.js'], plugins: [commonjs()] }); const { output } = await bundle.generate({ exports: 'auto', format: 'cjs', chunkFileNames: '[name].js' }); expect(output[0].code.startsWith('#!/usr/bin/env node\n')).toBe(true); }); test('handles bind when requireReturnsDefault is false', async () => { const bundle = await rollup({ input: 'fixtures/samples/bind/main.js', plugins: [commonjs()] }); const result = await executeBundle(bundle, avaAssertions); expect(result.error).toBe(undefined); expect(result.exports).toBe(42); });