Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support objects from other contexts in t.valueToNode #13275

Merged
merged 3 commits into from May 7, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
11 changes: 9 additions & 2 deletions packages/babel-types/src/converters/valueToNode.ts
Expand Up @@ -40,11 +40,18 @@ function isRegExp(value): value is RegExp {
}

function isPlainObject(value): value is object {
if (typeof value !== "object" || value === null) {
if (
typeof value !== "object" ||
value === null ||
Object.prototype.toString.call(value) !== "[object Object]"
) {
return false;
}
const proto = Object.getPrototypeOf(value);
return proto === null || proto === Object.prototype;
// Object.prototype's __proto__ is null. Every other class's __proto__.__proto__ is
// not null by default. We cannot check if proto === Object.prototype because it
// could come from another realm.
return proto === null || Object.getPrototypeOf(proto) === null;
}

function valueToNode(value: unknown): t.Expression {
Expand Down
20 changes: 20 additions & 0 deletions packages/babel-types/test/regressions.js
@@ -1,4 +1,5 @@
import * as t from "../lib";
import * as vm from "vm";

describe("regressions", () => {
const babel7 = process.env.BABEL_TYPES_8_BREAKING ? it.skip : it;
Expand All @@ -8,4 +9,23 @@ describe("regressions", () => {
t.file(t.program([]), [{ type: "Line" }]);
}).not.toThrow();
});

it(".valueToNode works with objects from different contexts", () => {
const context = {};
const script = new vm.Script(`this.obj = { foo: 2 }`);
script.runInNewContext(context);

expect(t.valueToNode(context.obj)).toMatchObject({
properties: [
{
computed: false,
key: { name: "foo", type: "Identifier" },
shorthand: false,
type: "ObjectProperty",
value: { type: "NumericLiteral", value: 2 },
},
],
type: "ObjectExpression",
});
});
});