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
Provenance
- Commit
d9bf68b- Tree
f078596- Author
Michel Weststrate <mweststrate@fb.com>- Committer
Michel Weststrate <mweststrate@fb.com>- Parent
7c52011
10 files changed+70 added−84 removed
modified:__tests__/base.js+10 added-30 removed
3 unmodified lines4 nothing,5 original,6 isDraft,7 immerable,8- enableAllPlugins8+ enableAllPlugins,9+ isDraftable10 } from "../src/immer"11 import {each, shallowCopy, DRAFT_STATE} from "../src/internal"12 import deepFreeze from "deep-freeze"13 import cloneDeep from "lodash.clonedeep"945 unmodified lines959 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 lines1414 it("'this' should not be bound anymore - 2", () => {1415 const incrementor = produce(function() {1416 expect(this).toBe(undefined)1417 })1416- incrementor()1418+ incrementor({})1419 })1420 1421 it("should be possible to use dynamic bound this", () => {1422 const world = {363 unmodified lines1786 expect(nextState).not.toBe(baseState)1787 })1788 1789 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)1794-1790 expect(produce({}, () => undefined)).toEqual({})1791 expect(produce({}, () => nothing)).toBe(undefined)1797- expect(produce(3, () => nothing)).toBe(undefined)1792 1793 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 })1797 1798 describe("base state type", () => {1799 if (!global.USES_BUILD) testObjectTypes(produce)151 unmodified lines1951 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 lines2117 describe(name, () => {2118 const value = values[name]2119 2120 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 })2131-2132- it("returns the base state when no changes are made", () => {2133- expect(produce(value, () => {})).toBe(value)2134- })2135-2136- 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 linesmodified:__tests__/curry.js+3 added-3 removed
34 unmodified lines3536373839394041424344454645464748495054 unmodified lines34 unmodified lines })
it("should support returning new states from curring", () => { const reducer = produce((item, index) => { if (!item) { if (!item.x) { return {hello: "world"} } item.index = index })
expect(reducer(undefined, 3)).toEqual({hello: "world"}) expect(reducer({}, 3)).toEqual({index: 3}) expect(reducer({}, 3)).toEqual({hello: "world"}) expect(reducer({x: true}, 3)).toEqual({x: true, index: 3}) })
it("should support passing an initial state as second argument", () => { const reducer = produce(54 unmodified linesmodified:__tests__/draft.ts+1 added-10 removed
11 unmodified lines12 const toDraft: <T>(value: T) => Draft<T> = x => x as any13 const fromDraft: <T>(draft: Draft<T>) => T = x => x as any14 15 test("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- }24-16 // Tuple17 {18 let val: [1, 2] = _19 assert(toDraft(val), val)272 unmodified lines292 {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 linesmodified:__tests__/frozen.js-8 removed
118 unmodified lines119 expect(next).toBe(base)120 expect(isFrozen(next)).toBeTruthy()121 expect(isFrozen(next.a)).toBeTruthy()122 })123-124- 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 })124 125 it("can handle already frozen trees", () => {126 const a = []90 unmodified linesmodified:__tests__/null.js+5 added-2 removed
3 unmodified lines4567898910111213143 unmodified linesdescribe("null functionality", () => { const baseState = null
it("should return the original without modifications", () => { const nextState = produce(baseState, () => {}) expect(nextState).toBe(baseState) expect(() => produce(baseState, () => {}) ).toThrowErrorMatchingInlineSnapshot( `"[Immer] produce can only be called on things that are draftable: plain objects, arrays, Map, Set or classes that are marked with '[immerable]: true'. Got 'null'"` ) })})modified:__tests__/patch.js+1 added-1 removed
757 unmodified lines758 )759 })760 761 describe("simple replacement", () => {762- runPatchTest({x: 3}, _d => 4, [{op: "replace", path: [], value: 4}])762+ runPatchTest({x: 3}, _d => [], [{op: "replace", path: [], value: []}])763 })764 765 describe("same value replacement - 1", () => {766 runPatchTest(284 unmodified linesmodified:__tests__/produce.ts+27 added-12 removed
76 unmodified lines77 let foo = produce((_: Draft<State>) => {})78 assert(foo, _ as Recipe)79 })80 81+it("does not allow recipes for primitives", () => {82+ let foo = produce((x: number) => {})83+ if (false) {84+ // @ts-expect-error85+ foo(3)86+ }87+})88+89+it("does not allow recipes for primitives - 2", () => {90+ let foo = produce((x: number) => {})91+ if (false) {92+ // @ts-expect-error93+ foo(3)94+ }95+})96+97 it("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 lines109 let foo = produce((draft: Draft<State>, x: number) => {}, _ as State)110 assert(foo, _ as Recipe)111 })112 97-it("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)113+it("won't accept non draftables", () => {114+ if (false) {115+ // @ts-expect-error116+ produce(3, () => {})117+ }118 })119 120 it("can update readonly state via curried api", () => {121 const newState = produce((draft: Draft<State>) => {50 unmodified lines172 {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 }178 179 // 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 }186 187 // With initial state:188 {3 unmodified lines192 ) => 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 }199 200 // When args is a tuple:201 {7 unmodified lines209 _ as State210 )211 assert(tup, _ as Recipe)212 tup({a: 1}, "", 2)197- tup(undefined, "", 2)213 }214 })215 216 it("can be passed a readonly array", () => {18 unmodified lines235 })236 })237 238 it("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 lines287 assert(result2, _ as typeof base | undefined)288 })289 290 it("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)293 294 // Currently, the `readonly` modifier is lost.295 assert(result, _ as {a: number})198 unmodified linesmodified:src/core/immerClass.ts+2 added-7 removed
113 unmodified lines114 )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 }121 122 produceWithPatches(arg1: any, arg2?: any, arg3?: any): any {123 if (typeof arg1 === "function") {21 unmodified lines145 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 linesmodified:src/types/types-external.ts+16 added-7 removed
1-import {Nothing} from "../internal"1+import {Nothing, DRAFTABLE} from "../internal"2 3 type Tail<T extends any[]> = ((...t: T) => any) extends (4 _: any,5 ...tail: infer TT41 unmodified lines47 : T extends object48 ? {readonly [K in keyof T]: Immutable<T[K]>}49 : T50 51+export type Draftable =52+ | {readonly [K in keyof any]: any}53+ | ReadonlyMap<any, any>54+ | ReadonlySet<any>55+ | ReadonlyArray<any>56+ | {57+ [DRAFTABLE]: true58+ }59+60 export interface Patch {61 op: "replace" | "remove" | "add"62 path: (string | number)[]63 value?: any34 unmodified lines98 /** 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 lines113 /** 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 line123 ...rest: Tail<Params>124 ) => Produced<Base, ReturnType<Recipe>>125 126 /** 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 lines141 /** 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 lines156 /** 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 line166 ...rest: Tail<Params>167 ) => [Produced<Base, ReturnType<Recipe>>, Patch[], Patch[]]168 169 /** 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 linesmodified:src/utils/errors.ts+5 added-4 removed
27 unmodified lines28 },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 const38 39 export function die(error: keyof typeof errors, ...args: any[]): never {40 if (__DEV__) {14 unmodified lines