Skip to content

Commit

Permalink
[utils] Fix isPlainObject to work across realm (mui#39981)
Browse files Browse the repository at this point in the history
  • Loading branch information
brijeshb42 authored and mnajdova committed Jan 9, 2024
1 parent ca9996e commit baec1e1
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 1 deletion.
14 changes: 14 additions & 0 deletions packages/mui-utils/src/deepmerge.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { expect } from 'chai';
import { runInNewContext } from 'vm';
import deepmerge from './deepmerge';

describe('deepmerge', () => {
Expand All @@ -11,6 +12,19 @@ describe('deepmerge', () => {
expect({}).not.to.have.property('isAdmin');
});

it('should merge objects across realms', function test() {
if (!/jsdom/.test(window.navigator.userAgent)) {
// vm is only available in Node.js.
// We could use https://github.com/browserify/vm-browserify to run the test in an iframe when
// in Karma but it doesn't seem we need to go as far.
this.skip();
}

const vmObject = runInNewContext('({hello: "realm"})');
const result = deepmerge({ hello: 'original' }, vmObject);
expect(result.hello).to.equal('realm');
});

// https://github.com/mui/material-ui/issues/20095
it('should not merge HTML elements', () => {
const element = document.createElement('div');
Expand Down
14 changes: 13 additions & 1 deletion packages/mui-utils/src/deepmerge.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,17 @@
// https://github.com/sindresorhus/is-plain-obj/blob/main/index.js
export function isPlainObject(item: unknown): item is Record<keyof any, unknown> {
return item !== null && typeof item === 'object' && item.constructor === Object;
if (typeof item !== 'object' || item === null) {
return false;
}

const prototype = Object.getPrototypeOf(item);
return (
(prototype === null ||
prototype === Object.prototype ||
Object.getPrototypeOf(prototype) === null) &&
!(Symbol.toStringTag in item) &&
!(Symbol.iterator in item)
);
}

export interface DeepmergeOptions {
Expand Down
1 change: 1 addition & 0 deletions test/karma.conf.js
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,7 @@ module.exports = function setKarmaConfig(config) {
stream: false,
// required by enzyme > cheerio > parse5
util: require.resolve('util/'),
vm: false,
},
},
// TODO: 'browserslist:modern'
Expand Down

0 comments on commit baec1e1

Please sign in to comment.