Skip to content
Myr

Immer 7

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

* Introduced `current`, which takes a snapshot of the current state of a draft and finalizes it (but without freezing). Current is a great utility to print the current state during debugging (no Proxies in the way), and the output of current can also be safely leaked outside the producer. Implements #441, #591 * [BREAKING CHANGE] getters and setters are now handled consistently: own getters and setters will always by copied into fields (like Object.assign does), inherited getters and setters will be left as-is. This should allow using Immer directly on objects that trap their fields, like down in Vue or MobX. Fixes #584, #439, #593, #558 * [BREAKING CHANGE] produce no longer accepts non-draftable objects as first argument * [BREAKING CHANGE] original can only be called on drafts and will throw otherwise (fixes #605) * [BREAKING CHANGE] non-enumerable and symbolic fields will never be frozen * [BREAKING CHANGE] the patches for arrays are now computed differently to fix some scenarios in which they were incorrect. In some cases they will be more optimal now, in other cases less. Especially splicing / unshifting items into an existing array might result in a lot of patches. Fixes #468 * Improved documentation in several areas, there is now a page for typical update patterns and a separate page on how to work with classes. And additional performance tips have been included. Fixes #457, #115, #462 * Fixed #462: All branches of the produced state should be frozen * Fixed #588: Inconsistent behavior with nested produce * Fixed #577: Immer might not work with polyfilled symbols * Fixed #514, #609: Explicitly calling `useProxies(false)` shouldn’t check for the presence of Proxy.

authored by Michel Weststrate · committed by GitHub · parents 30b5b77, 7bb29d5 · Browse files · 39 files+1324 added−513 removed
This commit

State

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

Diff stats

39 files+1324 added−513 removed

  • tests:+708 added−140 removed
  • other:+616 added−373 removed

39 files+1324 added−513 removed

modified:__tests__/__snapshots__/base.js.snap-16 removed
20 unmodified lines
21exports[`base functionality - es5 (autofreeze) set drafts revokes sets 1`] = `"[Immer] Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? {}"`;2223exports[`base functionality - es5 (autofreeze) set drafts revokes sets 2`] = `"[Immer] Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? {}"`;2425exports[`base functionality - es5 (autofreeze) throws on computed properties 1`] = `"[Immer] Immer drafts cannot have computed properties"`;2625exports[`base functionality - es5 (autofreeze) throws when the draft is modified and another object is returned 1`] = `"[Immer] An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft."`;2627exports[`base functionality - es5 (autofreeze)(patch listener) async recipe function works with rejected promises 1`] = `"[Immer] Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? {\\"a\\":0,\\"b\\":1}"`;28
16 unmodified lines
45exports[`base functionality - es5 (autofreeze)(patch listener) set drafts revokes sets 1`] = `"[Immer] Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? {}"`;4647exports[`base functionality - es5 (autofreeze)(patch listener) set drafts revokes sets 2`] = `"[Immer] Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? {}"`;4851exports[`base functionality - es5 (autofreeze)(patch listener) throws on computed properties 1`] = `"[Immer] Immer drafts cannot have computed properties"`;5249exports[`base functionality - es5 (autofreeze)(patch listener) throws when the draft is modified and another object is returned 1`] = `"[Immer] An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft."`;5051exports[`base functionality - es5 (no freeze) async recipe function works with rejected promises 1`] = `"[Immer] Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? {\\"a\\":0,\\"b\\":1}"`;52
16 unmodified lines
69exports[`base functionality - es5 (no freeze) set drafts revokes sets 1`] = `"[Immer] Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? {}"`;7071exports[`base functionality - es5 (no freeze) set drafts revokes sets 2`] = `"[Immer] Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? {}"`;7277exports[`base functionality - es5 (no freeze) throws on computed properties 1`] = `"[Immer] Immer drafts cannot have computed properties"`;7873exports[`base functionality - es5 (no freeze) throws when the draft is modified and another object is returned 1`] = `"[Immer] An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft."`;7475exports[`base functionality - es5 (patch listener) async recipe function works with rejected promises 1`] = `"[Immer] Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? {\\"a\\":0,\\"b\\":1}"`;76
16 unmodified lines
93exports[`base functionality - es5 (patch listener) set drafts revokes sets 1`] = `"[Immer] Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? {}"`;9495exports[`base functionality - es5 (patch listener) set drafts revokes sets 2`] = `"[Immer] Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? {}"`;96103exports[`base functionality - es5 (patch listener) throws on computed properties 1`] = `"[Immer] Immer drafts cannot have computed properties"`;10497exports[`base functionality - es5 (patch listener) throws when the draft is modified and another object is returned 1`] = `"[Immer] An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft."`;9899exports[`base functionality - proxy (autofreeze) array drafts throws when a non-numeric property is added 1`] = `"[Immer] Immer only supports setting array indices and the 'length' property"`;100
28 unmodified lines
129exports[`base functionality - proxy (autofreeze) set drafts revokes sets 1`] = `"[Immer] Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? {}"`;130131exports[`base functionality - proxy (autofreeze) set drafts revokes sets 2`] = `"[Immer] Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? {}"`;132141exports[`base functionality - proxy (autofreeze) throws on computed properties 1`] = `"[Immer] Immer drafts cannot have computed properties"`;142133exports[`base functionality - proxy (autofreeze) throws when Object.defineProperty() is used on drafts 1`] = `"[Immer] Object.defineProperty() cannot be used on an Immer draft"`;134135exports[`base functionality - proxy (autofreeze) throws when Object.setPrototypeOf() is used on a draft 1`] = `"[Immer] Object.setPrototypeOf() cannot be used on an Immer draft"`;136
32 unmodified lines
169exports[`base functionality - proxy (autofreeze)(patch listener) set drafts revokes sets 1`] = `"[Immer] Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? {}"`;170171exports[`base functionality - proxy (autofreeze)(patch listener) set drafts revokes sets 2`] = `"[Immer] Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? {}"`;172183exports[`base functionality - proxy (autofreeze)(patch listener) throws on computed properties 1`] = `"[Immer] Immer drafts cannot have computed properties"`;184173exports[`base functionality - proxy (autofreeze)(patch listener) throws when Object.defineProperty() is used on drafts 1`] = `"[Immer] Object.defineProperty() cannot be used on an Immer draft"`;174175exports[`base functionality - proxy (autofreeze)(patch listener) throws when Object.setPrototypeOf() is used on a draft 1`] = `"[Immer] Object.setPrototypeOf() cannot be used on an Immer draft"`;176
32 unmodified lines
209exports[`base functionality - proxy (no freeze) set drafts revokes sets 1`] = `"[Immer] Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? {}"`;210211exports[`base functionality - proxy (no freeze) set drafts revokes sets 2`] = `"[Immer] Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? {}"`;212225exports[`base functionality - proxy (no freeze) throws on computed properties 1`] = `"[Immer] Immer drafts cannot have computed properties"`;226213exports[`base functionality - proxy (no freeze) throws when Object.defineProperty() is used on drafts 1`] = `"[Immer] Object.defineProperty() cannot be used on an Immer draft"`;214215exports[`base functionality - proxy (no freeze) throws when Object.setPrototypeOf() is used on a draft 1`] = `"[Immer] Object.setPrototypeOf() cannot be used on an Immer draft"`;216
32 unmodified lines
249exports[`base functionality - proxy (patch listener) set drafts revokes sets 1`] = `"[Immer] Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? {}"`;250251exports[`base functionality - proxy (patch listener) set drafts revokes sets 2`] = `"[Immer] Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? {}"`;252267exports[`base functionality - proxy (patch listener) throws on computed properties 1`] = `"[Immer] Immer drafts cannot have computed properties"`;268253exports[`base functionality - proxy (patch listener) throws when Object.defineProperty() is used on drafts 1`] = `"[Immer] Object.defineProperty() cannot be used on an Immer draft"`;254255exports[`base functionality - proxy (patch listener) throws when Object.setPrototypeOf() is used on a draft 1`] = `"[Immer] Object.setPrototypeOf() cannot be used on an Immer draft"`;256
377 unmodified lines
modified:__tests__/base.js+290 added-33 removed
931 unmodified lines
932 expect(nextState.foo).toBeTruthy()933 expect(isEnumerable(nextState, "foo")).toBeFalsy()934 })935936 it("throws on computed properties", () => {937 const baseState = {}938 Object.defineProperty(baseState, "foo", {939 get: () => {},940 enumerable: true936 it("can work with own computed props", () => {937 const baseState = {938 x: 1,939 get y() {940 return this.x941 },942 set y(v) {943 this.x = v944 }945 }946947 const nextState = produce(baseState, d => {948 expect(d.y).toBe(1)949 d.x = 2950 expect(d.x).toBe(2)951 expect(d.y).toBe(1) // this has been copied!952 d.y = 3953 expect(d.x).toBe(2)954 })942 expect(() => {943 produce(baseState, s => {944 // Proxies only throw once a change is made.945 if (useProxies) {946 s.modified = true947 }948 })949 }).toThrowErrorMatchingSnapshot()955 expect(baseState.x).toBe(1)956 expect(baseState.y).toBe(1)957958 expect(nextState.x).toBe(2)959 expect(nextState.y).toBe(3)960 if (!autoFreeze) {961 nextState.y = 4 // decoupled now!962 expect(nextState.y).toBe(4)963 expect(nextState.x).toBe(2)964 expect(Object.getOwnPropertyDescriptor(nextState, "y").value).toBe(4)965 }966 })967968 it("can work with class with computed props", () => {969 class State {970 [immerable] = true971972 x = 1973974 set y(v) {975 this.x = v976 }977978 get y() {979 return this.x980 }981 }982983 const baseState = new State()984985 const nextState = produce(baseState, d => {986 expect(d.y).toBe(1)987 d.y = 2988 expect(d.x).toBe(2)989 expect(d.y).toBe(2)990 expect(Object.getOwnPropertyDescriptor(d, "y")).toBeUndefined()991 })992 expect(baseState.x).toBe(1)993 expect(baseState.y).toBe(1)994995 expect(nextState.x).toBe(2)996 expect(nextState.y).toBe(2)997 expect(Object.getOwnPropertyDescriptor(nextState, "y")).toBeUndefined()998 })9991000 it("allows inherited computed properties", () => {1001 const proto = {}1002 Object.defineProperty(proto, "foo", {1003 get() {
2 unmodified lines
1006 set(val) {1007 this.bar = val1008 }1009 })1010 proto[immerable] = true1011 const baseState = Object.create(proto)1012 produce(baseState, s => {1013 expect(s.bar).toBeUndefined()1014 s.foo = {}
541 unmodified lines
1556 expect(next2).toBe(a)1557 })15581559 autoFreeze &&1511 test.skip("issue #462 - frozen", () => {1560 test("issue #462 - frozen", () => {1561 var origin = {1562 a: {1563 value: "no"1564 },1565 b: {1566 value: "no"1567 }1568 }1520 var im = produce(origin, origin => {1521 origin.a.value = "im"1569 const next = produce(origin, draft => {1570 draft.a.value = "im"1571 })1523 expect(() => (origin.b.value = "yes")).toThrow() // should throw!1524 // to prevent this...:1525 // expect(im.b.value).toBe('no');1572 expect(() => {1573 origin.b.value = "yes"1574 }).toThrowError(1575 "Cannot assign to read only property 'value' of object '#<Object>'"1576 )1577 expect(() => {1578 next.b.value = "yes"1579 }).toThrowError(1580 "Cannot assign to read only property 'value' of object '#<Object>'"1581 ) // should throw!1582 })15831584 autoFreeze &&1585 test("issue #469, state not frozen", () => {
253 unmodified lines
1839 // so we don't atm1840 expect(nextState).not.toBe(baseState)1841 })18421843 it("cannot always detect noop assignments - 4", () => {1844 const baseState = {}1845 const [nextState, patches] = produceWithPatches(baseState, d => {1846 d.x = 41847 delete d.x1848 })1849 expect(nextState).toEqual({})1850 expect(patches).toEqual([])1851 // This differs between ES5 and proxy, and ES5 does it better :(1852 if (useProxies) expect(nextState).not.toBe(baseState)1853 else expect(nextState).toBe(baseState)1854 })18551856 it("cannot produce undefined by returning undefined", () => {1857 const base = 31858 expect(produce(base, () => 4)).toBe(4)1859 expect(produce(base, () => null)).toBe(null)
166 unmodified lines
2026 expect(isDraft(state.a)).toBeFalsy()2027 })2028 })2029 it("returns false for objects returned by the producer", () => {1961 const object = produce(null, Object.create)2030 const object = produce([], () => Object.create(null))2031 expect(isDraft(object)).toBeFalsy()2032 })2033 it("returns false for arrays returned by the producer", () => {1965 const array = produce(null, _ => [])2034 const array = produce({}, _ => [])2035 expect(isDraft(array)).toBeFalsy()2036 })2037 it("returns false for object drafts returned by the producer", () => {2038 const object = produce({}, state => state)
65 unmodified lines
2104 expect(base.map.get("set2")).toBe(set2)2105 expect(patches.length).toBe(0)2106 })2107 })21082109 if (!autoFreeze) {2110 describe("#613", () => {2111 const x1 = {}2112 const y1 = produce(x1, draft => {2113 draft.foo = produce({bar: "baz"}, draft1 => {2114 draft1.bar = "baa"2115 })2116 draft.foo.bar = "a"2117 })2118 expect(y1.foo.bar).toBe("a")2119 })2120 }2121}21222123function testObjectTypes(produce) {2124 class Foo {
46 unmodified lines
2171 expect(result[0]).toBe(random)2172 })2173 })2174 }21752176 describe("class with getters", () => {2177 class State {2178 [immerable] = true2179 _bar = {baz: 1}2180 foo2181 get bar() {2182 return this._bar2183 }2184 syncFoo() {2185 const value = this.bar.baz2186 this.foo = value2187 this.bar.baz++2188 }2189 }2190 const state = new State()21912192 it("should use a method to assing a field using a getter that return a non primitive object", () => {2193 const newState = produce(state, draft => {2194 draft.syncFoo()2195 })2196 expect(newState.foo).toEqual(1)2197 expect(newState.bar).toEqual({baz: 2})2198 expect(state.bar).toEqual({baz: 1})2199 })2200 })22012202 describe("super class with getters", () => {2203 class BaseState {2204 [immerable] = true2205 _bar = {baz: 1}2206 foo2207 get bar() {2208 return this._bar2209 }2210 syncFoo() {2211 const value = this.bar.baz2212 this.foo = value2213 this.bar.baz++2214 }2215 }22162217 class State extends BaseState {}22182219 const state = new State()22202221 it("should use a method to assing a field using a getter that return a non primitive object", () => {2222 const newState = produce(state, draft => {2223 draft.syncFoo()2224 })2225 expect(newState.foo).toEqual(1)2226 expect(newState.bar).toEqual({baz: 2})2227 expect(state.bar).toEqual({baz: 1})2228 })2229 })22302231 describe("class with setters", () => {2232 class State {2233 [immerable] = true2234 _bar = 02235 get bar() {2236 return this._bar2237 }2238 set bar(x) {2239 this._bar = x2240 }2241 }2242 const state = new State()22432244 it("should define a field with a setter", () => {2245 const newState3 = produce(state, d => {2246 d.bar = 12247 expect(d._bar).toEqual(1)2248 })2249 expect(newState3._bar).toEqual(1)2250 expect(newState3.bar).toEqual(1)2251 expect(state._bar).toEqual(0)2252 expect(state.bar).toEqual(0)2253 })2254 })22552256 describe("setter only", () => {2257 let setterCalled = 02258 class State {2259 [immerable] = true2260 x = 02261 set y(value) {2262 setterCalled++2263 this.x = value2264 }2265 }22662267 const state = new State()2268 const next = produce(state, draft => {2269 expect(draft.y).toBeUndefined()2270 draft.y = 2 // setter is inherited, so works2271 expect(draft.x).toBe(2)2272 })2273 expect(setterCalled).toBe(1)2274 expect(next.x).toBe(2)2275 expect(state.x).toBe(0)2276 })22772278 describe("getter only", () => {2279 let getterCalled = 02280 class State {2281 [immerable] = true2282 x = 02283 get y() {2284 getterCalled++2285 return this.x2286 }2287 }22882289 const state = new State()2290 const next = produce(state, draft => {2291 expect(draft.y).toBe(0)2292 expect(() => {2293 draft.y = 22294 }).toThrow("Cannot set property y")2295 draft.x = 22296 expect(draft.y).toBe(2)2297 })2298 expect(next.x).toBe(2)2299 expect(next.y).toBe(2)2300 expect(state.x).toBe(0)2301 })23022303 describe("own setter only", () => {2304 let setterCalled = 02305 const state = {2306 x: 0,2307 set y(value) {2308 setterCalled++2309 this.x = value2310 }2311 }23122313 const next = produce(state, draft => {2314 expect(draft.y).toBeUndefined()2315 // setter is not preserved, so we can write2316 draft.y = 22317 expect(draft.x).toBe(0)2318 expect(draft.y).toBe(2)2319 })2320 expect(setterCalled).toBe(0)2321 expect(next.x).toBe(0)2322 expect(next.y).toBe(2)2323 expect(state.x).toBe(0)2324 })23252326 describe("own getter only", () => {2327 let getterCalled = 02328 const state = {2329 x: 0,2330 get y() {2331 getterCalled++2332 return this.x2333 }2334 }23352336 const next = produce(state, draft => {2337 expect(draft.y).toBe(0)2338 // de-referenced, so stores it locally2339 draft.y = 22340 expect(draft.y).toBe(2)2341 expect(draft.x).toBe(0)2342 })2343 expect(getterCalled).not.toBe(1)2344 expect(next.x).toBe(0)2345 expect(next.y).toBe(2)2346 expect(state.x).toBe(0)2347 })2348}23492350function testLiteralTypes(produce) {2351 class Foo {}
25 unmodified lines
2377 for (const name in values) {2378 describe(name, () => {2379 const value = values[name]23802126 it("does not create a draft", () => {2127 produce(value, draft => {2128 expect(draft).toBe(value)2129 })2130 })21312132 it("returns the base state when no changes are made", () => {2133 expect(produce(value, () => {})).toBe(value)2134 })21352381 if (value && typeof value == "object") {2382 it("does not return a copy when changes are made", () => {2138 expect(2383 expect(() =>2384 produce(value, draft => {2385 draft.foo = true2386 })2142 ).toBe(value)2387 ).toThrowError(2388 "produce can only be called on things that are draftable"2389 )2390 })2391 } else {2392 it("does not create a draft", () => {2393 produce(value, draft => {2394 expect(draft).toBe(value)2395 })2396 })23972398 it("returns the base state when no changes are made", () => {2399 expect(produce(value, () => {})).toBe(value)2400 })2401 }2402 })2403 }2404}
15 unmodified lines
added:__tests__/current.js+206 added
1import {2 setUseProxies,3 setAutoFreeze,4 enableAllPlugins,5 current,6 immerable,7 isDraft,8 produce,9 original10} from "../src/immer"1112enableAllPlugins()1314runTests("proxy", true)15runTests("es5", false)1617function runTests(name, useProxies) {18 describe("current - " + name, () => {19 beforeAll(() => {20 setAutoFreeze(true)21 setUseProxies(useProxies)22 })2324 it("must be called on draft", () => {25 expect(() => {26 current({})27 }).toThrowError("[Immer] 'current' expects a draft, got: [object Object]")28 })2930 it("can handle simple arrays", () => {31 const base = [{x: 1}]32 let c33 const next = produce(base, draft => {34 expect(current(draft)).toEqual(base)35 draft[0].x++36 c = current(draft)37 expect(c).toEqual([{x: 2}])38 expect(Array.isArray(c))39 draft[0].x++40 })41 expect(next).toEqual([{x: 3}])42 expect(c).toEqual([{x: 2}])43 expect(isDraft(c)).toBe(false)44 })4546 it("won't freeze", () => {47 const base = {x: 1}48 const next = produce(base, draft => {49 draft.x++50 expect(Object.isFrozen(current(draft))).toBe(false)51 })52 })5354 it("returns original without changes", () => {55 const base = {}56 produce(base, draft => {57 expect(original(draft)).toBe(base)58 expect(current(draft)).toBe(base)59 })60 })6162 it("can handle property additions", () => {63 const base = {}64 produce(base, draft => {65 draft.x = true66 const c = current(draft)67 expect(c).not.toBe(base)68 expect(c).not.toBe(draft)69 expect(c).toEqual({70 x: true71 })72 })73 })7475 it("can handle property deletions", () => {76 const base = {77 x: 178 }79 produce(base, draft => {80 delete draft.x81 const c = current(draft)82 expect(c).not.toBe(base)83 expect(c).not.toBe(draft)84 expect(c).toEqual({})85 })86 })8788 it("won't reflect changes over time", () => {89 const base = {90 x: 191 }92 produce(base, draft => {93 draft.x++94 const c = current(draft)95 expect(c).toEqual({96 x: 297 })98 draft.x++99 expect(c).toEqual({100 x: 2101 })102 })103 })104105 it("will find drafts inside objects", () => {106 const base = {107 x: 1,108 y: {109 z: 2110 },111 z: {}112 }113 produce(base, draft => {114 draft.y.z++115 draft.y = {116 nested: draft.y117 }118 const c = current(draft)119 expect(c).toEqual({120 x: 1,121 y: {122 nested: {123 z: 3124 }125 },126 z: {}127 })128 expect(isDraft(c.y.nested)).toBe(false)129 expect(c.z).toBe(base.z)130 expect(c.y.nested).not.toBe(draft.y.nested)131 })132 })133134 it("handles map - 1", () => {135 const base = new Map([["a", {x: 1}]])136 produce(base, draft => {137 expect(current(draft)).toBe(base)138 draft.delete("a")139 let c = current(draft)140 expect(current(draft)).not.toBe(base)141 expect(current(draft)).not.toBe(draft)142 expect(c).toEqual(new Map())143 const obj = {}144 draft.set("b", obj)145 expect(c).toEqual(new Map())146 expect(current(draft)).toEqual(new Map([["b", obj]]))147 expect(c).toBeInstanceOf(Map)148 })149 })150151 it("handles map - 2", () => {152 const base = new Map([["a", {x: 1}]])153 produce(base, draft => {154 draft.get("a").x++155 const c = current(draft)156 expect(c).not.toBe(base)157 expect(c).toEqual(new Map([["a", {x: 2}]]))158 draft.get("a").x++159 expect(c).toEqual(new Map([["a", {x: 2}]]))160 })161 })162163 it("handles set", () => {164 const base = new Set([1])165 produce(base, draft => {166 expect(current(draft)).toBe(base)167 draft.add(2)168 const c = current(draft)169 expect(c).toEqual(new Set([1, 2]))170 expect(c).not.toBe(draft)171 expect(c).not.toBe(base)172 draft.add(3)173 expect(c).toEqual(new Set([1, 2]))174 expect(c).toBeInstanceOf(Set)175 })176 })177178 it("handles simple class", () => {179 class Counter {180 [immerable] = true181 current = 0182183 inc() {184 this.current++185 }186 }187188 const counter1 = new Counter()189 produce(counter1, draft => {190 expect(current(draft)).toBe(counter1)191 draft.inc()192 const c = current(draft)193 expect(c).not.toBe(draft)194 expect(c.current).toBe(1)195 c.inc()196 expect(c.current).toBe(2)197 expect(draft.current).toBe(1)198 draft.inc()199 draft.inc()200 expect(c.current).toBe(2)201 expect(draft.current).toBe(3)202 expect(c).toBeInstanceOf(Counter)203 })204 })205 })206}
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+26 added-2 removed
28 unmodified lines
29 expect(isFrozen(next)).toBeTruthy()30 expect(isFrozen(next.arr)).toBeTruthy()31 })3233 it("never freezes reused state", () => {33 it("freezes reused base state", () => {34 const base = {arr: [1], obj: {a: 1}}35 const next = produce(base, draft => {36 draft.arr.push(1)37 })38 expect(next.obj).toBe(base.obj)39 expect(isFrozen(next.obj)).toBeFalsy()39 expect(isFrozen(next.obj)).toBeTruthy()40 })4142 describe("the result is always auto-frozen when", () => {43 it("the root draft is mutated (and no error is thrown)", () => {
175 unmodified lines
219 state2.ref.state.x++220 }).not.toThrow()221 expect(state2.ref.state.x).toBe(2)222 })223224 it("never freezes symbolic fields #590", () => {225 const component = {}226 const symbol = Symbol("test")227 Object.defineProperty(component, symbol, {228 value: {x: 1},229 enumerable: true,230 writable: true,231 configurable: true232 })233234 const state = {235 x: 1236 }237238 const state2 = produce(state, draft => {239 draft.ref = component240 })241242 expect(() => {243 state2.ref[symbol].x++244 }).not.toThrow()245 expect(state2.ref[symbol].x).toBe(2)246 })247 })248}
modified:__tests__/manual.js+1 added-2 removed
modified:__tests__/original.js+13 added-5 removed
modified:__tests__/patch.js+143 added-72 removed
2 unmodified lines
3 setUseProxies,4 applyPatches,5 produceWithPatches,6 enableAllPlugins,7 isDraft7 isDraft,8 immerable9} from "../src/immer"1011enableAllPlugins()12
286 unmodified lines
299 ]300 )301 })302303 describe("nested change in object", () => {304 runPatchTest(305 {306 a: {b: 1}307 },308 d => {309 d.a.b++310 },311 [{op: "replace", path: ["a", "b"], value: 2}],312 [{op: "replace", path: ["a", "b"], value: 1}]313 )314 })315316 describe("nested change in map", () => {317 runPatchTest(318 new Map([["a", new Map([["b", 1]])]]),319 d => {320 d.get("a").set("b", 2)321 },322 [{op: "replace", path: ["a", "b"], value: 2}],323 [{op: "replace", path: ["a", "b"], value: 1}]324 )325 })326327 describe("nested change in array", () => {328 runPatchTest(329 [[{b: 1}]],330 d => {331 d[0][0].b++332 },333 [{op: "replace", path: [0, 0, "b"], value: 2}],334 [{op: "replace", path: [0, 0, "b"], value: 1}]335 )336 })337338 describe("nested map (no changes)", () => {339 runPatchTest(340 new Map([["a", new Map([["b", 1]])]]),341 d => {
169 unmodified lines
511 {x: [1, 2, 3]},512 d => {513 d.x.unshift(4)514 },479 [{op: "add", path: ["x", 0], value: 4}]515 [516 {op: "replace", path: ["x", 0], value: 4},517 {op: "replace", path: ["x", 1], value: 1},518 {op: "replace", path: ["x", 2], value: 2},519 {op: "add", path: ["x", 3], value: 3}520 ]521 )522})523524describe("arrays - multiple prepend", () => {
1 unmodified line
526 {x: [1, 2, 3]},527 d => {528 d.x.unshift(4)529 d.x.unshift(5)530 // 4,5,1,2,3531 },532 [491 {op: "add", path: ["x", 0], value: 5},492 {op: "add", path: ["x", 1], value: 4}533 {op: "replace", path: ["x", 0], value: 5},534 {op: "replace", path: ["x", 1], value: 4},535 {op: "replace", path: ["x", 2], value: 1},536 {op: "add", path: ["x", 3], value: 2},537 {op: "add", path: ["x", 4], value: 3}538 ]539 )540})541
2 unmodified lines
544 {x: [1, 2, 3]},545 d => {546 d.x.splice(1, 1)547 },503 [{op: "remove", path: ["x", 1]}]548 [549 {op: "replace", path: ["x", 1], value: 3},550 {op: "replace", path: ["x", "length"], value: 2}551 ]552 )553})554555describe("arrays - multiple splice", () => {556 runPatchTest(557 [0, 1, 2, 3, 4, 5, 0],558 d => {559 d.splice(4, 2, 3)560 // [0,1,2,3,3,0]561 d.splice(1, 2, 3)562 // [0,3,3,3,0]563 expect(d.slice()).toEqual([0, 3, 3, 3, 0])564 },565 [566 {op: "replace", path: [1], value: 3},567 {op: "replace", path: [2], value: 3},517 {op: "remove", path: [5]},518 {op: "remove", path: [4]}568 {op: "replace", path: [4], value: 0},569 {op: "replace", path: ["length"], value: 5}570 ]571 )572})573
2 unmodified lines
576 {x: [1, 2, 3]},577 d => {578 d.x[0] = 4579 d.x.length = 2580 // [0, 2]581 },582 [583 {op: "replace", path: ["x", 0], value: 4},532 {op: "remove", path: ["x", 2]}584 {op: "replace", path: ["x", "length"], value: 2}585 ],586 [587 {op: "replace", path: ["x", 0], value: 1},588 {op: "add", path: ["x", 2], value: 3}
6 unmodified lines
595 {x: [1, 2, 3]},596 d => {597 d.x.unshift(4)598 d.x.splice(2, 1)599 // 4, 1, 3600 },601 [602 {op: "replace", path: ["x", 0], value: 4},603 {op: "replace", path: ["x", 1], value: 1}
6 unmodified lines
610 {x: [1, 2, 3]},611 d => {612 d.x.splice(1, 1)613 d.x.unshift(4)614 // [4, 1, 3]615 },616 [617 {op: "replace", path: ["x", 0], value: 4},618 {op: "replace", path: ["x", 1], value: 1}
6 unmodified lines
625 {x: [1, 2, 3]},626 d => {627 d.x.length -= 2628 },629 [{op: "replace", path: ["x", "length"], value: 1}],630 [576 {op: "remove", path: ["x", 2]},577 {op: "remove", path: ["x", 1]}578 ],579 [631 {op: "add", path: ["x", 1], value: 2},632 {op: "add", path: ["x", 2], value: 3}633 ]634 )
5 unmodified lines
640 d => {641 d.x.pop()642 d.x.pop()643 },593 [594 {op: "remove", path: ["x", 2]},595 {op: "remove", path: ["x", 1]}596 ]644 [{op: "replace", path: ["x", "length"], value: 1}]645 )646})647648describe("arrays - push multiple", () => {649 // These patches were more optimal pre immer 7, but not always correct650 runPatchTest(651 {x: [1, 2, 3]},652 d => {653 d.x.push(4, 5)
1 unmodified line
655 [656 {op: "add", path: ["x", 3], value: 4},657 {op: "add", path: ["x", 4], value: 5}658 ],610 [611 {op: "remove", path: ["x", 4]},612 {op: "remove", path: ["x", 3]}613 ]659 [{op: "replace", path: ["x", "length"], value: 3}]660 )661})662663describe("arrays - splice (expand)", () => {664 // These patches were more optimal pre immer 7, but not always correct665 runPatchTest(666 {x: [1, 2, 3]},667 d => {621 d.x.splice(1, 1, 4, 5, 6)668 d.x.splice(1, 1, 4, 5, 6) // [1,4,5,6,3]669 },670 [671 {op: "replace", path: ["x", 1], value: 4},625 {op: "add", path: ["x", 2], value: 5},626 {op: "add", path: ["x", 3], value: 6}672 {op: "replace", path: ["x", 2], value: 5},673 {op: "add", path: ["x", 3], value: 6},674 {op: "add", path: ["x", 4], value: 3}675 ],676 [677 {op: "replace", path: ["x", 1], value: 2},630 {op: "remove", path: ["x", 3]},631 {op: "remove", path: ["x", 2]}678 {op: "replace", path: ["x", 2], value: 3},679 {op: "replace", path: ["x", "length"], value: 3}680 ]681 )682})683684describe("arrays - splice (shrink)", () => {685 // These patches were more optimal pre immer 7, but not always correct686 runPatchTest(687 {x: [1, 2, 3, 4, 5]},688 d => {640 d.x.splice(1, 3, 6)689 d.x.splice(1, 3, 6) // [1, 6, 5]690 },691 [692 {op: "replace", path: ["x", 1], value: 6},644 {op: "remove", path: ["x", 3]},645 {op: "remove", path: ["x", 2]}693 {op: "replace", path: ["x", 2], value: 5},694 {op: "replace", path: ["x", "length"], value: 3}695 ],696 [697 {op: "replace", path: ["x", 1], value: 2},649 {op: "add", path: ["x", 2], value: 3},650 {op: "add", path: ["x", 3], value: 4}698 {op: "replace", path: ["x", 2], value: 3},699 {op: "add", path: ["x", 3], value: 4},700 {op: "add", path: ["x", 4], value: 5}701 ]702 )703})704
81 unmodified lines
786 )787})788789describe("arrays - splice should should result in remove op.", () => {790 // These patches were more optimal pre immer 7, but not always correct791 runPatchTest(792 [1, 2],793 d => {794 d.splice(1, 1)795 },745 [{op: "remove", path: [1]}],796 [{op: "replace", path: ["length"], value: 1}],797 [{op: "add", path: [1], value: 2}]798 )799})800801describe("arrays - NESTED splice should should result in remove op.", () => {802 // These patches were more optimal pre immer 7, but not always correct803 runPatchTest(804 {a: {b: {c: [1, 2]}}},805 d => {806 d.a.b.c.splice(1, 1)807 },756 [{op: "remove", path: ["a", "b", "c", 1]}],808 [{op: "replace", path: ["a", "b", "c", "length"], value: 1}],809 [{op: "add", path: ["a", "b", "c", 1], value: 2}]810 )811})812
189 unmodified lines
1002 })1003 ).toEqual({x: -1})1004})1005954test.skip("#468", () => {955 const item = {id: 1}1006describe("#468", () => {1007 function run() {1008 const item = {id: 1}1009 const state = [item]1010 const [nextState, patches] = produceWithPatches(state, draft => {1011 draft[0].id = 21012 draft[1] = item1013 })1014957 const state = [item]1015 expect(nextState).toEqual([{id: 2}, {id: 1}])1016 expect(patches).toEqual([1017 {1018 op: "replace",1019 path: [0, "id"],1020 value: 21021 },1022 {1023 op: "add",1024 path: [1],1025 value: {1026 id: 11027 }1028 }1029 ])1030959 const [nextState, patches] = produceWithPatches(state, draft => {960 draft[0].id = 2961 draft[1] = item1031 const final = applyPatches(state, patches)1032 expect(final).toEqual(nextState)1033 }10341035 test("es5", () => {1036 setUseProxies(false)1037 run()1038 })1039964 expect(nextState).toMatchInlineSnapshot(`965 Array [966 Object {967 "id": 2,968 },969 Object {970 "id": 1,971 },972 ]973 `)974 expect(patches).toMatchInlineSnapshot(`975 Array [976 Object {977 "op": "replace",978 "path": Array [979 0,980 "id",981 ],982 "value": 2,983 },984 Object {985 "op": "add",986 "path": Array [987 0,988 ],989 "value": Object {990 "id": 2,991 },992 },993 ]994 `)995996 const final = applyPatches(state, patches)997 expect(final).toEqual(nextState)1040 test("proxy", () => {1041 setUseProxies(true)1042 run()1043 })1044})10451046test("#521", () => {1047 const state = new Map()
45 unmodified lines
1093 const reversedSubState = applyPatches(newState.sub, inverseChanges)10941095 expect(reversedSubState).toMatchObject(state.sub)1096})10971098describe("#588", () => {1099 const reference = {value: {num: 53}}11001101 class Base {1102 [immerable] = true1103 get nested() {1104 return reference.value1105 }1106 set nested(value) {}1107 }11081109 let base = new Base()11101111 runPatchTest(1112 base,1113 vdraft => {1114 reference.value = vdraft1115 produce(base, bdraft => {1116 bdraft.nested.num = 421117 })1118 },1119 [{op: "add", path: ["num"], value: 42}]1120 )1121})
modified:__tests__/produce.ts+1 added
95 unmodified lines
9697it("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 // @ts-expect-error101 assert(foo, _ as Recipe)102})103104it("can update readonly state via curried api", () => {
375 unmodified lines
modified:__tests__/readme.js+27 added
232 unmodified lines
233 expect(usersById_v1.size).toBe(0)234 // And trying to change a Map outside a producers is going to: NO!235 expect(() => usersById_v3.clear()).toThrowErrorMatchingSnapshot()236})237238test("clock class", () => {239 class Clock {240 [immerable] = true241242 constructor(hour, minute) {243 this.hour = hour244 this.minute = minute245 }246247 get time() {248 return `${this.hour}:${this.minute}`249 }250251 tick() {252 return produce(this, draft => {253 draft.minute++254 })255 }256 }257258 const clock1 = new Clock(12, 10)259 const clock2 = clock1.tick()260 expect(clock1.time).toEqual("12:10") // 12:10261 expect(clock2.time).toEqual("12:11") // 12:11262 expect(clock2).toBeInstanceOf(Clock)263})
modified:docs/api.md+1 added
10 unmodified lines
11| `applyPatches` | Given a base state or draft, and a set of patches, applies the patches | [Patches](patches.md) |12| `castDraft` | Converts any immutable type to its mutable counterpart. This is just a cast and doesn't actually do anything. | [TypeScript](typescript.md) |13| `castImmutable` | Converts any mutable type to its immutable counterpart. This is just a cast and doesn't actually do anything. | [TypeScript](typescript.md) |14| `createDraft` | Given a base state, creates a mutable draft for which any modifications will be recorded | [Async](async.md) |15| `current` | Given a draft object (doesn't have to be a tree root), takes a snapshot of the current state of the draft | [Current](current.md) |16| `Draft<T>` | Exposed TypeScript type to convert an immutable type to a mutable type | [TypeScript](typescript.md) |17| `enableAllPlugins()` | Enables all plugins mentioned below | [Installation](installation#pick-your-immer-version) |18| `enableES5()` | Enables support for older JavaScript engines, such as Internet Explorer and React Native | [Installation](installation#pick-your-immer-version) |19| `enableMapSet()` | Enables support for `Map` and `Set` collections. | [Installation](installation#pick-your-immer-version) |
30 unmodified lines
modified:docs/complex-objects.md+47 added-54 removed
1---2id: complex-objects3title: Working with Map, Set and classes3title: Classes4---56<div id="codefund"><!-- fallback content --></div>78_⚠ Since version 6 support for `Map`s and `Set`s has to be enabled explicitly by calling [`enableMapSet()`](installation#pick-your-immer-version) once when starting your application._8Plain objects (objects without a prototype), arrays, `Map`s and `Set`s are always drafted by Immer. Every other object must use the `immerable` symbol to mark itself as compatible with Immer. When one of these objects is mutated within a producer, its prototype is preserved between copies.910Plain objects, arrays, `Map`s and `Set`s are always drafted by Immer. An example of using Maps with immer:1112```javascript13test("Producers can update Maps", () => {14 const usersById_v1 = new Map()1516 const usersById_v2 = produce(usersById_v1, draft => {17 // Modifying a map results in a new map18 draft.set("michel", {name: "Michel Weststrate", country: "NL"})19 })2021 const usersById_v3 = produce(usersById_v2, draft => {22 // Making a change deep inside a map, results in a new map as well!23 draft.get("michel").country = "UK"24 })2526 // We got a new map each time!27 expect(usersById_v2).not.toBe(usersById_v1)28 expect(usersById_v3).not.toBe(usersById_v2)29 // With different content obviously30 expect(usersById_v1).toMatchInlineSnapshot(`Map {}`)31 expect(usersById_v2).toMatchInlineSnapshot(`32 Map {33 "michel" => Object {34 "country": "NL",35 "name": "Michel Weststrate",36 },37 }38 `)39 expect(usersById_v3).toMatchInlineSnapshot(`40 Map {41 "michel" => Object {42 "country": "UK",43 "name": "Michel Weststrate",44 },45 }46 `)47 // The old one was never modified48 expect(usersById_v1.size).toBe(0)49 // And trying to change a Map outside a producers is going to: NO!50 expect(() => usersById_v3.clear()).toThrowErrorMatchingInlineSnapshot(51 `"This object has been frozen and should not be mutated"`52 )53})54```5556Every other object must use the `immerable` symbol to mark itself as compatible with Immer. When one of these objects is mutated within a producer, its prototype is preserved between copies.5710```js11import {immerable} from "immer"1213class Foo {
6 unmodified lines
2021Foo[immerable] = true // Option 322```2372For arrays, only numeric properties and the `length` property can be mutated. Custom properties are not preserved on arrays.24### Example2574When working with `Date` objects, you should always create a new `Date` instance instead of mutating an existing `Date` object.26```js27import {immerable, produce} from "immer"2876Maps and Sets that are produced by Immer will be made artificially immutable. This means that they will throw an exception when trying mutative methods like `set`, `clear` etc. outside a producer.29class Clock {30 [immerable] = true3178_Note: The **keys** of a map are never drafted! This is done to avoid confusing semantics and keep keys always referentially equal_32 constructor(hour, minute) {33 this.hour = hour34 this.minute = minute35 }3637 get time() {38 return `${this.hour}:${minute}`39 }4041 tick() {42 return produce(this, draft => {43 draft.minute++44 })45 }46}4748const clock1 = new Clock(12, 10)49const clock2 = clock1.tick()50console.log(clock1.time) // 12:1051console.log(clock2.time) // 12:1152console.log(clock2 instanceof Clock) // true53```5455### Semantics in detail5657The semantics on how classes are drafted are as follows:58591. A draft of a class is a fresh object but with the same prototype as the original object.602. When creating a draft, Immer will copy all _own_ properties from the base to the draft.This includes non-enumerable and symbolic properties.613. _Own_ getters will be invoked during the copy process, just like `Object.assign` would.624. Inherited getters and methods will remain as is and be inherited by the draft.635. Immer will not invoke constructor functions.646. The final instance will be constructed with the same mechanism as the draft was created.657. Only getters that have a setter as well will be writable in the draft, as otherwise the value can't be copied back.6667Because Immer will dereference own getters of objects into normal properties, it is possible to use objects that use getter/setter traps on their fields, like MobX and Vue do.6869Immer does not support exotic objects such as DOM Nodes or Buffers.7071So when working for example with `Date` objects, you should always create a new `Date` instance instead of mutating an existing `Date` object.
added:docs/current.md+56 added
1---2id: current3title: Extracting the current state from a draft4sidebar_label: Current5---67<div id="codefund"><!-- fallback content --></div>89Immer exposes a named export `current` that create a copy of the current state of the draft. This can be very useful for debugging purposes (as those objects won't be Proxy objects and not be logged as such). Also, references to `current` can be safely leaked from a produce function. Put differently, `current` provides a snapshot of the current state of a draft.1011Objects generated by `current` work similar to the objects created by produce itself.12131. Unmodified objects will be structurally shared with the original objects.141. If no changes are made to a draft, generally it holds that `original(draft) === current(draft)`, but this is not guaranteed.151. Future changes to the draft won't be reflected in the object produced by `current` (except for references to undraftable objects)161. Unlinke `produce` objects created by `current` will _not_ be frozen.1718Use `current` sparingly, it can be a potentially expensive operation, especially when using ES5.1920Note that `current` cannot be invoked on objects that aren't drafts.2122### Example2324The following example shows the effect of `current` (and `original`):2526```js27const base = {28 x: 029}3031const next = produce(base, draft => {32 draft.x++33 const orig = original(draft)34 const copy = current(draft)35 console.log(orig.x)36 console.log(copy.x)3738 setTimeout(() => {39 // this will execute after the produce has finised!40 console.log(orig.x)41 console.log(copy.x)42 }, 100)4344 draft.x++45 console.log(draft.x)46})47console.log(next.x)4849// This will print50// 0 (orig.x)51// 1 (copy.x)52// 2 (draft.x)53// 2 (next.x)54// 0 (after timeout, orig.x)55// 1 (after timeout, copy.x)56```
modified:docs/example-reducer.md+3 added-3 removed
33 unmodified lines
34 }35}36```3738After using Immer, that simply becomes:38After using Immer, our reducer can be expressed as:3940```javascript41import produce from "immer"42
6 unmodified lines
49 }50}, {})51```5253Notice that it is not needed to handle the default case, a producer that doesn't do anything will simply return the original state.53Notice that it is not necessary to handle the default case, a producer that doesn't do anything will return the original state.5455Creating Redux reducer is just a sample application of the Immer package. Immer is not just designed to simplify Redux reducers. It can be used in any context where you have an immutable data tree that you want to clone and modify (with structural sharing).5657_Note: it might be tempting after using producers for a while, to just place `produce` in your root reducer and then pass the draft to each reducer and work directly over such draft. Don't do that. It kills the point of Redux where each reducer is testable as pure reducer. Immer is best used when applying it to small individual pieces of logic._57_Note: it might be tempting after using producers for a while, to just place `produce` in your root reducer and then pass the draft to each reducer and work directly over said draft. Don't do that. It removes the benefit of using Redux as a system where each reducer is testable as a pure function. Immer is best used when applied to small, individual pieces of logic._
modified:docs/freezing.md+2 added
14 unmodified lines
15</details>1617Immer automatically freezes any state trees that are modified using `produce`. This protects against accidental modifications of the state tree outside of a producer. This comes with a performance impact, so it is recommended to disable this option in production. By default, it is turned on during local development and turned off in production. Use `setAutoFreeze(true / false)` to explicitly turn this feature on or off.1819Immer will never freeze (the contents of) non-enumerable, non-own or symbolic properties, unless their content was drafted.2021_⚠️ If auto freezing is enabled, recipes are not entirely side-effect free: Any plain object or array that ends up in the produced result, will be frozen, even when these objects were not frozen before the start of the producer! ⚠️_
modified:docs/installation.md+7 added-7 removed
10 unmodified lines
11- NPM: `npm install immer`12- CDN: Exposed global is `immer`13 - Unpkg: `<script src="https://unpkg.com/immer"></script>`14 - JSDelivr: `<script src="https://cdn.jsdelivr.net/npm/immer"></script>`15 - ⚠️ When using a CDN, it is best to check the url in your browser and see what version it resolves to, so that your users aren't accidentally served a newer version in the future when updates are release. So use an url like: https://unpkg.com/immer@6.0.3/dist/immer.umd.production.min.js instead. Substitute `production.min` with `development` in the URL for a development build. 15 - ⚠️ When using a CDN, it is best to check the url in your browser and see what version it resolves to, so that your users aren't accidentally served a newer version in the future when updates are release. So use an url like: https://unpkg.com/immer@6.0.3/dist/immer.umd.production.min.js instead. Substitute `production.min` with `development` in the URL for a development build.1617## Pick your Immer version1819_This section only applies to version 6 and later_
38 unmodified lines
58Import size report for immer:59┌───────────────────────┬───────────┬────────────┬───────────┐60│ (index) │ just this │ cumulative │ increment │61├───────────────────────┼───────────┼────────────┼───────────┤62│ import * from 'immer' │ 5606 │ 0 │ 0 │63│ produce │ 3085 │ 3085 │ 0 │64│ enableES5 │ 3870 │ 3878 │ 793 │65│ enableMapSet │ 3893 │ 4654 │ 776 │66│ enablePatches │ 3826 │ 5387 │ 733 │67│ enableAllPlugins │ 5382 │ 5421 │ 34 │62│ import * from 'immer' │ 5662 │ 0 │ 0 │63│ produce │ 3100 │ 3100 │ 0 │64│ enableES5 │ 3761 │ 3770 │ 670 │65│ enableMapSet │ 3885 │ 4527 │ 757 │66│ enablePatches │ 3891 │ 5301 │ 774 │67│ enableAllPlugins │ 5297 │ 5348 │ 47 │68└───────────────────────┴───────────┴────────────┴───────────┘69(this report was generated by npmjs.com/package/import-size)70```71
5 unmodified lines
added:docs/map-set.md+58 added
1---2id: map-set3title: Map and Set4---56<div id="codefund"><!-- fallback content --></div>78_⚠ Since version 6 support for `Map`s and `Set`s has to be enabled explicitly by calling [`enableMapSet()`](installation#pick-your-immer-version) once when starting your application._910Plain objects, arrays, `Map`s and `Set`s are always drafted by Immer. An example of using Maps with immer:1112```javascript13test("Producers can update Maps", () => {14 const usersById_v1 = new Map()1516 const usersById_v2 = produce(usersById_v1, draft => {17 // Modifying a map results in a new map18 draft.set("michel", {name: "Michel Weststrate", country: "NL"})19 })2021 const usersById_v3 = produce(usersById_v2, draft => {22 // Making a change deep inside a map, results in a new map as well!23 draft.get("michel").country = "UK"24 })2526 // We got a new map each time!27 expect(usersById_v2).not.toBe(usersById_v1)28 expect(usersById_v3).not.toBe(usersById_v2)29 // With different content obviously30 expect(usersById_v1).toMatchInlineSnapshot(`Map {}`)31 expect(usersById_v2).toMatchInlineSnapshot(`32 Map {33 "michel" => Object {34 "country": "NL",35 "name": "Michel Weststrate",36 },37 }38 `)39 expect(usersById_v3).toMatchInlineSnapshot(`40 Map {41 "michel" => Object {42 "country": "UK",43 "name": "Michel Weststrate",44 },45 }46 `)47 // The old one was never modified48 expect(usersById_v1.size).toBe(0)49 // And trying to change a Map outside a producers is going to: NO!50 expect(() => usersById_v3.clear()).toThrowErrorMatchingInlineSnapshot(51 `"This object has been frozen and should not be mutated"`52 )53})54```5556Maps and Sets that are produced by Immer will be made artificially immutable. This means that they will throw an exception when trying mutative methods like `set`, `clear` etc. outside a producer.5758_Note: The **keys** of a map are never drafted! This is done to avoid confusing semantics and keep keys always referentially equal_
modified:docs/original.md+2 added-2 removed
1---2id: original3title: Extracting the original object from a proxied instance3title: Extracting the original state from a draft4sidebar_label: Original5---67<div id="codefund"><!-- fallback content --></div>
8 unmodified lines
16 original(draftState.users) // is === baseState.users17})18```1920Just want to know if a value is a proxied instance? Use the `isDraft` function!20Just want to know if a value is a proxied instance? Use the `isDraft` function! Note that `original` cannot be invoked on objects that aren't drafts.2122```js23import {isDraft, produce} from "immer"24
8 unmodified lines
modified:docs/performance.md+6 added
35 unmodified lines
36- Immer with proxies is roughly speaking twice to three times slower as a handwritten reducer (the above test case is worst case, see `yarn test:perf` for more tests). This is in practice negligible.37- Immer is roughly as fast as ImmutableJS. However, the _immutableJS + toJS_ makes clear the cost that often needs to be paid later; converting the immutableJS objects back to plain objects, to be able to pass them to components, over the network etc... (And there is also the upfront cost of converting data received from e.g. the server to immutable JS)38- Generating patches doesn't significantly slow down immer39- The ES5 fallback implementation is roughly twice as slow as the proxy implementation, in some cases worse.4041## Performance tips4243- When adding a large data set to the state tree in an Immer producer (for example data received from a JSON endpoint), it is worth to cool `Object.freeze(json)` on the root of the data to be added first. This will allow Immer to add the new data to the tree faster, as it will skeeping freezing it, or searching the tree for any changes (drafts) that might be made.44- Immer will convert anything you read in a draft recursively into a draft as well. If you have expensive side effect free operations on a draft that involves a lot of reading, for example finding an index using `find(Index)` in a very large array, you can speed this up by first doing the search, and only call the `produce` function once you know the index. Thereby preventing Immer to turn everything that was searched for in a draft. Or, perform the search on the original value of a draft, by using `original(someDraft)`, which boils to the same thing.45- Always try to pull produce 'up', for example `for (let x of y) produce(base, d => d.push(x))` is exponentially slower than `produce(base, d => { for (let x of y) d.push(x)})`
modified:docs/pitfalls.md+2 added-1 removed
3 unmodified lines
4---56<div id="codefund"><!-- fallback content --></div>781. For performance tips, see [Performance Tips](https://immerjs.github.io/immer/docs/performance/#performance-tips).91. Don't redefine draft like, `draft = myCoolNewState`. Instead, either modify the `draft` or return a new state. See [Returning data from producers](https://immerjs.github.io/immer/docs/return).101. Immer assumes your state to be a unidirectional tree. That is, no object should appear twice in the tree, and there should be no circular references.111. Since Immer uses proxies, reading huge amounts of data from state comes with an overhead (especially in the ES5 implementation). If this ever becomes an issue (measure before you optimize!), do the current state analysis before entering the producer function or read from the `currentState` rather than the `draftState`. Also, realize that immer is opt-in everywhere, so it is perfectly fine to manually write super performance critical reducers, and use immer for all the normal ones. Also note that `original` can be used to get the original state of an object, which is cheaper to read.111. Always try to pull `produce` 'up', for example `for (let x of y) produce(base, d => d.push(x))` is exponentially slower than `produce(base, d => { for (let x of y) d.push(x)})`121. It is possible to return values from producers, except, it is not possible to return `undefined` that way, as it is indistinguishable from not updating the draft at all! If you want to replace the draft with `undefined`, just return `nothing` from the producer.131. Immer [does not support exotic objects](https://github.com/immerjs/immer/issues/504) such as window.location.141. You will need to enable your own classes to work properly with Immer. For docs on the topic, check out the section on [working with complex objects](https://immerjs.github.io/immer/docs/complex-objects).151. For arrays, only numeric properties and the `length` property can be mutated. Custom properties are not preserved on arrays.161. Note that data that comes from the closure, and not from the base state, will never be drafted, even when the data has become part of the new draft:1718```javascript19function onReceiveTodo(todo) {
13 unmodified lines
added:docs/update-patterns.md+144 added
1---2id: update-patterns3title: Update patterns4---56<div id="codefund"><!-- fallback content --></div>78Working with immutable data, before Immer, used to mean learning all the immutable update patterns.910To help 'unlearning' those patterns here is an overview how you can leverage the built-in JavaScript APIs to update objects and collections:1112### Object mutations1314```javascript15import produce from "immer"1617const todosObj = {18 id1: {done: false, body: "Take out the trash"},19 id2: {done: false, body: "Check Email"}20}2122// add23const addedTodosObj = produce(todosObj, draft => {24 draft["id3"] = {done: false, body: "Buy bananas"}25})2627// delete28const deletedTodosObj = produce(todosObj, draft => {29 delete draft["id1"]30})3132// update33const updatedTodosObj = produce(todosObj, draft => {34 draft["id1"].done = true35})36```3738### Array mutations3940```javascript41import produce from "immer"4243const todosArray = [44 {id: "id1", done: false, body: "Take out the trash"},45 {id: "id2", done: false, body: "Check Email"}46]4748// add49const addedTodosArray = produce(todosArray, draft => {50 draft.push({id: "id3", done: false, body: "Buy bananas"})51})5253// delete by index54const deletedTodosArray = produce(todosArray, draft => {55 draft.splice(3 /*the index */, 1)56})5758// update by index59const updatedTodosArray = produce(todosArray, draft => {60 draft[3].done = true61})6263// insert at index64const updatedTodosArray = produce(todosArray, draft => {65 draft.splice(3, 0, {id: "id3", done: false, body: "Buy bananas"})66})6768// remove last item69const updatedTodosArray = produce(todosArray, draft => {70 draft.pop()71})7273// remove first item74const updatedTodosArray = produce(todosArray, draft => {75 draft.shift()76})7778// add item at the beginning of the array79const addedTodosArray = produce(todosArray, draft => {80 draft.unshift({id: "id3", done: false, body: "Buy bananas"})81})8283// delete by id84const deletedTodosArray = produce(todosArray, draft => {85 const index = draft.findIndex(todo => todo.id === "id1")86 if (index !== -1) draft.splice(index, 1)87})8889// update by id90const updatedTodosArray = produce(todosArray, draft => {91 const index = draft.findIndex(todo => todo.id === "id1")92 if (index !== -1) draft[index].done = true93})9495// filtering items96const updatedTodosArray = produce(todosArray, draft => {97 // creating a new state is simpler in this example98 // (note that we don't need produce in this case,99 // but as shown below, if the filter is not on the top100 // level produce is still pretty useful)101 return draft.filter(todo => todo.done)102})103```104105### Nested data structures106107```javascript108import produce from "immer"109110// example complex data structure111const store = {112 users: new Map([113 [114 "17",115 {116 name: "Michel",117 todos: [118 {119 title: "Get coffee",120 done: false121 }122 ]123 }124 ]125 ])126}127128// updating something deeply in-an-object-in-an-array-in-a-map-in-an-object:129const nextStore = produce(store, draft => {130 draft.users.get("17").todos[0].done = true131})132133// filtering out all unfinished todo's134const nextStore = produce(store, draft => {135 const user = draft.users.get("17")136 // when filtering, creating a fresh collection is simpler than137 // removing irrelvant items138 user.todos = user.todos.filter(todo => todo.done)139})140```141142Note that many array operations can be used to insert multiple items at once by passing multiple arguments or using the spread operation: `todos.unshift(...items)`.143144Note that when working with arrays that contain objects that are typically identified by some id, we recommend to use `Map` or index based objects (as shown above) instead of performing frequent find operations, lookup tables perform much better in general.
added:src/core/current.ts+60 added
1import {2 die,3 isDraft,4 shallowCopy,5 each,6 DRAFT_STATE,7 get,8 set,9 ImmerState,10 isDraftable,11 ArchtypeMap,12 ArchtypeSet,13 getArchtype,14 getPlugin15} from "../internal"1617export function current<T>(value: T): T18export function current(value: any): any {19 if (!isDraft(value)) die(22, value)20 return currentImpl(value)21}2223function currentImpl(value: any): any {24 if (!isDraftable(value)) return value25 const state: ImmerState | undefined = value[DRAFT_STATE]26 let copy: any27 const archType = getArchtype(value)28 if (state) {29 if (30 !state.modified_ &&31 (state.type_ < 4 || !getPlugin("ES5").hasChanges_(state as any))32 )33 return state.base_34 // Optimization: avoid generating new drafts during copying35 state.finalized_ = true36 copy = copyHelper(value, archType)37 state.finalized_ = false38 } else {39 copy = copyHelper(value, archType)40 }4142 each(copy, (key, childValue) => {43 if (state && get(state.base_, key) === childValue) return // no need to copy or search in something that didn't change44 set(copy, key, currentImpl(childValue))45 })46 // In the future, we might consider freezing here, based on the current settings47 return archType === ArchtypeSet ? new Set(copy) : copy48}4950function copyHelper(value: any, archType: number): any {51 // creates a shallow copy, even if it is a map or set52 switch (archType) {53 case ArchtypeMap:54 return new Map(value)55 case ArchtypeSet:56 // Set will be cloned as array temporarily, so that we can replace individual items57 return Array.from(value)58 }59 return shallowCopy(value)60}
modified:src/core/finalize.ts+4 added-10 removed
5 unmodified lines
6 PatchPath,7 each,8 has,9 freeze,10 shallowCopy,10 ImmerState,11 isDraft,12 SetState,13 set,15 is,16 get,14 ProxyTypeES5Object,15 ProxyTypeES5Array,16 ProxyTypeSet,17 getPlugin,18 die,19 revokeScope,23 isFrozen20 isFrozen,21 shallowCopy22} from "../internal"2324export function processResult(result: any, scope: ImmerScope) {25 scope.unfinalizedDrafts_ = scope.drafts_.length
58 unmodified lines
84 state.scope_.unfinalizedDrafts_--85 const result =86 // For ES5, create a good copy from the draft first, with added keys and without deleted keys.87 state.type_ === ProxyTypeES5Object || state.type_ === ProxyTypeES5Array90 ? (state.copy_ = shallowCopy(state.draft_, true))88 ? (state.copy_ = shallowCopy(state.draft_))89 : state.copy_90 // finalize all children of the copy91 each(result as any, (key, childValue) =>92 finalizeProperty(rootScope, state, result, key, childValue, path)
38 unmodified lines
131 if (isDraft(res)) {132 rootScope.canAutoFreeze_ = false133 } else return134 }137 // Unchanged draft properties are ignored.138 if (parentState && is(childValue, get(parentState!.base_, prop))) {139 return140 }135 // Search new objects for unfinalized drafts. Frozen objects should never contain drafts.142 if (isDraftable(childValue)) {136 if (isDraftable(childValue) && !Object.isFrozen(childValue)) {137 if (!rootScope.immer_.autoFreeze_ && rootScope.unfinalizedDrafts_ < 1) {138 // optimization: if an object is not a draft, and we don't have to139 // deepfreeze everything, and we are sure that no drafts are left in the remaining object140 // cause we saw and finalized all drafts already; we can stop visiting the rest of the tree.
16 unmodified lines
modified:src/core/immerClass.ts+9 added-16 removed
3 unmodified lines
4 ImmerState,5 Drafted,6 isDraftable,7 processResult,8 NOTHING,8 Patch,9 Objectish,10 DRAFT_STATE,11 Draft,12 PatchListener,13 isDraft,14 isMap,15 isSet,17 markChangedProxy,16 createProxyProxy,19 freeze,17 getPlugin,18 die,19 hasProxies,20 isMinified,21 enterScope,22 revokeScope,23 leaveScope,24 usePatchesInScope,28 getCurrentScope25 getCurrentScope,26 NOTHING,27 freeze,28 current29} from "../internal"3031interface ProducersFns {32 produce: IProduce
81 unmodified lines
114 )115 }116 usePatchesInScope(scope, patchListener)117 return processResult(result, scope)118 } else {118 } else if (!base || typeof base !== "object") {119 result = recipe(base)120 if (result === NOTHING) return undefined121 if (result === undefined) result = base122 if (this.autoFreeze_) freeze(result, true)123 return result124 }124 } else die(21, base)125 }126127 produceWithPatches(arg1: any, arg2?: any, arg3?: any): any {128 if (typeof arg1 === "function") {
10 unmodified lines
139 }140141 createDraft<T extends Objectish>(base: T): Draft<T> {142 if (!isDraftable(base)) die(8)143 if (isDraft(base)) base = current(base)144 const scope = enterScope(this)145 const proxy = createProxy(this, base, undefined)146 proxy[DRAFT_STATE].isManual_ = true147 leaveScope(scope)
3 unmodified lines
151 finishDraft<D extends Draft<any>>(152 draft: D,153 patchListener?: PatchListener154 ): D extends Draft<infer T> ? T : never {154 const state: ImmerState = draft && draft[DRAFT_STATE]155 const state: ImmerState = draft && (draft as any)[DRAFT_STATE]156 if (__DEV__) {157 if (!state || !state.isManual_) die(9)158 if (state.finalized_) die(10)159 }
17 unmodified lines
177 *178 * By default, feature detection is used, so calling this is rarely necessary.179 */180 setUseProxies(value: boolean) {180 if (!hasProxies) {181 if (value && !hasProxies) {182 die(20)183 }184 this.useProxies_ = value185 }
39 unmodified lines
225 const scope = parent ? parent.scope_ : getCurrentScope()226 scope.drafts_.push(draft)227 return draft228}228229export function markChanged(immer: Immer, state: ImmerState) {230 if (immer.useProxies_) {231 markChangedProxy(state)232 } else {233 getPlugin("ES5").markChangedES5_(state)234 }235}
modified:src/core/proxy.ts+49 added-70 removed
1"use strict"1import {2 each,3 has,4 is,
18 unmodified lines
23 assigned_: {24 [property: string]: boolean25 }26 parent_?: ImmerState28 drafts_?: {29 [property: string]: Drafted<any, any>30 }27 revoke_(): void28}2930export interface ProxyObjectState extends ProxyBaseState {31 type_: typeof ProxyTypeProxyObject36 base_: AnyObject37 copy_: AnyObject | null32 base_: any33 copy_: any34 draft_: Drafted<AnyObject, ProxyObjectState>35}3637export interface ProxyArrayState extends ProxyBaseState {
30 unmodified lines
68 // The base state.69 base_: base,70 // The base proxy.71 draft_: null as any, // set below76 // Any property proxies.77 drafts_: {},72 // The base copy with any updated values.73 copy_: null,74 // Called by the `produce` function.75 revoke_: null as any,
21 unmodified lines
9798/**99 * Object drafts100 */107const objectTraps: ProxyHandler<ProxyState> = {101export const objectTraps: ProxyHandler<ProxyState> = {102 get(state, prop) {103 if (prop === DRAFT_STATE) return state110 let {drafts_: drafts} = state104112 // Check for existing draft in unmodified state.113 if (!state.modified_ && has(drafts, prop)) {114 return drafts![prop as any]105 const source = latest(state)106 if (!has(source, prop)) {107 // non-existing or non-own property...108 return readPropFromProto(state, source, prop)109 }116117 const value = latest(state)[prop]110 const value = source[prop]111 if (state.finalized_ || !isDraftable(value)) {112 return value113 }121114 // Check for existing draft in modified state.123 if (state.modified_) {124 // Assigned values are never drafted. This catches any drafts we created, too.125 if (value !== peek(state.base_, prop)) return value126 // Store drafts on the copy (when one exists).127 // @ts-ignore128 drafts = state.copy_115 // Assigned values are never drafted. This catches any drafts we created, too.116 if (value === peek(state.base_, prop)) {117 prepareCopy(state)118 return (state.copy_![prop as any] = createProxy(119 state.scope_.immer_,120 value,121 state122 ))123 }130131 return (drafts![prop as any] = createProxy(132 state.scope_.immer_,133 value,134 state135 ))124 return value125 },126 has(state, prop) {127 return prop in latest(state)128 },129 ownKeys(state) {130 return Reflect.ownKeys(latest(state))131 },132 set(state, prop: string /* strictly not, but helps TS */, value) {133 state.assigned_[prop] = true134 if (!state.modified_) {145 const baseValue = peek(state.base_, prop)146 // Optimize based on value's truthiness. Truthy values are guaranteed to147 // never be undefined, so we can avoid the `in` operator. Lastly, truthy148 // values may be drafts, but falsy values are never drafts.149 const isUnchanged = value150 ? is(baseValue, value) || value === state.drafts_![prop]151 : is(baseValue, value) && prop in state.base_152 if (isUnchanged) return true135 if (is(value, peek(latest(state), prop)) && value !== undefined)136 return true137 prepareCopy(state)154 markChangedProxy(state)138 markChanged(state)139 }156 state.assigned_[prop] = true140 // @ts-ignore141 state.copy_![prop] = value142 return true143 },
1 unmodified line
145 // The `undefined` check is a fast path for pre-existing keys.146 if (peek(state.base_, prop) !== undefined || prop in state.base_) {147 state.assigned_[prop] = false148 prepareCopy(state)166 markChangedProxy(state)167 } else if (state.assigned_[prop]) {149 markChanged(state)150 } else {151 // if an originally not assigned property was deleted152 delete state.assigned_[prop]153 }154 // @ts-ignore
4 unmodified lines
159 // the same guarantee in ES5 mode.160 getOwnPropertyDescriptor(state, prop) {161 const owner = latest(state)162 const desc = Reflect.getOwnPropertyDescriptor(owner, prop)180 if (desc) {181 desc.writable = true182 desc.configurable =183 state.type_ !== ProxyTypeProxyArray || prop !== "length"163 if (!desc) return desc164 return {165 writable: true,166 configurable: state.type_ !== ProxyTypeProxyArray || prop !== "length",167 enumerable: desc.enumerable,168 value: owner[prop]169 }185 return desc170 },171 defineProperty() {172 die(11)173 },
25 unmodified lines
199 if (__DEV__ && prop !== "length" && isNaN(parseInt(prop as any))) die(14)200 return objectTraps.set!.call(this, state[0], prop, value, state[0])201}202219/**220 * Map drafts221 */222203// Access a property without creating an Immer draft.224function peek(draft: Drafted, prop: PropertyKey): any {204function peek(draft: Drafted, prop: PropertyKey) {205 const state = draft[DRAFT_STATE]226 const desc = Reflect.getOwnPropertyDescriptor(227 state ? latest(state) : draft,228 prop229 )230 return desc && desc.value206 const source = state ? latest(state) : draft207 return source[prop]208}209210function readPropFromProto(state: ImmerState, source: any, prop: PropertyKey) {211 // 'in' checks proto!212 if (!(prop in source)) return undefined213 let proto = Object.getPrototypeOf(source)214 while (proto) {215 const desc = Object.getOwnPropertyDescriptor(proto, prop)216 // This is a very special case, if the prop is a getter defined by the217 // prototype, we should invoke it with the draft as context!218 if (desc) return `value` in desc ? desc.value : desc.get?.call(state.draft_)219 proto = Object.getPrototypeOf(proto)220 }221 return undefined222}223233export function markChangedProxy(state: ImmerState) {224export function markChanged(state: ImmerState) {225 if (!state.modified_) {226 state.modified_ = true236 if (237 state.type_ === ProxyTypeProxyObject ||238 state.type_ === ProxyTypeProxyArray239 ) {240 const copy = (state.copy_ = shallowCopy(state.base_))241 each(state.drafts_!, (key, value) => {242 // @ts-ignore243 copy[key] = value244 })245 state.drafts_ = undefined246 }247227 if (state.parent_) {249 markChangedProxy(state.parent_)228 markChanged(state.parent_)229 }230 }231}232254function prepareCopy(state: ProxyState) {233export function prepareCopy(state: {base_: any; copy_: any}) {234 if (!state.copy_) {235 state.copy_ = shallowCopy(state.base_)236 }237}
modified:src/plugins/es5.ts+49 added-96 removed
1import {2 ImmerState,3 Drafted,4 Objectish,4 ES5ArrayState,5 ES5ObjectState,6 each,7 has,8 isDraft,10 isDraftable,11 shallowCopy,9 latest,10 DRAFT_STATE,11 is,12 loadPlugin,13 ImmerScope,17 createProxy,14 ProxyTypeES5Array,15 ProxyTypeES5Object,20 AnyObject,16 getCurrentScope,22 die17 die,18 markChanged,19 objectTraps20} from "../internal"2122type ES5State = ES5ArrayState | ES5ObjectState23
2 unmodified lines
26 scope: ImmerScope,27 result: any,28 isReplaced: boolean29 ) {33 scope.drafts_!.forEach((draft: any) => {34 ;(draft[DRAFT_STATE] as ES5State).finalizing_ = true35 })30 if (!isReplaced) {31 if (scope.patches_) {32 markChangesRecursively(scope.drafts_![0])33 }
8 unmodified lines
42 markChangesSweep(scope.drafts_)43 }44 }4546 function createES5Draft(isArray: boolean, base: any) {47 // Create a new object / array, where each own property is trapped with an accessor48 const descriptors = Object.getOwnPropertyDescriptors(base)49 // Descriptors we want to skip:50 if (isArray) delete descriptors.length51 delete descriptors[DRAFT_STATE as any]52 for (let key in descriptors) {53 descriptors[key] = proxyProperty(54 key,55 isArray || !!descriptors[key].enumerable56 )57 }58 if (isArray) {59 const draft = new Array(base.length)60 Object.defineProperties(draft, descriptors)61 return draft62 } else {63 return Object.create(Object.getPrototypeOf(base), descriptors)64 }65 }6667 function createES5Proxy_<T>(68 base: T,69 parent?: ImmerState70 ): Drafted<T, ES5ObjectState | ES5ArrayState> {71 const isArray = Array.isArray(base)57 const draft: any = clonePotentialDraft(base)72 const draft = createES5Draft(isArray, base)7359 each(draft, prop => {60 proxyProperty(draft, prop, isArray || isEnumerable(base, prop))61 })6274 const state: ES5ObjectState | ES5ArrayState = {75 type_: isArray ? ProxyTypeES5Array : (ProxyTypeES5Object as any),76 scope_: parent ? parent.scope_ : getCurrentScope(),77 modified_: false,67 finalizing_: false,78 finalized_: false,79 assigned_: {},80 parent_: parent,81 // base is the object we are drafting82 base_: base,83 // draft is the draft object itself, that traps all reads and reads from either the base (if unmodified) or copy (if modified)84 draft_: draft,85 copy_: null,86 revoked_: false,87 isManual_: false
6 unmodified lines
94 })95 return draft96 }9786 // Access a property without creating an Immer draft.87 function peek(draft: Drafted, prop: PropertyKey) {88 const state: ES5State = draft[DRAFT_STATE]89 if (state && !state.finalizing_) {90 state.finalizing_ = true91 const value = draft[prop]92 state.finalizing_ = false93 return value94 }95 return draft[prop]96 }9798 function get(state: ES5State, prop: string | number) {99 assertUnrevoked(state)100 const value = peek(latest(state), prop)101 if (state.finalizing_) return value102 // Create a draft if the value is unmodified.103 if (value === peek(state.base_, prop) && isDraftable(value)) {104 prepareCopy(state)105 // @ts-ignore106 return (state.copy_![prop] = createProxy(107 state.scope_.immer_,108 value,109 state110 ))111 }112 return value113 }114115 function set(state: ES5State, prop: string | number, value: any) {116 assertUnrevoked(state)117 state.assigned_[prop] = true118 if (!state.modified_) {119 if (is(value, peek(latest(state), prop))) return120 markChangedES5_(state)121 prepareCopy(state)122 }123 // @ts-ignore124 state.copy_![prop] = value125 }126127 function markChangedES5_(state: ImmerState) {128 if (!state.modified_) {129 state.modified_ = true130 if (state.parent_) markChangedES5_(state.parent_)131 }132 }133134 function prepareCopy(state: ES5State) {135 if (!state.copy_) state.copy_ = clonePotentialDraft(state.base_)136 }137138 function clonePotentialDraft(base: Objectish) {139 const state: ES5State | undefined = base && (base as any)[DRAFT_STATE]140 if (state) {141 state.finalizing_ = true142 const draft = shallowCopy(state.draft_, true)143 state.finalizing_ = false144 return draft145 }146 return shallowCopy(base)147 }14898 // property descriptors are recycled to make sure we don't create a get and set closure per property,99 // but share them all instead100 const descriptors: {[prop: string]: PropertyDescriptor} = {}101102 function proxyProperty(154 draft: Drafted<any, ES5State>,103 prop: string | number,104 enumerable: boolean157 ) {105 ): PropertyDescriptor {106 let desc = descriptors[prop]107 if (desc) {108 desc.enumerable = enumerable109 } else {110 descriptors[prop] = desc = {163 // configurable: true,111 configurable: true,112 enumerable,113 get(this: any) {166 return get(this[DRAFT_STATE], prop)114 const state = this[DRAFT_STATE]115 if (__DEV__) assertUnrevoked(state)116 // @ts-ignore117 return objectTraps.get(state, prop)118 },119 set(this: any, value) {169 set(this[DRAFT_STATE], prop, value)120 const state = this[DRAFT_STATE]121 if (__DEV__) assertUnrevoked(state)122 // @ts-ignore123 objectTraps.set(state, prop, value)124 }125 }126 }173 Object.defineProperty(draft, prop, desc)127 return desc128 }129130 // This looks expensive, but only proxies are visited, and only objects without known changes are scanned.131 function markChangesSweep(drafts: Drafted<any, ImmerState>[]) {
5 unmodified lines
137 const state: ES5State = drafts[i][DRAFT_STATE]138 if (!state.modified_) {139 switch (state.type_) {140 case ProxyTypeES5Array:187 if (hasArrayChanges(state)) markChangedES5_(state)141 if (hasArrayChanges(state)) markChanged(state)142 break143 case ProxyTypeES5Object:190 if (hasObjectChanges(state)) markChangedES5_(state)144 if (hasObjectChanges(state)) markChanged(state)145 break146 }147 }148 }
5 unmodified lines
154 if (!state) return155 const {base_, draft_, assigned_, type_} = state156 if (type_ === ProxyTypeES5Object) {157 // Look for added keys.204 // TODO: looks quite duplicate to hasObjectChanges,158 // probably there is a faster way to detect changes, as sweep + recurse seems to do some159 // unnecessary work.160 // also: probably we can store the information we detect here, to speed up tree finalization!161 each(draft_, key => {162 if ((key as any) === DRAFT_STATE) return163 // The `undefined` check is a fast path for pre-existing keys.164 if ((base_ as any)[key] === undefined && !has(base_, key)) {165 assigned_[key] = true213 markChangedES5_(state)166 markChanged(state)167 } else if (!assigned_[key]) {168 // Only untouched properties trigger recursion.169 markChangesRecursively(draft_[key])170 }
2 unmodified lines
173 each(base_, key => {174 // The `undefined` check is a fast path for pre-existing keys.175 if (draft_[key] === undefined && !has(draft_, key)) {176 assigned_[key] = false224 markChangedES5_(state)177 markChanged(state)178 }179 })180 } else if (type_ === ProxyTypeES5Array) {181 if (hasArrayChanges(state as ES5ArrayState)) {229 markChangedES5_(state)182 markChanged(state)183 assigned_.length = true184 }185186 if (draft_.length < base_.length) {
60 unmodified lines
247 // For all other cases, we don't have to compare, as they would have been picked up by the index setters248 return false249 }250298 /*#__PURE__*/299 function isEnumerable(base: AnyObject, prop: PropertyKey): boolean {300 const desc = Object.getOwnPropertyDescriptor(base, prop)301 return desc && desc.enumerable ? true : false251 function hasChanges_(state: ES5State) {252 return state.type_ === ProxyTypeES5Object253 ? hasObjectChanges(state)254 : hasArrayChanges(state)255 }256257 function assertUnrevoked(state: any /*ES5State | MapState | SetState*/) {258 if (state.revoked_) die(3, JSON.stringify(latest(state)))259 }260261 loadPlugin("ES5", {262 createES5Proxy_,310 markChangedES5_,311 willFinalizeES5_263 willFinalizeES5_,264 hasChanges_265 })266}
modified:src/plugins/mapset.ts+6 added-6 removed
80 unmodified lines
81 const state: MapState = this[DRAFT_STATE]82 assertUnrevoked(state)83 if (latest(state).get(key) !== value) {84 prepareMapCopy(state)85 markChanged(state.scope_.immer_, state)85 markChanged(state)86 state.assigned_!.set(key, true)87 state.copy_!.set(key, value)88 state.assigned_!.set(key, true)89 }
7 unmodified lines
9798 const state: MapState = this[DRAFT_STATE]99 assertUnrevoked(state)100 prepareMapCopy(state)101 markChanged(state.scope_.immer_, state)101 markChanged(state)102 state.assigned_!.set(key, false)103 state.copy_!.delete(key)104 return true105 }
1 unmodified line
107 p.clear = function() {108 const state: MapState = this[DRAFT_STATE]109 assertUnrevoked(state)110 prepareMapCopy(state)111 markChanged(state.scope_.immer_, state)111 markChanged(state)112 state.assigned_ = new Map()113 return state.copy_!.clear()114 }115
126 unmodified lines
242 const state: SetState = this[DRAFT_STATE]243 assertUnrevoked(state)244 if (!this.has(value)) {245 prepareSetCopy(state)246 markChanged(state.scope_.immer_, state)246 markChanged(state)247 state.copy_!.add(value)248 }249 return this250 }
5 unmodified lines
256257 const state: SetState = this[DRAFT_STATE]258 assertUnrevoked(state)259 prepareSetCopy(state)260 markChanged(state.scope_.immer_, state)260 markChanged(state)261 return (262 state.copy_!.delete(value) ||263 (state.drafts_.has(value)264 ? state.copy_!.delete(state.drafts_.get(value))
4 unmodified lines
269 p.clear = function() {270 const state: SetState = this[DRAFT_STATE]271 assertUnrevoked(state)272 prepareSetCopy(state)273 markChanged(state.scope_.immer_, state)273 markChanged(state)274 return state.copy_!.clear()275 }276277 p.values = function(): IterableIterator<any> {
60 unmodified lines
modified:src/plugins/patches.ts+11 added-24 removed
22 unmodified lines
23 ProxyTypeSet,24 ArchtypeMap,25 ArchtypeSet,26 ArchtypeArray,27 die27 die,28 isDraft29} from "../internal"29import {isDraft} from "../utils/common"3031export function enablePatches() {32 const REPLACE = "replace"33 const ADD = "add"
43 unmodified lines
77 ;[base_, copy_] = [copy_, base_]78 ;[patches, inversePatches] = [inversePatches, patches]79 }8081 const delta = copy_.length - base_.length8283 // Find the first replaced index.84 let start = 085 while (base_[start] === copy_[start] && start < base_.length) {86 ++start87 }8889 // Find the last replaced index. Search from the end to optimize splice patches.90 let end = base_.length91 while (end > start && base_[end - 1] === copy_[end + delta - 1]) {92 --end93 }9481 // Process replaced indices.96 for (let i = start; i < end; ++i) {82 for (let i = 0; i < base_.length; i++) {83 if (assigned_[i] && copy_[i] !== base_[i]) {84 const path = basePath.concat([i])85 patches.push({86 op: REPLACE,
9 unmodified lines
96 })97 }98 }99114 const replaceCount = patches.length115100 // Process added indices.117 for (let i = end + delta - 1; i >= end; --i) {101 for (let i = base_.length; i < copy_.length; i++) {102 const path = basePath.concat([i])119 patches[replaceCount + i - end] = {103 patches.push({104 op: ADD,105 path,106 // Need to maybe clone it, as it can in fact be the original value107 // due to the base/copy inversion at the start of this function108 value: clonePatchValueIfNeeded(copy_[i])125 }109 })110 }111 if (base_.length < copy_.length) {112 inversePatches.push({127 op: REMOVE,128 path113 op: REPLACE,114 path: basePath.concat(["length"]),115 value: base_.length116 })117 }118 }119
174 unmodified lines
modified:src/types/index.js.flow+36 added-34 removed
1// @flow23export interface Patch {4 op: "replace" | "remove" | "add",5 path: (string|number)[],6 value?: any4 op: "replace" | "remove" | "add";5 path: (string | number)[];6 value?: any;7}89export type PatchListener = (patches: Patch[], inversePatches: Patch[]) => void1011type Base = {...} | Array<any> | Map<any> | Set<any>;11type Base = {...} | Array<any> | Map<any> | Set<any>12interface IProduce {13 /**14 * Immer takes a state, and runs a function against it.15 * That function can freely mutate the state, as it will create copies-on-write.16 * This means that the original state will stay unchanged, and once the function finishes, the modified state is returned.17 *18 * If the first argument is a function, this is interpreted as the recipe, and will create a curried function that will execute the recipe19 * any time it is called with the current state.20 *21 * @param currentState - the state to start with22 * @param recipe - function that receives a proxy of the current state as first argument and which can be freely modified23 * @param initialState - if a curried function is created and this argument was given, it will be used as fallback if the curried function is called with a state of undefined24 * @returns The next state: a new state, or the current state if nothing was modified25 */26 <S: Base>(27 currentState: S,28 recipe: (draftState: S) => S | void,29 patchListener?: PatchListener30 ): S;31 // curried invocations with inital state32 <S: Base, A = void, B = void, C = void>(33 recipe: (draftState: S, a: A, b: B, c: C, ...extraArgs: any[]) => S | void,34 initialState: S35 ): (currentState: S | void, a: A, b: B, c: C, ...extraArgs: any[]) => S;36 // curried invocations without inital state37 <S: Base, A = void, B = void, C = void>(38 recipe: (draftState: S, a: A, b: B, c: C, ...extraArgs: any[]) => S | void39 ): (currentState: S, a: A, b: B, c: C, ...extraArgs: any[]) => S;13 /**14 * Immer takes a state, and runs a function against it.15 * That function can freely mutate the state, as it will create copies-on-write.16 * This means that the original state will stay unchanged, and once the function finishes, the modified state is returned.17 *18 * If the first argument is a function, this is interpreted as the recipe, and will create a curried function that will execute the recipe19 * any time it is called with the current state.20 *21 * @param currentState - the state to start with22 * @param recipe - function that receives a proxy of the current state as first argument and which can be freely modified23 * @param initialState - if a curried function is created and this argument was given, it will be used as fallback if the curried function is called with a state of undefined24 * @returns The next state: a new state, or the current state if nothing was modified25 */26 <S: Base>(27 currentState: S,28 recipe: (draftState: S) => S | void,29 patchListener?: PatchListener30 ): S;31 // curried invocations with inital state32 <S: Base, A = void, B = void, C = void>(33 recipe: (draftState: S, a: A, b: B, c: C, ...extraArgs: any[]) => S | void,34 initialState: S35 ): (currentState: S | void, a: A, b: B, c: C, ...extraArgs: any[]) => S;36 // curried invocations without inital state37 <S: Base, A = void, B = void, C = void>(38 recipe: (draftState: S, a: A, b: B, c: C, ...extraArgs: any[]) => S | void39 ): (currentState: S, a: A, b: B, c: C, ...extraArgs: any[]) => S;40}4142declare export var produce: IProduce43declare export default IProduce
17 unmodified lines
61declare export function setUseProxies(useProxies: boolean): void6263declare export function applyPatches<S>(state: S, patches: Patch[]): S6465declare export function original<S>(value: S): ?S65declare export function original<S>(value: S): S6667declare export function current<S>(value: S): S6869declare export function isDraft(value: any): boolean7071/**70 * Creates a mutable draft from an (immutable) object / array. 72 * Creates a mutable draft from an (immutable) object / array.73 * The draft can be modified until `finishDraft` is called74 */75declare export function createDraft<T>(base: T): T7677/**76 * Given a draft that was created using `createDraft`, 78 * Given a draft that was created using `createDraft`,79 * finalizes the draft into a new immutable object.80 * Optionally a patch-listener can be provided to gather the patches that are needed to construct the object.81 */82declare export function finishDraft<T>(base: T, listener?: PatchListener): T
5 unmodified lines
modified:src/utils/common.ts+26 added-35 removed
3 unmodified lines
4 hasSet,5 Objectish,6 Drafted,7 AnyObject,8 AnyArray,8 AnyMap,9 AnySet,10 ImmerState,11 hasMap,
34 unmodified lines
46/** Get the underlying object that is represented by the given draft */47/*#__PURE__*/48export function original<T>(value: T): T | undefined49export function original(value: Drafted<any>): any {51 if (value && value[DRAFT_STATE]) {52 return value[DRAFT_STATE].base_ as any53 }54 // otherwise return undefined50 if (!isDraft(value)) die(23, value)51 return value[DRAFT_STATE].base_52}5354/*#__PURE__*/55export const ownKeys: (target: AnyObject) => PropertyKey[] =
12 unmodified lines
68 enumerableOnly?: boolean69): void70export function each(obj: any, iter: any, enumerableOnly = false) {71 if (getArchtype(obj) === ArchtypeObject) {75 ;(enumerableOnly ? Object.keys : ownKeys)(obj).forEach(key =>76 iter(key, obj[key], obj)77 )72 ;(enumerableOnly ? Object.keys : ownKeys)(obj).forEach(key => {73 if (!enumerableOnly || typeof key !== "symbol") iter(key, obj[key], obj)74 })75 } else {76 obj.forEach((entry: any, index: any) => iter(index, entry, obj))77 }78}
62 unmodified lines
141 return state.copy_ || state.base_142}143144/*#__PURE__*/148export function shallowCopy<T extends AnyObject | AnyArray>(149 base: T,150 invokeGetters?: boolean151): T152export function shallowCopy(base: any, invokeGetters = false) {145export function shallowCopy(base: any) {146 if (Array.isArray(base)) return base.slice()154 const clone = Object.create(Object.getPrototypeOf(base))155 each(base, (key: any) => {156 if (key === DRAFT_STATE) {157 return // Never copy over draft state.147 const descriptors = Object.getOwnPropertyDescriptors(base)148 delete descriptors[DRAFT_STATE as any]149 for (let key in descriptors) {150 const desc = descriptors[key]151 if (desc.writable === false) {152 desc.writable = true153 desc.configurable = true154 }159 const desc = Object.getOwnPropertyDescriptor(base, key)!160 let {value} = desc161 if (desc.get) {162 if (!invokeGetters) die(1)163 value = desc.get.call(base)164 }165 if (desc.enumerable) {166 clone[key] = value167 } else {168 Object.defineProperty(clone, key, {169 value,170 writable: true,171 configurable: true172 })173 }174 })175 return clone155 // like object.assign, we will read any _own_, get/set accessors. This helps in dealing156 // with libraries that trap values, like mobx or vue157 // unlike object.assign, non-enumerables will be copied as well158 if (desc.get || desc.set)159 descriptors[key] = {160 configurable: true,161 writable: true, // could live with !!desc.set as well here...162 enumerable: desc.enumerable,163 value: base[key]164 }165 }166 return Object.create(Object.getPrototypeOf(base), descriptors)167}168169export function freeze(obj: any, deep: boolean): void {179 if (isDraft(obj) || isFrozen(obj) || !isDraftable(obj)) return170 if (Object.isFrozen(obj) || isDraft(obj) || !isDraftable(obj)) return171 if (getArchtype(obj) > 1 /* Map or Set */) {172 obj.set = obj.add = obj.clear = obj.delete = dontMutateFrozenCollections as any173 }174 Object.freeze(obj)
12 unmodified lines
modified:src/utils/errors.ts+10 added-3 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: " + plugin32 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 },35 20: "Cannot use proxies if Proxy, Proxy.revocable or Reflect are not available"37 22(thing: string) {38 return `'current' expects a draft, got: ${thing}`39 },40 23(thing: string) {41 return `'original' expects a draft, got: ${thing}`42 }43} as const4445export function die(error: keyof typeof errors, ...args: any[]): never {46 if (__DEV__) {
14 unmodified lines
modified:src/utils/plugins.ts+3 added-5 removed
3 unmodified lines
4 ImmerScope,5 Drafted,6 AnyObject,7 ImmerBaseState,8 AnyArray,8 AnyMap,9 AnySet,10 ProxyTypeES5Array,11 ProxyTypeES5Object,
24 unmodified lines
36 createES5Proxy_<T>(37 base: T,38 parent?: ImmerState39 ): Drafted<T, ES5ObjectState | ES5ArrayState>41 markChangedES5_(state: ImmerState): void40 hasChanges_(state: ES5ArrayState | ES5ObjectState): boolean41 }42 MapSet?: {43 proxyMap_<T extends AnyMap>(target: T, parent?: ImmerState): T44 proxySet_<T extends AnySet>(target: T, parent?: ImmerState): T
22 unmodified lines
6768/** ES5 Plugin */6970interface ES5BaseState extends ImmerBaseState {72 finalizing_: boolean71 assigned_: {[key: string]: any}72 parent_?: ImmerState73 revoked_: boolean74}
7 unmodified lines
8283export interface ES5ArrayState extends ES5BaseState {84 type_: typeof ProxyTypeES5Array85 draft_: Drafted<AnyObject, ES5ArrayState>88 base_: AnyArray89 copy_: AnyArray | null86 base_: any87 copy_: any88}8990/** Map / Set plugin */91
21 unmodified lines
modified:src/immer.ts+1 added
10 unmodified lines
11 Immutable,12 Patch,13 PatchListener,14 original,15 current,16 isDraft,17 isDraftable,18 NOTHING as nothing,19 DRAFTABLE as immerable
97 unmodified lines
modified:src/internal.ts+1 added
6 unmodified lines
7export * from "./core/scope"8export * from "./core/finalize"9export * from "./core/proxy"10export * from "./core/immerClass"11export * from "./core/current"
modified:website/i18n/en.json+12 added-2 removed
14 unmodified lines
15 "built-with": {16 "title": "Built with Immer"17 },18 "complex-objects": {19 "title": "Working with Map, Set and classes"19 "title": "Classes"20 },21 "current": {22 "title": "Extracting the current state from a draft",23 "sidebar_label": "Current"24 },25 "curried-produce": {26 "title": "Curried producers"27 },28 "example-reducer": {
15 unmodified lines
44 "introduction": {45 "title": "Introduction to Immer",46 "sidebar_label": "Introduction"47 },48 "map-set": {49 "title": "Map and Set"50 },51 "original": {45 "title": "Extracting the original object from a proxied instance",52 "title": "Extracting the original state from a draft",53 "sidebar_label": "Original"54 },55 "patches": {56 "title": "Patches"
18 unmodified lines
75 },76 "typescript": {77 "title": "Using TypeScript or Flow",78 "sidebar_label": "TypeScript / Flow"79 },80 "update-patterns": {81 "title": "Update patterns"82 }83 },84 "links": {85 "Documentation": "Documentation",
15 unmodified lines
modified:website/sidebars.json+2 added-2 removed
1{2 "Immer": {3 "Basics": ["introduction", "installation", "produce", "curried-produce", "example-reducer", "example-setstate"],4 "Advanced Features": ["api", "typescript", "return", "patches", "freezing", "original", "async", "complex-objects"],3 "Basics": ["introduction", "installation", "produce", "curried-produce", "example-reducer", "example-setstate", "update-patterns"],4 "Advanced Features": ["api", "map-set", "complex-objects", "current", "original", "patches", "freezing", "return", "async", "typescript"],5 "Resources": ["performance", "resources", "faq", "pitfalls", "built-with", "support"]6 }7}
modified:jest.config.js+2 added-1 removed
3 unmodified lines
4 __DEV__: true,5 "ts-jest": {6 tsConfig: {7 noUnusedLocals: false8 }8 },9 disableSourceMapSupport: true10 }11 },12 preset: "ts-jest/presets/js-with-ts",13 testEnvironment: "node",
2 unmodified lines
modified:package.json+2 added-2 removed
1{2 "name": "immer",3 "version": "6.0.0-alpha.4",3 "version": "7.0.0-beta.0",4 "description": "Create your next immutable state by mutating the current one",5 "main": "dist/index.js",6 "module": "dist/immer.esm.js",7 "umd:main": "dist/immer.umd.production.min.js",
83 unmodified lines
91 "semantic-release": "^17.0.2",92 "spec.ts": "^1.1.0",93 "ts-jest": "^25.2.0",94 "tsdx": "^0.12.3",95 "typescript": "^3.7.3",95 "typescript": "^3.9.3",96 "webpack": "^4.41.6",97 "webpack-cli": "^3.3.11"98 }99}
modified:yarn.lock+5 added
11699 unmodified lines
11700 version "3.7.5"11701 resolved "https://registry.yarnpkg.com/typescript/-/typescript-3.7.5.tgz#0692e21f65fd4108b9330238aac11dd2e177a1ae"11702 integrity sha512-/P5lkRXkWHNAbcJIiHPfRoKqyd7bsyCma1hZNUGfn20qm64T6ZBlrzprymeu918H+mB/0rIg2gGK/BXkhhYgBw==1170311704typescript@^3.9.3:11705 version "3.9.3"11706 resolved "https://registry.yarnpkg.com/typescript/-/typescript-3.9.3.tgz#d3ac8883a97c26139e42df5e93eeece33d610b8a"11707 integrity sha512-D/wqnB2xzNFIcoBG9FG8cXRDjiqSTbG2wd8DMZeQyJlP1vfTkIxH4GKveWaEBYySKIg+USu+E+EDIR47SqnaMQ==1170811709uglify-js@^3.1.4:11710 version "3.7.7"11711 resolved "https://registry.yarnpkg.com/uglify-js/-/uglify-js-3.7.7.tgz#21e52c7dccda80a53bf7cde69628a7e511aec9c9"11712 integrity sha512-FeSU+hi7ULYy6mn8PKio/tXsdSXN35lm4KgV2asx00kzrLU9Pi3oAslcJT70Jdj7PHX29gGUPOT6+lXGBbemhA==
738 unmodified lines