From 03121ffc76800b9f7aa3e72e6814d570caf68901 Mon Sep 17 00:00:00 2001 From: Will Soto Date: Sat, 14 Nov 2026 10:20:51 -0500 Subject: [PATCH] fix(core)!: deep merge in assign and stop get at scalars Closes #575 --- .changeset/deep-merge-assign.md | 7 ++++ core/README.md | 1 + core/src/store.ts | 56 ++++++++++++++++++++++++++++---- core/test/store.spec.ts | 57 +++++++++++++++++++++++++++++++++ docs/guide/usage.md | 1 + 5 files changed, 115 insertions(+), 7 deletions(-) create mode 100644 .changeset/deep-merge-assign.md diff --git a/.changeset/deep-merge-assign.md b/.changeset/deep-merge-assign.md new file mode 100644 index 00000000..a7c3a2c2 --- /dev/null +++ b/.changeset/deep-merge-assign.md @@ -0,0 +1,7 @@ +--- +"@willsoto/node-konfig-core": major +--- + +`Store#assign` now recursively merges plain objects instead of replacing them per top-level key. This affects every loader that writes through `assign`, notably `FileLoader`: a later file only needs to contain the nested properties it changes. Scalars, arrays and class instances are still replaced. If you relied on a later object replacing an earlier one wholesale, that no longer happens. + +`Store#get` and `Store#getOrThrow` no longer return an intermediate scalar when the path continues past it: `get("port.host")` is now `undefined` (and `getOrThrow` throws `NoValueForKeyError`) when `port` is not an object. diff --git a/core/README.md b/core/README.md index ea41772f..2a9ac38e 100644 --- a/core/README.md +++ b/core/README.md @@ -42,6 +42,7 @@ export const store = new Konfig.Store(); // so the loader knows how to interpret the file. // Files are loaded in order, so any conflicts will be resolved through a "last one wins" approach. // In this case, `local.json` will override properties that exist in both configurations. +// Nested objects are merged recursively, so `local.json` only needs to contain the properties it changes. const loader = new Konfig.FileLoader({ files: [ { diff --git a/core/src/store.ts b/core/src/store.ts index d46a40b7..c6b3aa04 100644 --- a/core/src/store.ts +++ b/core/src/store.ts @@ -110,6 +110,9 @@ export class Store> { current = current.get(key); } else if (typeof current === "object" && current !== null) { current = (current as Record)[key]; + } else { + // The path continues past a scalar (or null), so there is nothing to find. + current = undefined; } } @@ -218,22 +221,27 @@ export class Store> { /** * Given a config, will recursively merge all of its properties onto this instance's config. - * If a Group (ie `Store`) is encountered, it will correctly merge those properties onto that Group. + * Plain objects are merged key by key; anything else (scalars, arrays, class instances) replaces + * the existing value. If a Group (ie `Store`) is encountered, the properties are merged onto that Group. * * @param config - The config to merge with this instance's config * * @public */ assign(config: TConfig): this { - Object.keys(config).forEach((key) => { - const existingValue = (this.config as Record)[key]; + const current = this.config as Record; + + for (const [key, value] of Object.entries(config)) { + const existing = current[key]; - if (existingValue instanceof Store) { - existingValue.assign((config as Record)[key]); + if (existing instanceof Store) { + existing.assign(value as Record); + } else if (isPlainObject(existing) && isPlainObject(value)) { + current[key] = merge(existing, value); } else { - this.set(key, (config as Record)[key]); + this.set(key, value); } - }); + } return this; } @@ -327,3 +335,37 @@ export class Store> { return group; } } + +function isPlainObject(value: unknown): value is Record { + if (typeof value !== "object" || value === null) { + return false; + } + const prototype: unknown = Object.getPrototypeOf(value); + + return prototype === Object.prototype || prototype === null; +} + +/** + * Returns a new object rather than mutating `target`, since values in the store may be + * references to objects owned by the caller (eg the `values` given to a `ValueLoader`). + */ +function merge( + target: Record, + source: Record, +): Record { + const result = { ...target }; + + for (const [key, value] of Object.entries(source)) { + const existing = result[key]; + + if (existing instanceof Store) { + existing.assign(value as Record); + } else if (isPlainObject(existing) && isPlainObject(value)) { + result[key] = merge(existing, value); + } else { + result[key] = value; + } + } + + return result; +} diff --git a/core/test/store.spec.ts b/core/test/store.spec.ts index 314c6010..5e54c389 100644 --- a/core/test/store.spec.ts +++ b/core/test/store.spec.ts @@ -90,6 +90,18 @@ describe("Store", () => { expect(store.get("name")).toBe("baz"); }); + test("should return undefined when the path continues past a non-object value", () => { + const store = new Konfig.Store(); + + store.assign({ name: "my-app", port: 5432, nothing: null }); + + expect(store.get("name.length")).toBeUndefined(); + expect(store.get("name.x.y")).toBeUndefined(); + expect(store.get("port.host")).toBeUndefined(); + expect(store.get("nothing.host")).toBeUndefined(); + expect(() => store.getOrThrow("port.host")).toThrow(NoValueForKeyError); + }); + test("should assign values in bulk while retaining any existing groups", async () => { const store = new Konfig.Store(); @@ -148,6 +160,51 @@ describe("Store", () => { }); }); + test("should recursively merge plain objects when assigning", () => { + const store = new Konfig.Store(); + const first = { + name: "my-app", + database: { host: "localhost", port: 5432, replicas: ["a", "b"] }, + }; + + store.assign(first); + store.assign({ database: { host: "db.internal", replicas: ["c"], pool: { max: 10 } } }); + store.assign({ database: { pool: { min: 1 } } }); + + expect(store.toJSON()).toEqual({ + name: "my-app", + database: { + host: "db.internal", + port: 5432, + replicas: ["c"], + pool: { max: 10, min: 1 }, + }, + }); + // Callers keep ownership of what they pass in. + expect(first.database).toEqual({ host: "localhost", port: 5432, replicas: ["a", "b"] }); + }); + + test("should retain groups nested under a plain object when assigning", () => { + const store = new Konfig.Store(); + const group = store.group("services.database"); + + group.assign({ host: "localhost", port: 5432 }); + store.assign({ services: { database: { host: "rds" }, cache: { host: "redis" } } }); + + expect(store.group("services.database")).toBe(group); + expect(store.get("services.database")).toEqual({ host: "rds", port: 5432 }); + expect(store.get("services.cache.host")).toBe("redis"); + }); + + test("should replace rather than merge when either side is not a plain object", () => { + const store = new Konfig.Store(); + + store.assign({ database: { host: "localhost" }, cache: "redis://localhost" }); + store.assign({ database: null, cache: { host: "localhost" } }); + + expect(store.toJSON()).toEqual({ database: null, cache: { host: "localhost" } }); + }); + describe("getOrThrow", () => { test("should raise an error if the retrieved value is null", async () => { const store = new Konfig.Store(); diff --git a/docs/guide/usage.md b/docs/guide/usage.md index 08a5224d..b22cb5b4 100755 --- a/docs/guide/usage.md +++ b/docs/guide/usage.md @@ -44,6 +44,7 @@ const parser = new Konfig.JSONParser(); // so the loader knows how to interpret the file. // Files are loaded in order, so any conflicts will be resolved through a "last one wins" approach. // In this case, `local.json` will override properties that exist in both configurations. +// Nested objects are merged recursively, so `local.json` only needs to contain the properties it changes. const loader = new Konfig.FileLoader({ files: [ {