From 4da2e0d5af3c155ba26af1364a7095366adff6ba Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20Burzy=C5=84ski?= Date: Sat, 27 Apr 2024 22:05:41 +0200 Subject: [PATCH] fix: Make `applyPatches` to accept `readonly Patch[]` (#1094) * Demonstrate possible regression * Make `Patch[]` arrays `readonly` on the outer bounds * Limit the change to `applyPatches` --------- Co-authored-by: Minh Nguyen <2852660+NMinhNguyen@users.noreply.github.com> --- __tests__/produce.ts | 17 ++++++++++++++++- src/core/immerClass.ts | 2 +- src/plugins/patches.ts | 2 +- src/utils/plugins.ts | 2 +- 4 files changed, 19 insertions(+), 4 deletions(-) diff --git a/__tests__/produce.ts b/__tests__/produce.ts index 22f0a318..f9093688 100644 --- a/__tests__/produce.ts +++ b/__tests__/produce.ts @@ -8,7 +8,8 @@ import { Immutable, Immer, enableMapSet, - enablePatches + enablePatches, + produceWithPatches } from "../src/immer" enableMapSet() @@ -162,6 +163,20 @@ it("can apply patches", () => { expect(applyPatches({}, patches)).toEqual({x: 4}) }) +it("can apply readonly patches", () => { + const [, patches]: readonly [ + { + x: number + }, + readonly Patch[], + readonly Patch[] + ] = produceWithPatches({x: 3}, d => { + d.x++ + }) + + expect(applyPatches({}, patches)).toEqual({x: 4}) +}) + describe("curried producer", () => { it("supports rest parameters", () => { type State = {readonly a: 1} diff --git a/src/core/immerClass.ts b/src/core/immerClass.ts index 763ed621..f827361c 100644 --- a/src/core/immerClass.ts +++ b/src/core/immerClass.ts @@ -172,7 +172,7 @@ export class Immer implements ProducersFns { this.useStrictShallowCopy_ = value } - applyPatches(base: T, patches: Patch[]): T { + applyPatches(base: T, patches: readonly Patch[]): T { // If a patch replaces the entire state, take that replacement as base // before applying patches let i: number diff --git a/src/plugins/patches.ts b/src/plugins/patches.ts index e82e9996..934e0b96 100644 --- a/src/plugins/patches.ts +++ b/src/plugins/patches.ts @@ -211,7 +211,7 @@ export function enablePatches() { }) } - function applyPatches_(draft: T, patches: Patch[]): T { + function applyPatches_(draft: T, patches: readonly Patch[]): T { patches.forEach(patch => { const {path, op} = patch diff --git a/src/utils/plugins.ts b/src/utils/plugins.ts index 36cc1d70..fede08f5 100644 --- a/src/utils/plugins.ts +++ b/src/utils/plugins.ts @@ -24,7 +24,7 @@ const plugins: { patches: Patch[], inversePatches: Patch[] ): void - applyPatches_(draft: T, patches: Patch[]): T + applyPatches_(draft: T, patches: readonly Patch[]): T } MapSet?: { proxyMap_(target: T, parent?: ImmerState): T