Skip to content
Myr

fix: produce no longer accepts non draftable objects, fixes #596

Before adoption: this commit came in with the history the project adopted, so no landing records it.

BREAKING CHANGE: `produce` no longer accepts any base state to operate on that is not draftable, something which caused quite some confusion in the past. If you were using `produce` in a way where it might be invoked on non draftable data, you need to guard it with `isDraftable` from now before invoking the producer.

authored by Michel Weststrate · committed by Michel Weststrate · parent 7c52011 · Browse files · 10 files+70 added−84 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

10 files+70 added−84 removed

  • tests:+47 added−66 removed
  • other:+23 added−18 removed

10 files+70 added−84 removed

modified:__tests__/base.js+10 added-30 removed
3 unmodified lines
4 nothing,5 original,6 isDraft,7 immerable,8 enableAllPlugins8 enableAllPlugins,9 isDraftable10} from "../src/immer"11import {each, shallowCopy, DRAFT_STATE} from "../src/internal"12import deepFreeze from "deep-freeze"13import cloneDeep from "lodash.clonedeep"
945 unmodified lines
959 set(val) {960 this.bar = val961 }962 })963 proto[immerable] = true964 const baseState = Object.create(proto)965 produce(baseState, s => {966 expect(s.bar).toBeUndefined()967 s.foo = {}
446 unmodified lines
1414 it("'this' should not be bound anymore - 2", () => {1415 const incrementor = produce(function() {1416 expect(this).toBe(undefined)1417 })1416 incrementor()1418 incrementor({})1419 })14201421 it("should be possible to use dynamic bound this", () => {1422 const world = {
363 unmodified lines
1786 expect(nextState).not.toBe(baseState)1787 })17881789 it("cannot produce undefined by returning undefined", () => {1788 const base = 31789 expect(produce(base, () => 4)).toBe(4)1790 expect(produce(base, () => null)).toBe(null)1791 expect(produce(base, () => undefined)).toBe(3)1792 expect(produce(base, () => {})).toBe(3)1793 expect(produce(base, () => nothing)).toBe(undefined)17941790 expect(produce({}, () => undefined)).toEqual({})1791 expect(produce({}, () => nothing)).toBe(undefined)1797 expect(produce(3, () => nothing)).toBe(undefined)17921793 expect(produce(() => undefined)({})).toEqual({})1794 expect(produce(() => nothing)({})).toBe(undefined)1801 expect(produce(() => nothing)(3)).toBe(undefined)1795 expect(produce(() => nothing, {})(undefined)).toEqual(undefined)1796 })17971798 describe("base state type", () => {1799 if (!global.USES_BUILD) testObjectTypes(produce)
151 unmodified lines
1951 expect(isDraft(state.a)).toBeFalsy()1952 })1953 })1954 it("returns false for objects returned by the producer", () => {1961 const object = produce(null, Object.create)1955 const object = produce([], () => Object.create(null))1956 expect(isDraft(object)).toBeFalsy()1957 })1958 it("returns false for arrays returned by the producer", () => {1965 const array = produce(null, _ => [])1959 const array = produce({}, _ => [])1960 expect(isDraft(array)).toBeFalsy()1961 })1962 it("returns false for object drafts returned by the producer", () => {1963 const object = produce({}, state => state)
153 unmodified lines
2117 describe(name, () => {2118 const value = values[name]21192120 it("does not create a draft", () => {2127 produce(value, draft => {2128 expect(draft).toBe(value)2129 })2121 expect(() => produce(value, () => {})).toThrow(2122 /produce can only be called on things that are draftable/2123 )2124 })21312132 it("returns the base state when no changes are made", () => {2133 expect(produce(value, () => {})).toBe(value)2134 })21352136 if (value && typeof value == "object") {2137 it("does not return a copy when changes are made", () => {2138 expect(2139 produce(value, draft => {2140 draft.foo = true2141 })2142 ).toBe(value)2143 })2144 }2125 })2126 }2127}2128
14 unmodified lines
modified:__tests__/curry.js+3 added-3 removed
modified:__tests__/draft.ts+1 added-10 removed
11 unmodified lines
12const toDraft: <T>(value: T) => Draft<T> = x => x as any13const fromDraft: <T>(draft: Draft<T>) => T = x => x as any1415test("draft.ts", () => {16 // DraftArray<T>17 {18 // NOTE: As of 3.2.2, everything fails without "extends any"19 ;<Value extends any>(val: ReadonlyArray<Value>) => {20 val = _ as Draft<typeof val>21 let elem: Value = _ as Draft<Value>22 }23 }2416 // Tuple17 {18 let val: [1, 2] = _19 assert(toDraft(val), val)
272 unmodified lines
292 {293 // NOTE: "extends any" only helps a little.294 const $ = <T extends any>(val: ReadonlyArray<T>) => {295 let draft: Draft<typeof val> = _305 val = assert(toDraft(val), draft)296 assert(toDraft(val), draft)297 // $ExpectError: [ts] Argument of type 'DraftArray<T>' is not assignable to parameter of type 'Draft<T>'. [2345]298 // assert(fromDraft(draft), draft)299 }300 }
35 unmodified lines
modified:__tests__/frozen.js-8 removed
118 unmodified lines
119 expect(next).toBe(base)120 expect(isFrozen(next)).toBeTruthy()121 expect(isFrozen(next.a)).toBeTruthy()122 })123124 it("a new object replaces a primitive base", () => {125 const obj = {a: {}}126 const next = produce(null, () => obj)127 expect(next).toBe(obj)128 expect(isFrozen(next)).toBeTruthy()129 expect(isFrozen(next.a)).toBeTruthy()130 })123 })124125 it("can handle already frozen trees", () => {126 const a = []
90 unmodified lines
modified:__tests__/null.js+5 added-2 removed
modified:__tests__/patch.js+1 added-1 removed
757 unmodified lines
758 )759})760761describe("simple replacement", () => {762 runPatchTest({x: 3}, _d => 4, [{op: "replace", path: [], value: 4}])762 runPatchTest({x: 3}, _d => [], [{op: "replace", path: [], value: []}])763})764765describe("same value replacement - 1", () => {766 runPatchTest(
284 unmodified lines
modified:__tests__/produce.ts+27 added-12 removed
76 unmodified lines
77 let foo = produce((_: Draft<State>) => {})78 assert(foo, _ as Recipe)79})8081it("does not allow recipes for primitives", () => {82 let foo = produce((x: number) => {})83 if (false) {84 // @ts-expect-error85 foo(3)86 }87})8889it("does not allow recipes for primitives - 2", () => {90 let foo = produce((x: number) => {})91 if (false) {92 // @ts-expect-error93 foo(3)94 }95})9697it("can infer state type from recipe function with arguments", () => {98 type State = {readonly a: string} | {readonly b: string}99 type Recipe = <S extends State>(state: S, x: number) => S100
8 unmodified lines
109 let foo = produce((draft: Draft<State>, x: number) => {}, _ as State)110 assert(foo, _ as Recipe)111})11297it("cannot infer state type when the function type and default state are missing", () => {98 type Recipe = <S extends any>(state: S) => S99 const foo = produce((_: any) => {})100 assert(foo, _ as Recipe)113it("won't accept non draftables", () => {114 if (false) {115 // @ts-expect-error116 produce(3, () => {})117 }118})119120it("can update readonly state via curried api", () => {121 const newState = produce((draft: Draft<State>) => {
50 unmodified lines
172 {173 type Recipe = <S extends State>(state: S, a: number, b: number) => S174 let foo = produce((s: State, a: number, b: number) => {})175 assert(foo, _ as Recipe)159 foo(_ as State, 1, 2)176 foo({} as State, 1, 2)177 }178179 // Using argument parameters:180 {181 type Recipe = <S extends State>(state: S, ...rest: number[]) => S182 let woo = produce((state: Draft<State>, ...args: number[]) => {})183 assert(woo, _ as Recipe)167 woo(_ as State, 1, 2)184 woo({} as State, 1, 2)185 }186187 // With initial state:188 {
3 unmodified lines
192 ) => S193 let bar = produce((state: Draft<State>, ...args: number[]) => {},194 _ as State)195 assert(bar, _ as Recipe)179 bar(_ as State, 1, 2)180 bar(_ as State)181 bar()196 bar({} as State, 1, 2)197 bar({} as State)198 }199200 // When args is a tuple:201 {
7 unmodified lines
209 _ as State210 )211 assert(tup, _ as Recipe)212 tup({a: 1}, "", 2)197 tup(undefined, "", 2)213 }214 })215216 it("can be passed a readonly array", () => {
18 unmodified lines
235 })236})237238it("works with return type of: number", () => {224 let base = _ as {a: number}239 let base = {} as {a: number}240 let result = produce(base, () => 1)241 assert(result, _ as number)242})243
43 unmodified lines
287 assert(result2, _ as typeof base | undefined)288})289290it("can return the draft itself", () => {276 let base = _ as {readonly a: number}291 let base = {} as {readonly a: number}292 let result = produce(base, draft => draft)293294 // Currently, the `readonly` modifier is lost.295 assert(result, _ as {a: number})
198 unmodified lines
modified:src/core/immerClass.ts+2 added-7 removed
113 unmodified lines
114 )115 }116 usePatchesInScope(scope, patchListener)117 return processResult(result, scope)118 } else {119 result = recipe(base)120 if (result === NOTHING) return undefined121 if (result === undefined) result = base122 if (this.autoFreeze_) freeze(result, true)123 return result118 }119 die(21, base)120 }121122 produceWithPatches(arg1: any, arg2?: any, arg3?: any): any {123 if (typeof arg1 === "function") {
21 unmodified lines
145 finishDraft<D extends Draft<any>>(146 draft: D,147 patchListener?: PatchListener148 ): D extends Draft<infer T> ? T : never {154 const state: ImmerState = draft && draft[DRAFT_STATE]149 const state: ImmerState = draft && (draft as any)[DRAFT_STATE]150 if (__DEV__) {151 if (!state || !state.isManual_) die(9)152 if (state.finalized_) die(10)153 }
77 unmodified lines
modified:src/types/types-external.ts+16 added-7 removed
1import {Nothing} from "../internal"1import {Nothing, DRAFTABLE} from "../internal"23type Tail<T extends any[]> = ((...t: T) => any) extends (4 _: any,5 ...tail: infer TT
41 unmodified lines
47 : T extends object48 ? {readonly [K in keyof T]: Immutable<T[K]>}49 : T5051export type Draftable =52 | {readonly [K in keyof any]: any}53 | ReadonlyMap<any, any>54 | ReadonlySet<any>55 | ReadonlyArray<any>56 | {57 [DRAFTABLE]: true58 }5960export interface Patch {61 op: "replace" | "remove" | "add"62 path: (string | number)[]63 value?: any
34 unmodified lines
98 /** Curried producer */99 <100 Recipe extends (...args: any[]) => any,101 Params extends any[] = Parameters<Recipe>,93 T = Params[0]102 T = Params[0] extends object ? Params[0] : never103 >(104 recipe: Recipe105 ): <Base extends Immutable<T>>(106 base: Base,
6 unmodified lines
113 /** Curried producer with initial state */114 <115 Recipe extends (...args: any[]) => any,116 Params extends any[] = Parameters<Recipe>,108 T = Params[0]117 T = Params[0] extends object ? Params[0] : never118 >(119 recipe: Recipe,120 initialState: Immutable<T>121 ): <Base extends Immutable<T>>(
1 unmodified line
123 ...rest: Tail<Params>124 ) => Produced<Base, ReturnType<Recipe>>125126 /** Normal producer */118 <Base, D = Draft<Base>, Return = void>(127 <Base extends Draftable, D = Draft<Base>, Return = void>(128 base: Base,129 recipe: (draft: D) => Return,130 listener?: PatchListener131 ): Produced<Base, Return>
9 unmodified lines
141 /** Curried producer */142 <143 Recipe extends (...args: any[]) => any,144 Params extends any[] = Parameters<Recipe>,136 T = Params[0]145 T = Params[0] extends object ? Params[0] : never146 >(147 recipe: Recipe148 ): <Base extends Immutable<T>>(149 base: Base,
6 unmodified lines
156 /** Curried producer with initial state */157 <158 Recipe extends (...args: any[]) => any,159 Params extends any[] = Parameters<Recipe>,151 T = Params[0]160 T = Params[0] extends object ? Params[0] : never161 >(162 recipe: Recipe,163 initialState: Immutable<T>164 ): <Base extends Immutable<T>>(
1 unmodified line
166 ...rest: Tail<Params>167 ) => [Produced<Base, ReturnType<Recipe>>, Patch[], Patch[]]168169 /** Normal producer */161 <Base, D = Draft<Base>, Return = void>(170 <Base extends Draftable, D = Draft<Base>, Return = void>(171 base: Base,172 recipe: (draft: D) => Return173 ): [Produced<Base, Return>, Patch[], Patch[]]174}
4 unmodified lines
modified:src/utils/errors.ts+5 added-4 removed
27 unmodified lines
28 },29 18(plugin: string) {30 return `The plugin for '${plugin}' has not been loaded into Immer. To enable the plugin, import and call \`enable${plugin}()\` when initializing your application.`31 },32 19(plugin: string) {33 return "plugin not loaded: " + plugin34 },35 20: "Cannot use proxies if Proxy, Proxy.revocable or Reflect are not available"32 19: "plugin not loaded",33 20: "Cannot use proxies if Proxy, Proxy.revocable or Reflect are not available",34 21(thing: string) {35 return `produce can only be called on things that are draftable: plain objects, arrays, Map, Set or classes that are marked with '[immerable]: true'. Got '${thing}'`36 }37} as const3839export function die(error: keyof typeof errors, ...args: any[]): never {40 if (__DEV__) {
14 unmodified lines