Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
104 changes: 104 additions & 0 deletions lib/deep-merge.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
/*
The MIT License (MIT)

Copyright (c) 2014 Stefan Thomas

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import isPlainObj from 'is-plain-obj'

const own = {}.hasOwnProperty

/**
* Deeply merge plain objects and arrays.
*
* @template {Record<string, unknown> | Array<unknown>} Target
* @param {Target} target
* @param {unknown} source
* @returns {Target}
*/
export function deepMerge(target, source) {
Comment thread
fuma-nama marked this conversation as resolved.
Resolved
if (!source || typeof source !== 'object') {
return target
}

const values = /** @type {Record<string, unknown>} */ (source)

for (const key in values) {
// mainly to satisfy eslint, `getOwn()` also does the check
if (!Object.hasOwn(source, key)) continue
const value = getOwn(values, key)

if (value === undefined || value === target) {
continue
}

if (Array.isArray(value)) {
const existing = getOwn(target, key)
const base = Array.isArray(existing)
? /** @type {Array<unknown>} */ (existing)
: []

setOwn(target, key, deepMerge(base, value))
} else if (isPlainObj(value)) {
const existing = getOwn(target, key)
const base = isPlainObj(existing) ? existing : {}

setOwn(target, key, deepMerge(base, value))
} else {
setOwn(target, key, value)
}
}

return target
}

/**
* @param {Record<string, unknown> | Array<unknown>} target
* @param {string} key
* @returns {unknown}
*/
function getOwn(target, key) {
if (key === '__proto__' && !own.call(target, key)) {
return undefined
}

return /** @type {Record<string, unknown>} */ (target)[key]
}

/**
* @param {Record<string, unknown> | Array<unknown>} target
* @param {string} key
* @param {unknown} value
* @returns {undefined}
*/
function setOwn(target, key, value) {
if (key === '__proto__') {
Object.defineProperty(target, key, {
configurable: true,
enumerable: true,
value,
writable: true
})
} else {
const record = /** @type {Record<string, unknown>} */ (target)
record[key] = value
}
}
25 changes: 15 additions & 10 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -341,12 +341,12 @@
*/

import {bail} from 'bail'
import extend from 'extend'
import {ok as assert} from 'devlop'
import isPlainObj from 'is-plain-obj'
import {trough} from 'trough'
import {VFile} from 'vfile'
import {CallableInstance} from './callable-instance.js'
import {deepMerge} from './deep-merge.js'

// To do: next major: drop `Compiler`, `Parser`: prefer lowercase.

Expand Down Expand Up @@ -501,7 +501,7 @@ export class Processor extends CallableInstance {
destination.use(...attacher)
}

destination.data(extend(true, {}, this.namespace))
destination.data(deepMerge({}, this.namespace))

return destination
}
Expand Down Expand Up @@ -1109,7 +1109,12 @@ export class Processor extends CallableInstance {
addList(result.plugins)

if (result.settings) {
namespace.settings = extend(true, namespace.settings, result.settings)
namespace.settings = /** @type {Settings} */ (
deepMerge(
/** @type {Record<string, unknown>} */ (namespace.settings || {}),
result.settings
)
)
}
}

Expand Down Expand Up @@ -1157,7 +1162,7 @@ export class Processor extends CallableInstance {
let [primary, ...rest] = parameters
const currentPrimary = attachers[entryIndex][1]
if (isPlainObj(currentPrimary) && isPlainObj(primary)) {
primary = extend(true, currentPrimary, primary)
primary = deepMerge(currentPrimary, primary)
}

attachers[entryIndex] = [plugin, primary, ...rest]
Expand Down Expand Up @@ -1285,9 +1290,9 @@ function vfile(value) {
function looksLikeAVFile(value) {
return Boolean(
value &&
typeof value === 'object' &&
'message' in value &&
'messages' in value
typeof value === 'object' &&
'message' in value &&
'messages' in value
)
}

Expand All @@ -1310,8 +1315,8 @@ function looksLikeAValue(value) {
function isUint8Array(value) {
return Boolean(
value &&
typeof value === 'object' &&
'byteLength' in value &&
'byteOffset' in value
typeof value === 'object' &&
'byteLength' in value &&
'byteOffset' in value
)
}
2 changes: 0 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,12 @@
"@types/unist": "^3.0.0",
"bail": "^2.0.0",
"devlop": "^1.0.0",
"extend": "^3.0.0",
"is-plain-obj": "^4.0.0",
"trough": "^2.0.0",
"vfile": "^6.0.0"
},
"description": "parse, inspect, transform, and serialize content through syntax trees",
"devDependencies": {
"@types/extend": "^3.0.0",
"@types/hast": "^3.0.0",
"@types/mdast": "^4.0.0",
"@types/node": "^22.0.0",
Expand Down
3 changes: 3 additions & 0 deletions test/types.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@ declare module 'unified' {
bar?: boolean | undefined
foo?: boolean | undefined
qux?: boolean | undefined

date?: Date | undefined
nested?: Record<string, unknown> | undefined
}
}

Expand Down
79 changes: 79 additions & 0 deletions test/use.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import {unified} from 'unified'
import {deepMerge} from '../lib/deep-merge.js'

test('`use`', async function (t) {
const givenOptions = {alpha: 'bravo', charlie: true, delta: 1}
Expand Down Expand Up @@ -284,6 +285,84 @@ test('`use`', async function (t) {
.data(),
{settings: {foo: false, bar: true, qux: true}}
)

assert.deepEqual(
unified()
.use({
settings: {
date: new Date(),
nested: {
array: [],
array2: '',
obj: {},
map: new Map([['test', 'a']])
}
}
})
.use({
settings: {
date: undefined,
nested: {
array: ['test'],
array2: ['apple'],
obj: null,
map: new Map([['test', 'b']])
}
}
})
.data(),
{
settings: {
date: new Date(),
nested: {
array: ['test'],
array2: ['apple'],
obj: null,
map: new Map([['test', 'b']])
}
}
}
)
})

await t.test('should not merge inherited object properties', function () {
const settings = Object.create({alpha: true})
settings.bravo = true

assert.deepEqual(unified().use({settings}).data(), {
settings: {bravo: true}
})
})

await t.test(
'should keep object `__proto__` property in preset settings',
function () {
/** @type {import('unified').Settings} */
const settings = {}

Object.defineProperty(settings, '__proto__', {
enumerable: true,
value: {alpha: true}
})

const data = unified().use({settings}).data()
const descriptor = Object.getOwnPropertyDescriptor(
data.settings,
'__proto__'
)

assert(descriptor)
assert.equal(
Object.getPrototypeOf(data.settings),
Object.getPrototypeOf({})
)
assert.deepEqual(descriptor.value, {alpha: true})
}
)

// shouldn't happen in reality, just to ensure 100% test coverage
await t.test('should support non-object merge sources', function () {
assert.deepEqual(deepMerge({}, 'alpha'), {})
})

await t.test('should support extending presets', function () {
Expand Down
Loading