Skip to content

CJS require() of failing ESM produces uninitialized exports on import() #27287

@kevgeoleo

Description

@kevgeoleo

What version of Bun is running?

1.3.9+cf6cdbbba

What platform is your computer?

Microsoft Windows NT 10.0.26200.0 x64

What steps can reproduce the bug?

Hi,
Below is the PoC for reproduction:

  1. Create 2 files
// bad-esm.mjs
throw globalThis.err;
export const foo = 2;
// entry.cjs
'use strict';
const assert = require('node:assert');
globalThis.err = new Error;
assert.throws(() => require('./bad-esm.mjs'), globalThis.err);
assert.rejects(import('./bad-esm.mjs').then(console.log), globalThis.err);
console.log('bar')
  1. Run the command bun run entry.cjs

What is the expected behavior?

As in the case of NodeJS 24.13.1 (Latest LTE)

bar

What do you see instead?

Calling require() on a file with a top level throw/error makes all future import(esm) of the same file fail silently and return garbage.
ReferenceError gets thrown inside Assertion instead of globalThis.err

PS D:\secbench_test_windows\50_repro\node_\58945> bun run .\entry.cjs
bar
AssertionError: Expected values to be strictly deep-equal:
+ actual - expected

  Comparison {
+   message: "Cannot access 'foo' before initialization.",
+   name: 'ReferenceError'
-   message: '',
-   name: 'Error'
  }

 generatedMessage: true,
   operator: "rejects",
       code: "ERR_ASSERTION"

      at compareExceptionKey (node:assert:288:35)
      at expectedException (node:assert:339:28)
      at expectsError (node:assert:449:20)
      at rejects (node:assert:487:15)
      at processTicksAndRejections (native:7:39)

ReferenceError: Cannot access 'foo' before initialization.

1 | 'use strict';
2 | const assert = require('node:assert');
3 | globalThis.err = new Error;
                         ^
Error:
      at <anonymous> (D:\secbench_test_windows\50_repro\node_\58945\entry2.cjs:3:22)

Bun v1.3.9 (Windows x64)

Additional information

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions