Skip to content

Patches modify previous patches with nested objects #377

@jacklj

Description

@jacklj

Applying a series of patches can modify the patch before it, if the first patch is adding a nested object and the second is modifying it. cloneDiffValues: true doesn't help.

Minimal repro:

const { create } = await import("jsondiffpatch");

const jdp = create();

const createPatch = jdp.diff.bind(jdp);
const applyPatch = jdp.patch.bind(jdp);

const p1 = createPatch({}, { stages: [] }); // create stages array
const p2 = createPatch({stages: []}, { stages: [{ id: '2' }] }); // add item

console.log("p1", JSON.stringify(p1)); // {"stages":[[]]}
console.log("p2", JSON.stringify(p2)); // {"stages":{"0":[{"id":"2"}],"_t":"a"}}

let results = applyPatch({}, p1);
results = applyPatch(results, p2);

console.log("results", JSON.stringify(results)); // {"stages":[{"id":"2"}]}
console.log("p1", JSON.stringify(p1)); // {"stages":[[{"id":"2"}]]} // **it's changed!!**
console.log("p2", JSON.stringify(p2)); // {"stages":{"0":[{"id":"2"}],"_t":"a"}}

// now apply the two patches again to see the bug in the results object
let results2 = applyPatch({}, p1);
results2 = applyPatch(results2, p2);
console.log("results2", JSON.stringify(results2)); // { stages: [ { id: '2' }, { id: '2' } ] } // results has 2 items
console.log("p1", JSON.stringify(p1)); // {"stages":[[{"id":"2"},{"id":"2"}]]}  // now p1 has 2 items
console.log("p2", JSON.stringify(p2)); // {"stages":{"0":[{"id":"2"}],"_t":"a"}}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions