Skip to content

[Bug]: @babel/types valueToNode throws error on plain object from different context #13263

@lukebro

Description

@lukebro

💻

  • Would you like to work on a fix?

How are you using Babel?

Programmatic API (babel.transform, babel.parse)

Input code

const vm = require('vm');
const t = require('@babel/types');

const e = {};
const context = { module: { exports: e }, exports: e };

const script = new vm.Script(`module.exports = { hello: 'world' };`);

script.runInContext(vm.createContext(context));

try {
  t.valueToNode(context.module.exports);
} catch (e) {
  // error is thrown
  // "don't know how to turn this value into a node"
  console.log(e);
}

Configuration file name

No response

Configuration

None needed.

Current and expected behavior

Currently it throws an error because isPlainObject returns false. This started after lodash/isPlainObject was replaced with an local version in an effort to drop lodash as a dependency.

The current version checks the prototype reference equality but the object is coming from a different context (and hence a different Object.prototype).

The expected behavior is for it to correctly convert the plain object to a node without erroring.

Environment

System:
OS: Linux 5.4 Debian GNU/Linux 10 (buster) 10 (buster)
Binaries:
Node: 10.24.1 - /usr/local/bin/node
Yarn: 1.22.10 - /usr/local/bin/yarn
npm: 6.14.12 - /usr/local/bin/npm
npmPackages:
@babel/types: 7.14.1 => 7.14.1

Possible solution

Update isPlainObject method to mirror the previous functionality of lodash/isPlainObject.

OR

Document this breaking change.

Additional context

Here is a codesandbox with the fully reproducible result as well as showing the difference between old/new isPlainObject: https://codesandbox.io/s/valuetonode-bug-report-xnirg

I can't think of any other scenarios besides this one where this can happen.

Metadata

Metadata

Labels

i: regressionoutdatedA closed issue/PR that is archived due to age. Recommended to make a new issuepkg: types

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions