Skip to content
Myr

feat: added first class support for `Map` and `Set`

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

BREAKING CHANGE: Maps and Sets are treated differently now; they will no longer directly mutated when updated inside a draft This release introduces first class support for Maps and Sets! Some things to keep in mind: * Inside recipes, you can directly modify Maps and Sets with methods like `add`, `set`, `delete` and `clear` * Those methods do mutate draft Maps and Sets, but won't actually change their originals! * Immer does not polyfill Map and Set automatically in environments where those aren't available out of the box * Maps and Sets are supported both in ES5 and Proxy mode * If `autoFreeze` is enabled, the maps and sets returned from a producer will be artificially frozen by making their mutative APIs unusable * Non primitive keys for Maps, and non primitive values for Sets are supported. However, we strongly recommend to not combine non-primitive keys to Maps with patches, for reasons expressed below. Open questions * TypeScript support for storing immutable types inside Maps and Sets, and converting them to `Draft`'s, is limited, see #448 for details * Since JSON-patch standard doesn't offer support for Sets or Maps, it is not entirely clear how mutations to those are best described by patches, so this might be refined in the future. See also #450 Credits to @runnez, @aigoncharov and @aleclarson for making this happen!

authored by Michel Weststrate · committed by GitHub · parents 09d37ce, 0f4fe3f · Browse files · 33 files+2527 added−478 removed
This commit

State

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

Diff stats

33 files+2527 added−478 removed

  • tests:+1529 added−79 removed
  • other:+998 added−399 removed

33 files+2527 added−478 removed

modified:__tests__/__snapshots__/base.js.snap+282 added
153 unmodified lines
154155exports[`base functionality - proxy (no freeze) throws when Object.setPrototypeOf() is used on a draft 1`] = `"Object.setPrototypeOf() cannot be used on an Immer draft"`;156157exports[`base functionality - proxy (no freeze) throws when the draft is modified and another object is returned 1`] = `"An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft."`;158159exports[`complex nesting map / set / object modify deep object 1`] = `160Object {161 "map": Map {162 "set1" => Set {163 Object {164 "a": 2,165 },166 Object {167 "b": 2,168 },169 },170 "set2" => Set {171 Object {172 "c": 3,173 },174 },175 },176}177`;178179exports[`complex nesting map / set / object modify deep object 2`] = `180Array [181 Object {182 "op": "remove",183 "path": Array [184 "map",185 "set1",186 0,187 ],188 "value": Object {189 "a": 1,190 },191 },192 Object {193 "op": "add",194 "path": Array [195 "map",196 "set1",197 0,198 ],199 "value": Object {200 "a": 2,201 },202 },203]204`;205206exports[`complex nesting map / set / object modify deep object 3`] = `207Object {208 "map": Map {209 "set1" => Set {210 Object {211 "a": 2,212 },213 Object {214 "b": 2,215 },216 },217 "set2" => Set {218 Object {219 "c": 3,220 },221 },222 },223}224`;225226exports[`complex nesting map / set / object modify deep object 4`] = `227Array [228 Object {229 "op": "remove",230 "path": Array [231 "map",232 "set1",233 0,234 ],235 "value": Object {236 "a": 1,237 },238 },239 Object {240 "op": "add",241 "path": Array [242 "map",243 "set1",244 0,245 ],246 "value": Object {247 "a": 2,248 },249 },250]251`;252253exports[`complex nesting map / set / object modify deep object 5`] = `254Object {255 "map": Map {256 "set1" => Set {257 Object {258 "a": 2,259 },260 Object {261 "b": 2,262 },263 },264 "set2" => Set {265 Object {266 "c": 3,267 },268 },269 },270}271`;272273exports[`complex nesting map / set / object modify deep object 6`] = `274Array [275 Object {276 "op": "remove",277 "path": Array [278 "map",279 "set1",280 0,281 ],282 "value": Object {283 "a": 1,284 },285 },286 Object {287 "op": "add",288 "path": Array [289 "map",290 "set1",291 0,292 ],293 "value": Object {294 "a": 2,295 },296 },297]298`;299300exports[`complex nesting map / set / object modify deep object 7`] = `301Object {302 "map": Map {303 "set1" => Set {304 Object {305 "a": 2,306 },307 Object {308 "b": 2,309 },310 },311 "set2" => Set {312 Object {313 "c": 3,314 },315 },316 },317}318`;319320exports[`complex nesting map / set / object modify deep object 8`] = `321Array [322 Object {323 "op": "remove",324 "path": Array [325 "map",326 "set1",327 0,328 ],329 "value": Object {330 "a": 1,331 },332 },333 Object {334 "op": "add",335 "path": Array [336 "map",337 "set1",338 0,339 ],340 "value": Object {341 "a": 2,342 },343 },344]345`;346347exports[`complex nesting map / set / object modify deep object 9`] = `348Object {349 "map": Map {350 "set1" => Set {351 Object {352 "a": 2,353 },354 Object {355 "b": 2,356 },357 },358 "set2" => Set {359 Object {360 "c": 3,361 },362 },363 },364}365`;366367exports[`complex nesting map / set / object modify deep object 10`] = `368Array [369 Object {370 "op": "remove",371 "path": Array [372 "map",373 "set1",374 0,375 ],376 "value": Object {377 "a": 1,378 },379 },380 Object {381 "op": "add",382 "path": Array [383 "map",384 "set1",385 0,386 ],387 "value": Object {388 "a": 2,389 },390 },391]392`;393394exports[`complex nesting map / set / object modify deep object 11`] = `395Object {396 "map": Map {397 "set1" => Set {398 Object {399 "a": 2,400 },401 Object {402 "b": 2,403 },404 },405 "set2" => Set {406 Object {407 "c": 3,408 },409 },410 },411}412`;413414exports[`complex nesting map / set / object modify deep object 12`] = `415Array [416 Object {417 "op": "remove",418 "path": Array [419 "map",420 "set1",421 0,422 ],423 "value": Object {424 "a": 1,425 },426 },427 Object {428 "op": "add",429 "path": Array [430 "map",431 "set1",432 0,433 ],434 "value": Object {435 "a": 2,436 },437 },438]439`;
modified:__tests__/__snapshots__/hooks.js.snap+212 added
1// Jest Snapshot v1, https://goo.gl/fbAQLP23exports[`hooks (es5) - onAssign() when draft is a Map assign 1`] = `4Array [5 Array [6 "a",7 10,8 ],9 Array [10 Object {11 "prop": "val1",12 },13 11,14 ],15]16`;1718exports[`hooks (es5) - onAssign() when draft is a Map nested assignments 1`] = `19Array [20 Array [21 "b",22 2,23 ],24 Array [25 Object {26 "prop": "val1",27 },28 Map {29 "b" => 2,30 "d" => 1,31 },32 ],33 Array [34 "a",35 Map {36 Object {37 "prop": "val1",38 } => Map {39 "b" => 2,40 "d" => 1,41 },42 },43 ],44]45`;4647exports[`hooks (es5) - onAssign() when draft is a Set assign 1`] = `48Array [49 Array [50 "a",51 Set {52 1,53 2,54 3,55 4,56 },57 ],58]59`;6061exports[`hooks (es5) - onAssign() when draft is a Set delete 1`] = `62Array [63 Array [64 "a",65 Set {66 2,67 3,68 },69 ],70]71`;7273exports[`hooks (es5) - onAssign() when draft is a Set nested assignments 1`] = `74Array [75 Array [76 "a",77 Set {78 "a",79 Set {80 1,81 2,82 },83 },84 ],85]86`;8788exports[`hooks (es5) - onAssign() when draft is an array assign 1`] = `89Array [90 Array [91 0,
100 unmodified lines
192 ],193]194`;195196exports[`hooks (es5) - onDelete() when draft is a Map - delete 1`] = `197Array [198 Array [199 "a",200 ],201 Array [202 Object {203 "prop": "val1",204 },205 ],206]207`;208209exports[`hooks (es5) - onDelete() when draft is a Map - nested deletions 1`] = `210Array [211 Array [212 "b",213 ],214]215`;216217exports[`hooks (es5) - onDelete() when draft is an array - length = 0 1`] = `218Array [219 Array [220 0,
35 unmodified lines
256 ],257]258`;259260exports[`hooks (proxy) - onAssign() when draft is a Map assign 1`] = `261Array [262 Array [263 "a",264 10,265 ],266 Array [267 Object {268 "prop": "val1",269 },270 11,271 ],272]273`;274275exports[`hooks (proxy) - onAssign() when draft is a Map nested assignments 1`] = `276Array [277 Array [278 "b",279 2,280 ],281 Array [282 Object {283 "prop": "val1",284 },285 Map {286 "b" => 2,287 "d" => 1,288 },289 ],290 Array [291 "a",292 Map {293 Object {294 "prop": "val1",295 } => Map {296 "b" => 2,297 "d" => 1,298 },299 },300 ],301]302`;303304exports[`hooks (proxy) - onAssign() when draft is a Set assign 1`] = `305Array [306 Array [307 "a",308 Set {309 1,310 2,311 3,312 4,313 },314 ],315]316`;317318exports[`hooks (proxy) - onAssign() when draft is a Set delete 1`] = `319Array [320 Array [321 "a",322 Set {323 2,324 3,325 },326 ],327]328`;329330exports[`hooks (proxy) - onAssign() when draft is a Set nested assignments 1`] = `331Array [332 Array [333 "a",334 Set {335 "a",336 Set {337 1,338 2,339 },340 },341 ],342]343`;344345exports[`hooks (proxy) - onAssign() when draft is an array assign 1`] = `346Array [347 Array [348 0,
100 unmodified lines
449 ],450]451`;452453exports[`hooks (proxy) - onDelete() when draft is a Map - delete 1`] = `454Array [455 Array [456 "a",457 ],458 Array [459 Object {460 "prop": "val1",461 },462 ],463]464`;465466exports[`hooks (proxy) - onDelete() when draft is a Map - nested deletions 1`] = `467Array [468 Array [469 "b",470 ],471]472`;473474exports[`hooks (proxy) - onDelete() when draft is an array - length = 0 1`] = `Array []`;475476exports[`hooks (proxy) - onDelete() when draft is an array - pop 1`] = `477Array [
32 unmodified lines
modified:__tests__/base.js+488 added-4 removed
1"use strict"2import {Immer, nothing, original, isDraft, immerable} from "../src/index"3import {each, shallowCopy, isEnumerable} from "../src/common"3import {each, shallowCopy, isEnumerable, DRAFT_STATE} from "../src/common"4import deepFreeze from "deep-freeze"5import cloneDeep from "lodash.clonedeep"6import * as lodash from "lodash"7
11 unmodified lines
19runBaseTest("es5 (autofreeze)(patch listener)", false, true, true)2021function runBaseTest(name, useProxies, autoFreeze, useListener) {22 const listener = useListener ? function() {} : undefined23 const {produce} = createPatchedImmer({23 const {produce, produceWithPatches} = createPatchedImmer({24 useProxies,25 autoFreeze26 })27
2 unmodified lines
30 function createPatchedImmer(options) {31 const immer = new Immer(options)3233 const {produce} = immer34 immer.produce = (...args) =>35 typeof args[1] === "function" && args.length < 334 immer.produce = function(...args) {35 return typeof args[1] === "function" && args.length < 336 ? produce(...args, listener)37 : produce(...args)38 }3940 return immer41 }42
256 unmodified lines
299 })300 }301 })302303 describe("map drafts", () => {304 it("supports key access", () => {305 const value = baseState.aMap.get("jedi")306 const nextState = produce(baseState, s => {307 expect(s.aMap.get("jedi")).toEqual(value)308 })309 expect(nextState).toBe(baseState)310 })311312 it("supports key access for non-primitive keys", () => {313 const key = {prop: "val"}314 const base = new Map([[key, {id: 1, a: 1}]])315 const value = base.get(key)316 const nextState = produce(base, s => {317 expect(s.get(key)).toEqual(value)318 })319 expect(nextState).toBe(base)320 })321322 it("supports iteration", () => {323 const base = new Map([324 ["first", {id: 1, a: 1}],325 ["second", {id: 2, a: 1}]326 ])327 const findById = (map, id) => {328 for (const [, item] of map) {329 if (item.id === id) return item330 }331 return null332 }333 const result = produce(base, draft => {334 const obj1 = findById(draft, 1)335 const obj2 = findById(draft, 2)336 obj1.a = 2337 obj2.a = 2338 })339 expect(result).not.toBe(base)340 expect(result.get("first").a).toEqual(2)341 expect(result.get("second").a).toEqual(2)342 })343344 it("supports 'entries'", () => {345 const base = new Map([346 ["first", {id: 1, a: 1}],347 ["second", {id: 2, a: 1}]348 ])349 const findById = (map, id) => {350 for (const [, item] of map.entries()) {351 if (item.id === id) return item352 }353 return null354 }355 const result = produce(base, draft => {356 const obj1 = findById(draft, 1)357 const obj2 = findById(draft, 2)358 obj1.a = 2359 obj2.a = 2360 })361 expect(result).not.toBe(base)362 expect(result.get("first").a).toEqual(2)363 expect(result.get("second").a).toEqual(2)364 })365366 it("supports 'values'", () => {367 const base = new Map([368 ["first", {id: 1, a: 1}],369 ["second", {id: 2, a: 1}]370 ])371 const findById = (map, id) => {372 for (const item of map.values()) {373 if (item.id === id) return item374 }375 return null376 }377 const result = produce(base, draft => {378 const obj1 = findById(draft, 1)379 const obj2 = findById(draft, 2)380 obj1.a = 2381 obj2.a = 2382 })383 expect(result).not.toBe(base)384 expect(result.get("first").a).toEqual(2)385 expect(result.get("second").a).toEqual(2)386 })387388 it("supports 'keys", () => {389 const base = new Map([["first", Symbol()], ["second", Symbol()]])390 const result = produce(base, draft => {391 expect([...draft.keys()]).toEqual(["first", "second"])392 draft.set("third", Symbol())393 expect([...draft.keys()]).toEqual(["first", "second", "third"])394 })395 })396397 it("supports forEach", () => {398 const key1 = {prop: "val1"}399 const key2 = {prop: "val2"}400 const base = new Map([401 ["first", {id: 1, a: 1}],402 ["second", {id: 2, a: 1}],403 [key1, {id: 3, a: 1}],404 [key2, {id: 4, a: 1}]405 ])406 const result = produce(base, draft => {407 let sum1 = 0408 draft.forEach(({a}) => {409 sum1 += a410 })411 expect(sum1).toBe(4)412 let sum2 = 0413 draft.get("first").a = 10414 draft.get("second").a = 20415 draft.get(key1).a = 30416 draft.get(key2).a = 40417 draft.forEach(({a}) => {418 sum2 += a419 })420 expect(sum2).toBe(100)421 })422 expect(result).not.toBe(base)423 expect(base.get("first").a).toEqual(1)424 expect(base.get("second").a).toEqual(1)425 expect(base.get(key1).a).toEqual(1)426 expect(base.get(key2).a).toEqual(1)427 expect(result.get("first").a).toEqual(10)428 expect(result.get("second").a).toEqual(20)429 expect(result.get(key1).a).toEqual(30)430 expect(result.get(key2).a).toEqual(40)431 })432433 it("supports forEach mutation", () => {434 const base = new Map([435 ["first", {id: 1, a: 1}],436 ["second", {id: 2, a: 1}]437 ])438 const result = produce(base, draft => {439 draft.forEach(item => {440 item.a = 100441 })442 })443 expect(result).not.toBe(base)444 expect(result.get("first").a).toEqual(100)445 expect(result.get("second").a).toEqual(100)446 })447448 it("can assign by key", () => {449 const nextState = produce(baseState, s => {450 // Map.prototype.set should return the Map itself451 const res = s.aMap.set("force", true)452 expect(res).toBe(s.aMap[DRAFT_STATE].draft)453 })454 expect(nextState).not.toBe(baseState)455 expect(nextState.aMap).not.toBe(baseState.aMap)456 expect(nextState.aMap.get("force")).toEqual(true)457 })458459 it("can assign by a non-primitive key", () => {460 const key = {prop: "val"}461 const value = {id: 1, a: 1}462 const base = new Map([[key, value]])463 const nextState = produce(base, s => {464 s.set(key, true)465 })466 expect(nextState).not.toBe(base)467 expect(base.get(key)).toEqual(value)468 expect(nextState.get(key)).toEqual(true)469 })470471 it("state stays the same if the the same item is assigned by key", () => {472 const nextState = produce(baseState, s => {473 s.aMap.set("jediTotal", 42)474 })475 expect(nextState).toBe(baseState)476 expect(nextState.aMap).toBe(baseState.aMap)477 })478479 it("returns 'size'", () => {480 const nextState = produce(baseState, s => {481 s.aMap.set("newKey", true)482 expect(s.aMap.size).toBe(baseState.aMap.size + 1)483 })484 expect(nextState).not.toBe(baseState)485 expect(nextState.aMap).not.toBe(baseState.aMap)486 expect(nextState.aMap.get("newKey")).toEqual(true)487 expect(nextState.aMap.size).toEqual(baseState.aMap.size + 1)488 })489490 it("can use 'delete' to remove items", () => {491 const nextState = produce(baseState, s => {492 expect(s.aMap.has("jedi")).toBe(true)493 s.aMap.delete("jedi")494 expect(s.aMap.has("jedi")).toBe(false)495 })496 expect(nextState.aMap).not.toBe(baseState.aMap)497 expect(nextState.aMap.size).toBe(baseState.aMap.size - 1)498 expect(baseState.aMap.has("jedi")).toBe(true)499 expect(nextState.aMap.has("jedi")).toBe(false)500 })501502 it("can use 'clear' to remove items", () => {503 const nextState = produce(baseState, s => {504 expect(s.aMap.size).not.toBe(0)505 s.aMap.clear()506 expect(s.aMap.size).toBe(0)507 })508 expect(nextState.aMap).not.toBe(baseState.aMap)509 expect(baseState.aMap.size).not.toBe(0)510 expect(nextState.aMap.size).toBe(0)511 })512513 it("support 'has'", () => {514 const nextState = produce(baseState, s => {515 expect(s.aMap.has("newKey")).toBe(false)516 s.aMap.set("newKey", true)517 expect(s.aMap.has("newKey")).toBe(true)518 })519 expect(nextState).not.toBe(baseState)520 expect(nextState.aMap).not.toBe(baseState.aMap)521 expect(baseState.aMap.has("newKey")).toBe(false)522 expect(nextState.aMap.has("newKey")).toBe(true)523 })524525 it("supports nested maps", () => {526 const base = new Map([["first", new Map([["second", {prop: "test"}]])]])527 const result = produce(base, draft => {528 draft.get("first").get("second").prop = "test1"529 })530 expect(result).not.toBe(base)531 expect(result.get("first")).not.toBe(base.get("first"))532 expect(result.get("first").get("second")).not.toBe(533 base.get("first").get("second")534 )535 expect(base.get("first").get("second").prop).toBe("test")536 expect(result.get("first").get("second").prop).toBe("test1")537 })538 })539540 describe("set drafts", () => {541 it("supports iteration", () => {542 const base = new Set([{id: 1, a: 1}, {id: 2, a: 1}])543 const findById = (set, id) => {544 for (const item of set) {545 if (item.id === id) return item546 }547 return null548 }549 const result = produce(base, draft => {550 const obj1 = findById(draft, 1)551 const obj2 = findById(draft, 2)552 obj1.a = 2553 obj2.a = 2554 })555 expect(result).not.toBe(base)556 expect(base).toEqual(new Set([{id: 1, a: 1}, {id: 2, a: 1}]))557 expect(result).toEqual(new Set([{id: 1, a: 2}, {id: 2, a: 2}]))558 })559560 it("supports 'entries'", () => {561 const base = new Set([{id: 1, a: 1}, {id: 2, a: 1}])562 const findById = (set, id) => {563 for (const [item1, item2] of set.entries()) {564 expect(item1).toBe(item2)565 if (item1.id === id) return item1566 }567 return null568 }569 const result = produce(base, draft => {570 const obj1 = findById(draft, 1)571 const obj2 = findById(draft, 2)572 obj1.a = 2573 obj2.a = 2574 })575 expect(result).not.toBe(base)576 expect(base).toEqual(new Set([{id: 1, a: 1}, {id: 2, a: 1}]))577 expect(result).toEqual(new Set([{id: 1, a: 2}, {id: 2, a: 2}]))578 })579580 it("supports 'values'", () => {581 const base = new Set([{id: 1, a: 1}, {id: 2, a: 1}])582 const findById = (set, id) => {583 for (const item of set.values()) {584 if (item.id === id) return item585 }586 return null587 }588 const result = produce(base, draft => {589 const obj1 = findById(draft, 1)590 const obj2 = findById(draft, 2)591 obj1.a = 2592 obj2.a = 2593 })594 expect(result).not.toBe(base)595 expect(base).toEqual(new Set([{id: 1, a: 1}, {id: 2, a: 1}]))596 expect(result).toEqual(new Set([{id: 1, a: 2}, {id: 2, a: 2}]))597 })598599 it("supports 'keys'", () => {600 const base = new Set([{id: 1, a: 1}, {id: 2, a: 1}])601 const findById = (set, id) => {602 for (const item of set.keys()) {603 if (item.id === id) return item604 }605 return null606 }607 const result = produce(base, draft => {608 const obj1 = findById(draft, 1)609 const obj2 = findById(draft, 2)610 obj1.a = 2611 obj2.a = 2612 })613 expect(result).not.toBe(base)614 expect(base).toEqual(new Set([{id: 1, a: 1}, {id: 2, a: 1}]))615 expect(result).toEqual(new Set([{id: 1, a: 2}, {id: 2, a: 2}]))616 })617618 it("supports forEach with mutation after reads", () => {619 const base = new Set([{id: 1, a: 1}, {id: 2, a: 2}])620 const result = produce(base, draft => {621 let sum1 = 0622 draft.forEach(({a}) => {623 sum1 += a624 })625 expect(sum1).toBe(3)626 let sum2 = 0627 draft.forEach(item => {628 item.a += 10629 sum2 += item.a630 })631 expect(sum2).toBe(23)632 })633 expect(result).not.toBe(base)634 expect(base).toEqual(new Set([{id: 1, a: 1}, {id: 2, a: 2}]))635 expect(result).toEqual(new Set([{id: 1, a: 11}, {id: 2, a: 12}]))636 })637638 it("state stays the same if the same item is added", () => {639 const nextState = produce(baseState, s => {640 s.aSet.add("Luke")641 })642 expect(nextState).toBe(baseState)643 expect(nextState.aSet).toBe(baseState.aSet)644 })645646 it("can add new items", () => {647 const nextState = produce(baseState, s => {648 // Set.prototype.set should return the Set itself649 const res = s.aSet.add("force")650 expect(res).toBe(s.aSet[DRAFT_STATE].draft)651 })652 expect(nextState).not.toBe(baseState)653 expect(nextState.aSet).not.toBe(baseState.aSet)654 expect(baseState.aSet.has("force")).toBe(false)655 expect(nextState.aSet.has("force")).toBe(true)656 })657658 it("returns 'size'", () => {659 const nextState = produce(baseState, s => {660 s.aSet.add("newKey")661 expect(s.aSet.size).toBe(baseState.aSet.size + 1)662 })663 expect(nextState).not.toBe(baseState)664 expect(nextState.aSet).not.toBe(baseState.aSet)665 expect(nextState.aSet.has("newKey")).toBe(true)666 expect(nextState.aSet.size).toEqual(baseState.aSet.size + 1)667 })668669 it("can use 'delete' to remove items", () => {670 const nextState = produce(baseState, s => {671 expect(s.aSet.has("Luke")).toBe(true)672 s.aSet.delete("Luke")673 expect(s.aSet.has("Luke")).toBe(false)674 })675 expect(nextState.aSet).not.toBe(baseState.aSet)676 expect(nextState.aSet.size).toBe(baseState.aSet.size - 1)677 expect(baseState.aSet.has("Luke")).toBe(true)678 expect(nextState.aSet.has("Luke")).toBe(false)679 })680681 it("can use 'clear' to remove items", () => {682 const nextState = produce(baseState, s => {683 expect(s.aSet.size).not.toBe(0)684 s.aSet.clear()685 expect(s.aSet.size).toBe(0)686 })687 expect(nextState.aSet).not.toBe(baseState.aSet)688 expect(baseState.aSet.size).not.toBe(0)689 expect(nextState.aSet.size).toBe(0)690 })691692 it("supports 'has'", () => {693 const nextState = produce(baseState, s => {694 expect(s.aSet.has("newKey")).toBe(false)695 s.aSet.add("newKey")696 expect(s.aSet.has("newKey")).toBe(true)697 })698 expect(nextState).not.toBe(baseState)699 expect(nextState.aSet).not.toBe(baseState.aSet)700 expect(baseState.aSet.has("newKey")).toBe(false)701 expect(nextState.aSet.has("newKey")).toBe(true)702 })703704 it("supports nested sets", () => {705 const base = new Set([new Set(["Serenity"])])706 const result = produce(base, draft => {707 draft.forEach(nestedItem => nestedItem.add("Firefly"))708 })709 expect(result).not.toBe(base)710 expect(base).toEqual(new Set([new Set(["Serenity"])]))711 expect(result).toEqual(new Set([new Set(["Serenity", "Firefly"])]))712 })713 })714715 it("supports `immerable` symbol on constructor", () => {716 class One {}717 One[immerable] = true718 const baseState = new One()
788 unmodified lines
1507 function createBaseState() {1508 const data = {1509 anInstance: new Foo(),1510 anArray: [3, 2, {c: 3}, 1],1511 aMap: new Map([1512 ["jedi", {name: "Luke", skill: 10}],1513 ["jediTotal", 42],1514 ["force", "these aren't the droids you're looking for"]1515 ]),1516 aSet: new Set([1517 "Luke",1518 42,1519 {1520 jedi: "Yoda"1521 }1522 ]),1523 aProp: "hi",1524 anObject: {1525 nested: {1526 yummie: true
44 unmodified lines
1571 const array = produce([], state => state)1572 expect(isDraft(array)).toBeFalsy()1573 })1574 })15751576 describe(`complex nesting map / set / object`, () => {1577 const a = {a: 1}1578 const b = {b: 2}1579 const c = {c: 3}1580 const set1 = new Set([a, b])1581 const set2 = new Set([c])1582 const map = new Map([["set1", set1], ["set2", set2]])1583 const base = {map}15841585 function first(set) {1586 return Array.from(set.values())[0]1587 }15881589 function second(set) {1590 return Array.from(set.values())[1]1591 }15921593 test(`modify deep object`, () => {1594 const [res, patches] = produceWithPatches(base, draft => {1595 const v = first(draft.map.get("set1"))1596 expect(original(v)).toBe(a)1597 expect(v).toEqual(a)1598 expect(v).not.toBe(a)1599 v.a++1600 })1601 expect(res).toMatchSnapshot()1602 expect(patches).toMatchSnapshot()1603 expect(a.a).toBe(1)1604 expect(base.map.get("set1")).toBe(set1)1605 expect(first(base.map.get("set1"))).toBe(a)1606 expect(res).not.toBe(base)1607 expect(res.map).not.toBe(base.map)1608 expect(res.map.get("set1")).not.toBe(base.map.get("set1"))1609 expect(second(base.map.get("set1"))).toBe(b)1610 expect(base.map.get("set2")).toBe(set2)1611 expect(first(res.map.get("set1"))).toEqual({a: 2})1612 })16131614 test(`modify deep object - keep value`, () => {1615 const [res, patches] = produceWithPatches(base, draft => {1616 const v = first(draft.map.get("set1"))1617 expect(original(v)).toBe(a)1618 expect(v).toEqual(a)1619 expect(v).not.toBe(a)1620 v.a = 1 // same value1621 })1622 expect(a.a).toBe(1)1623 expect(base.map.get("set1")).toBe(set1)1624 expect(first(base.map.get("set1"))).toBe(a)1625 expect(res).toBe(base)1626 expect(res.map).toBe(base.map)1627 expect(res.map.get("set1")).toBe(base.map.get("set1"))1628 expect(first(res.map.get("set1"))).toBe(a)1629 expect(second(base.map.get("set1"))).toBe(b)1630 expect(base.map.get("set2")).toBe(set2)1631 expect(patches.length).toBe(0)1632 })1633 })1634}16351636function testObjectTypes(produce) {1637 class Foo {
115 unmodified lines
modified:__tests__/frozen.js+39 added
modified:__tests__/hooks.js+137 added-3 removed
1"use strict"2import {Immer, setUseProxies} from "../src/index"3import matchers from "expect/build/matchers"4import {isSet} from "../src/common"56describe("hooks (proxy) -", () => createHookTests(true))7describe("hooks (es5) -", () => createHookTests(false))8
109 unmodified lines
118 // properties always come first in their ancestor chain.119 expect(calls).toEqual(["b", "d", "c", "x"])120 })121 })122123 describe("when draft is a Map", () => {124 test("assign", () => {125 const key1 = {prop: "val1"}126 const key2 = {prop: "val2"}127 produce(new Map([["a", 0], [key1, 1], [key2, 2]]), s => {128 s.set("a", 10)129 s.set(key1, 11)130 })131 expectCalls(onAssign)132 })133 test("assign (no change)", () => {134 produce(new Map([["a", 0]]), s => {135 s.set("a", 0)136 })137 expect(onAssign).not.toBeCalled()138 })139 test("delete", () => {140 produce(new Map([["a", 0]]), s => {141 s.delete("a")142 })143 expect(onAssign).not.toBeCalled()144 })145 test("nested assignments", () => {146 const key1 = {prop: "val1"}147 produce(148 new Map([149 ["a", new Map([[key1, new Map([["b", 1], ["c", 1], ["d", 1]])]])]150 ]),151 s => {152 const nested = s.get("a").get(key1)153 nested.set("b", 2)154 nested.delete("c")155 nested.set("d", 1) // no-op156 }157 )158 expectCalls(onAssign)159 })160 })161162 describe("when draft is a Set", () => {163 test("assign", () => {164 produce({a: new Set([1, 2, 3])}, s => {165 s.a.add(4)166 })167 expectCalls(onAssign)168 })169 test("assign (no change)", () => {170 produce({a: new Set([1, 2, 3])}, s => {171 s.a.add(3)172 })173 expect(onAssign).not.toBeCalled()174 })175 // Any mutation of a Set results in a new assignment. Including deletes.176 test("delete", () => {177 produce({a: new Set([1, 2, 3])}, s => {178 s.a.delete(1)179 })180 expectCalls(onAssign)181 })182 test("nested assignments", () => {183 const val1 = {prop: "val1"}184 produce({a: new Set(["a", new Set([val1, 1])])}, s => {185 let nested186 s.a.forEach(value => {187 if (isSet(value)) {188 nested = value189 }190 })191 nested.add(2)192 nested.delete(val1)193 nested.add(1) // no-op194 })195 expectCalls(onAssign)196 })197 })198 })199200 describe("onDelete()", () => {201 useSharedTests(() => onDelete)
37 unmodified lines
239 })240 expectCalls(onDelete)241 })242 })243244 describe("when draft is a Map -", () => {245 test("delete", () => {246 const key1 = {prop: "val1"}247 const key2 = {prop: "val2"}248 produce(new Map([["a", 0], [key1, 1], [key2, 2]]), s => {249 s.delete("a")250 s.delete(key1)251 })252 expectCalls(onDelete)253 })254 test("delete (no change)", () => {255 produce(new Map(), s => {256 s.delete("a")257 })258 expect(onDelete).not.toBeCalled()259 })260 test("nested deletions", () => {261 const key1 = {prop: "val1"}262 produce(new Map([["a", new Map([[key1, new Map([["b", 1]])]])]]), s => {263 s.get("a")264 .get(key1)265 .delete("b")266 })267 expectCalls(onDelete)268 })269 })270271 describe("when draft is a Set -", () => {272 test("delete", () => {273 produce({a: new Set([1])}, s => {274 s.a.delete(1)275 })276 expect(onDelete).not.toBeCalled()277 })278 })279 })280281 describe("onCopy()", () => {169 useSharedTests(() => onCopy)170 it("is called in the right order", () => {171 const calls = []282 let calls283 beforeEach(() => {284 calls = []285 onCopy.mockImplementation(s => {286 calls.push(s.base)287 })288 })289290 useSharedTests(() => onCopy)291 it("is called in the right order for objects", () => {292 const base = {a: {b: {c: 1}}}293 produce(base, s => {294 delete s.a.b.c295 })296 expect(calls).toShallowEqual([base.a.b, base.a, base])297 })298299 it("is called in the right order for Maps", () => {300 const base = new Map([["a", new Map([["b", 0]])]])301 produce(base, s => {302 s.get("a").delete("b")303 })304 expect(calls).toShallowEqual([base.get("a"), base])305 })306307 it("is called in the right order for Sets", () => {308 const item1 = {a: 0}309 const base = new Set([item1])310 produce(base, s => {311 s.forEach(item => item.a++)312 })313 expect(calls).toShallowEqual([item1, base])314 })315 })316317 function useSharedTests(getHook) {318 it("is called before the parent is frozen", () => {
43 unmodified lines
modified:__tests__/patch.js+283 added
138 unmodified lines
139 [{op: "replace", path: ["x", 0, "y"], value: 5}]140 )141})142143describe("simple assignment - 4", () => {144 runPatchTest(145 new Map([["x", {y: 4}]]),146 d => {147 d.get("x").y++148 },149 [{op: "replace", path: ["x", "y"], value: 5}],150 [{op: "replace", path: ["x", "y"], value: 4}]151 )152})153154describe("simple assignment - 5", () => {155 runPatchTest(156 {x: new Map([["y", 4]])},157 d => {158 d.x.set("y", 5)159 },160 [{op: "replace", path: ["x", "y"], value: 5}],161 [{op: "replace", path: ["x", "y"], value: 4}]162 )163})164165describe("simple assignment - 6", () => {166 runPatchTest(167 new Map([["x", 1]]),168 d => {169 // Map.prototype.set should return the Map itself170 const res = d.set("x", 2)171 res.set("y", 3)172 },173 [174 {op: "replace", path: ["x"], value: 2},175 {op: "add", path: ["y"], value: 3}176 ],177 [{op: "replace", path: ["x"], value: 1}, {op: "remove", path: ["y"]}]178 )179})180181describe("simple assignment - 7", () => {182 const key1 = {prop: "val1"}183 const key2 = {prop: "val2"}184 runPatchTest(185 {x: new Map([[key1, 4]])},186 d => {187 d.x.set(key1, 5)188 d.x.set(key2, 6)189 },190 [191 {op: "replace", path: ["x", key1], value: 5},192 {op: "add", path: ["x", key2], value: 6}193 ],194 [195 {op: "replace", path: ["x", key1], value: 4},196 {op: "remove", path: ["x", key2]}197 ]198 )199})200201describe("delete 1", () => {202 runPatchTest(203 {x: {y: 4}},204 d => {
2 unmodified lines
207 [{op: "remove", path: ["x"]}]208 )209})210211describe("delete 2", () => {212 runPatchTest(213 new Map([["x", 1]]),214 d => {215 d.delete("x")216 },217 [{op: "remove", path: ["x"]}],218 [{op: "add", path: ["x"], value: 1}]219 )220})221222describe("delete 3", () => {223 runPatchTest(224 {x: new Map([["y", 1]])},225 d => {226 d.x.delete("y")227 },228 [{op: "remove", path: ["x", "y"]}],229 [{op: "add", path: ["x", "y"], value: 1}]230 )231})232233describe("delete 5", () => {234 const key1 = {prop: "val1"}235 const key2 = {prop: "val2"}236 runPatchTest(237 {x: new Map([[key1, 1], [key2, 2]])},238 d => {239 d.x.delete(key1)240 d.x.delete(key2)241 },242 [{op: "remove", path: ["x", key1]}, {op: "remove", path: ["x", key2]}],243 [244 {op: "add", path: ["x", key1], value: 1},245 {op: "add", path: ["x", key2], value: 2}246 ]247 )248})249250describe("delete 6", () => {251 runPatchTest(252 new Set(["x", 1]),253 d => {254 d.delete("x")255 },256 [{op: "remove", path: [0], value: "x"}],257 [{op: "add", path: [0], value: "x"}]258 )259})260261describe("delete 7", () => {262 runPatchTest(263 {x: new Set(["y", 1])},264 d => {265 d.x.delete("y")266 },267 [{op: "remove", path: ["x", 0], value: "y"}],268 [{op: "add", path: ["x", 0], value: "y"}]269 )270})271272describe("renaming properties", () => {273 describe("nested object (no changes)", () => {274 runPatchTest(275 {a: {b: 1}},
4 unmodified lines
280 [{op: "add", path: ["x"], value: {b: 1}}, {op: "remove", path: ["a"]}]281 )282 })283284 describe("nested map (no changes)", () => {285 runPatchTest(286 new Map([["a", new Map([["b", 1]])]]),287 d => {288 d.set("x", d.get("a"))289 d.delete("a")290 },291 [292 {op: "add", path: ["x"], value: new Map([["b", 1]])},293 {op: "remove", path: ["a"]}294 ],295 [296 {op: "remove", path: ["x"]},297 {op: "add", path: ["a"], value: new Map([["b", 1]])}298 ]299 )300 })301302 describe("nested object (with changes)", () => {303 runPatchTest(304 {a: {b: 1, c: 1}},305 d => {
12 unmodified lines
318 ]319 )320 })321322 describe("nested map (with changes)", () => {323 runPatchTest(324 new Map([["a", new Map([["b", 1], ["c", 1]])]]),325 d => {326 let a = d.get("a")327 a.set("b", 2) // change328 a.delete("c") // delete329 a.set("y", 2) // add330331 // rename332 d.set("x", a)333 d.delete("a")334 },335 [336 {op: "add", path: ["x"], value: new Map([["b", 2], ["y", 2]])},337 {op: "remove", path: ["a"]}338 ],339 [340 {op: "remove", path: ["x"]},341 {op: "add", path: ["a"], value: new Map([["b", 1], ["c", 1]])}342 ]343 )344 })345346 describe("deeply nested object (with changes)", () => {347 runPatchTest(348 {a: {b: {c: 1, d: 1}}},349 d => {
11 unmodified lines
361 {op: "remove", path: ["a", "b"]}362 ]363 )364 })365366 describe("deeply nested map (with changes)", () => {367 runPatchTest(368 new Map([["a", new Map([["b", new Map([["c", 1], ["d", 1]])]])]]),369 d => {370 let b = d.get("a").get("b")371 b.set("c", 2) // change372 b.delete("d") // delete373 b.set("y", 2) // add374375 // rename376 d.get("a").set("x", b)377 d.get("a").delete("b")378 },379 [380 {381 op: "add",382 path: ["a", "x"],383 value: new Map([["c", 2], ["y", 2]])384 },385 {op: "remove", path: ["a", "b"]}386 ],387 [388 {op: "remove", path: ["a", "x"]},389 {390 op: "add",391 path: ["a", "b"],392 value: new Map([["c", 1], ["d", 1]])393 }394 ]395 )396 })397})398399describe("minimum amount of changes", () => {400 runPatchTest(
179 unmodified lines
580 ]581 )582})583584describe("sets - add - 1", () => {585 runPatchTest(586 new Set([1]),587 d => {588 d.add(2)589 },590 [{op: "add", path: [1], value: 2}],591 [{op: "remove", path: [1], value: 2}]592 )593})594595describe("sets - add, delete, add - 1", () => {596 runPatchTest(597 new Set([1]),598 d => {599 d.add(2)600 d.delete(2)601 d.add(2)602 },603 [{op: "add", path: [1], value: 2}],604 [{op: "remove", path: [1], value: 2}]605 )606})607608describe("sets - add, delete, add - 2", () => {609 runPatchTest(610 new Set([2, 1]),611 d => {612 d.add(2)613 d.delete(2)614 d.add(2)615 },616 [],617 []618 )619})620621describe("sets - mutate - 1", () => {622 const findById = (set, id) => {623 for (const item of set) {624 if (item.id === id) return item625 }626 }627 runPatchTest(628 new Set([{id: 1, val: "We"}, {id: 2, val: "will"}]),629 d => {630 const obj1 = findById(d, 1)631 const obj2 = findById(d, 2)632 obj1.val = "rock"633 obj2.val = "you"634 },635 [636 {op: "remove", path: [0], value: {id: 1, val: "We"}},637 {op: "remove", path: [1], value: {id: 2, val: "will"}},638 {op: "add", path: [0], value: {id: 1, val: "rock"}},639 {op: "add", path: [1], value: {id: 2, val: "you"}}640 ],641 [642 {op: "remove", path: [1], value: {id: 2, val: "you"}},643 {op: "remove", path: [0], value: {id: 1, val: "rock"}},644 {op: "add", path: [1], value: {id: 2, val: "will"}},645 {op: "add", path: [0], value: {id: 1, val: "We"}}646 ]647 )648})649650describe("arrays - splice should should result in remove op.", () => {651 runPatchTest(652 [1, 2],653 d => {
62 unmodified lines
716 []717 )718})719720describe("same value replacement - 5", () => {721 runPatchTest(722 new Map([["x", 3]]),723 d => {724 d.set("x", 4)725 d.set("x", 3)726 },727 [],728 []729 )730})731732describe("same value replacement - 6", () => {733 runPatchTest(734 new Set(["x", 3]),735 d => {736 d.delete("x")737 d.add("x")738 },739 [],740 []741 )742})743744describe("simple delete", () => {745 runPatchTest(746 {x: 2},747 d => {
116 unmodified lines
modified:__tests__/produce.ts+31 added
414 unmodified lines
415416 expect(queueAfter).toEqual([1, 2, 3, 4])417 expect(queueBefore).toEqual([1, 2, 3])418})419420it("works with Map and Set", () => {421 const m = new Map([["a", {x: 1}]])422 const s = new Set([{x: 2}])423424 const res1 = produce(m, draft => {425 assert(draft, _ as Map<string, {x: number}>)426 })427 assert(res1, _ as Map<string, {x: number}>)428429 const res2 = produce(s, draft => {430 assert(draft, _ as Set<{x: number}>)431 })432 assert(res2, _ as Set<{x: number}>)433})434435it("works with readonly Map and Set", () => {436 type S = {readonly x: number}437 const m = new Map<string, S>([["a", {x: 1}]])438 const s = new Set<S>([{x: 2}])439440 const res1 = produce(m, (draft: Draft<Map<string, S>>) => {441 assert(draft, _ as Map<string, {readonly x: number}>) // TODO: drop readonly in TS 3.7442 })443 assert(res1, _ as Map<string, {readonly x: number}>)444445 const res2 = produce(s, (draft: Draft<Set<S>>) => {446 assert(draft, _ as Set<{readonly x: number}>) // TODO: drop readonly in TS 3.7447 })448 assert(res2, _ as Set<{readonly x: number}>)449})
modified:__tests__/readme.js+9 added-24 removed
91 unmodified lines
92 tokenSet: new Set()93 }9495 const nextState = produce(state, draft => {96 draft.title = draft.title.toUpperCase() // let immer do its job97 // don't use the operations onSet, as that mutates the instance!98 // draft.tokenSet.add("c1342")99100 // instead: clone the set (once!)101 const newSet = new Set(draft.tokenSet)102 // mutate it once103 newSet.add("c1342")104 // update the draft with the new set105 draft.tokenSet = newSet96 draft.title = draft.title.toUpperCase()97 draft.tokenSet.add("c1342")98 })99100 expect(state).toEqual({title: "hello", tokenSet: new Set()})101 expect(nextState).toEqual({
1 unmodified line
103 tokenSet: new Set(["c1342"])104 })105 })106115 it("can deep udpate map", () => {107 it("can deep update map", () => {108 const state = {117 users: new Map([["michel", {name: "miche"}]])109 users: new Map([["michel", {name: "miche", age: 27}]])110 }111112 const nextState = produce(state, draft => {121 const newUsers = new Map(draft.users)122 // mutate the new map and set a _new_ user object123 // but leverage produce again to deeply update its contents124 newUsers.set(125 "michel",126 produce(draft.users.get("michel"), draft => {127 draft.name = "michel"128 })129 )130 draft.users = newUsers113 draft.users.get("michel").name = "michel"114 })115133 expect(state).toEqual({users: new Map([["michel", {name: "miche"}]])})116 expect(state).toEqual({117 users: new Map([["michel", {name: "miche", age: 27}]])118 })119 expect(nextState).toEqual({135 users: new Map([["michel", {name: "michel"}]])120 users: new Map([["michel", {name: "michel", age: 27}]])121 })122 })123124 it("supports immerable", () => {
66 unmodified lines
modified:__tests__/test-data.json+43 added-43 removed
1{2 "_id": "5a5e59f1bc9132a90101f521",3 "index": 0,4 "guid": "8dc96fdb-0526-4bc4-a0ef-fb08e6c06e77",5 "isActive": true,6 "balance": "$3,359.66",7 "picture": "http://placehold.it/32x32",8 "age": 40,9 "eyeColor": "blue",10 "name": "Samantha Richardson",11 "gender": "female",12 "company": "COWTOWN",13 "email": "samantharichardson@cowtown.com",14 "phone": "+1 (847) 556-2336",15 "address": "419 Bergen Street, Emison, Nebraska, 554",16 "about": "Enim magna ut do esse voluptate et commodo anim laborum proident aute. Nulla non sit in incididunt minim velit. Laboris et tempor enim cillum ex adipisicing excepteur. Dolore consectetur eiusmod eu ad eu. Veniam qui sunt est reprehenderit et ut occaecat eiusmod pariatur aliquip officia ipsum.\r\n",17 "registered": "2017-07-09T02:30:48 -02:00",18 "latitude": -38.375287,19 "longitude": -27.090184,20 "tags": ["ex", "cillum", "cillum", "Lorem", "fugiat", "dolore", "nulla", "anim", "aliqua", "sint"],21 "friends": [22 {23 "id": 0,24 "name": "Adrian Dunlap"25 },26 {27 "id": 1,28 "name": "Salinas Copeland"29 },30 {31 "id": 2,32 "name": "Doreen Emerson"33 },34 {35 "id": 3,36 "name": "Willis Long"37 },38 {39 "id": 4,40 "name": "Josefina Garza"41 }42 ],43 "greeting": "Hello, Samantha Richardson! You have 8 unread messages.",44 "favoriteFruit": "banana"2 "_id": "5a5e59f1bc9132a90101f521",3 "index": 0,4 "guid": "8dc96fdb-0526-4bc4-a0ef-fb08e6c06e77",5 "isActive": true,6 "balance": "$3,359.66",7 "picture": "http://placehold.it/32x32",8 "age": 40,9 "eyeColor": "blue",10 "name": "Samantha Richardson",11 "gender": "female",12 "company": "COWTOWN",13 "email": "samantharichardson@cowtown.com",14 "phone": "+1 (847) 556-2336",15 "address": "419 Bergen Street, Emison, Nebraska, 554",16 "about": "Enim magna ut do esse voluptate et commodo anim laborum proident aute. Nulla non sit in incididunt minim velit. Laboris et tempor enim cillum ex adipisicing excepteur. Dolore consectetur eiusmod eu ad eu. Veniam qui sunt est reprehenderit et ut occaecat eiusmod pariatur aliquip officia ipsum.\r\n",17 "registered": "2017-07-09T02:30:48 -02:00",18 "latitude": -38.375287,19 "longitude": -27.090184,20 "tags": ["ex", "cillum", "cillum", "Lorem", "fugiat", "dolore", "nulla", "anim", "aliqua", "sint"],21 "friends": [22 {23 "id": 0,24 "name": "Adrian Dunlap"25 },26 {27 "id": 1,28 "name": "Salinas Copeland"29 },30 {31 "id": 2,32 "name": "Doreen Emerson"33 },34 {35 "id": 3,36 "name": "Willis Long"37 },38 {39 "id": 4,40 "name": "Josefina Garza"41 }42 ],43 "greeting": "Hello, Samantha Richardson! You have 8 unread messages.",44 "favoriteFruit": "banana"45}
modified:__tests__/tsconfig.json+5 added-5 removed
1{2 "include": ["*", "../dist"],3 "compilerOptions": {4 "lib": ["es2015"],5 "strict": true6 }2 "include": ["*", "../dist"],3 "compilerOptions": {4 "lib": ["es2015"],5 "strict": true6 }7}
modified:.github/ISSUE_TEMPLATE/bug.md+3 added-3 removed
20 unmodified lines
21Please provide either a [CodeSandbox demo](https://codesandbox.io/s/82zqr6n3kj) or a minimal repository on GitHub.2223## Environment2425- **Immer version:**26- [ ] Occurs with `setUseProxies(true)`27- [ ] Occurs with `setUseProxies(false)` (ES5 only)25- **Immer version:**26- [ ] Occurs with `setUseProxies(true)`27- [ ] Occurs with `setUseProxies(false)` (ES5 only)
modified:docs/api.md+1 added
18 unmodified lines
19| `nothing` | Value that can be returned from a recipe, to indicate that the value `undefined` should be produced | [Return](return.md) |20| `original` | Given a draft object (doesn't have to be a tree root), returns the the original object at the same path in the original state tree, if present | [Original](original.md) |21| `Patch` | Exposed TypeScript type, describes the shape of an (inverse) patch object | [Patches](patches.md) |22| `produce` | The core API of Immer, also exposed as the `default` export | [Produce](produce.md) |23| `produceWithPatches` | Works the same as `produce`, but instead of just returning the produced object, it returns a tuple, consisting of `[result, patches, inversePatches]`. | [Patches](patches.md) |24| `setAutoFreeze` | Enables / disables automatic freezing of the trees produces. By default enabled in development builds | [Freezing](freezing.md) |25| `setUseProxies` | Can be used to disable or force the use of `Proxy` objects. Useful when filing bug reports. | |2627## Importing immer
14 unmodified lines
modified:docs/complex-objects.md+2 added-34 removed
3 unmodified lines
4---56<div id="codefund"><!-- fallback content --></div>78Plain objects and arrays are always drafted by Immer.8Plain objects, arrays, `Map`s and `Set`s are always drafted by Immer.910Every 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.1112```js
13 unmodified lines
26For arrays, only numeric properties and the `length` property can be mutated. Custom properties are not preserved on arrays.2728When working with `Date` objects, you should always create a new `Date` instance instead of mutating an existing `Date` object.2930Built-in classes like `Map` and `Set` are not yet supported (they might be if there is popular demand). As a workaround, you should clone them before mutating them in a producer:3132```js33const state = {34 set: new Set(),35 map: new Map()36}37const nextState = produce(state, draft => {38 // Don't use any Set methods, as that mutates the instance!39 draft.set.add("foo") // ❌4041 // 1. Instead, clone the set (just once)42 const newSet = new Set(draft.set) // ✅4344 // 2. Mutate the clone (just in this producer)45 newSet.add("foo")4647 // 3. Update the draft with the new set48 draft.set = newSet4950 // Similarly, don't use any Map methods.51 draft.map.set("foo", "bar") // ❌5253 // 1. Instead, clone the map (just once)54 const newMap = new Map(draft.map) // ✅5556 // 2. Mutate it57 newMap.set("foo", "bar")5859 // 3. Update the draft60 draft.map = newMap61})62```30Maps 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.
modified:docs/faq.md+5 added-1 removed
18 unmodified lines
19A: Yes2021## Q: I can't rely on Proxies being present on my target environments. Can I use Immer?2223A: Yes23A: Yes [details](http://localhost:3000/immer/docs/installation#immer-on-older-javascript-environments)2425## Q: Can I typecheck my data structures when using Immer?2627A: Yes
1 unmodified line
29## Q: Can I store `Date` objects, functions etc in my state tree when using Immer?3031A: Yes3233## Q: Can I use Maps and Sets?3435A: Yes3637## Q: Is it fast?3839A: Yes40
3 unmodified lines
modified:docs/introduction.md+1 added-1 removed
52 unmodified lines
53Head to the [next section](produce) to further dive into `produce`.5455## Benefits5657- Immutability with normal JavaScript objects and arrays. No new APIs to learn!57- Immutability with normal JavaScript objects, arrays, Sets and Maps. No new APIs to learn!58- Strongly typed, no string based paths selectors etc.59- Structural sharing out of the box60- Object freezing out of the box61- Deep updates are a breeze
3 unmodified lines
modified:docs/performance.md+1 added-1 removed
25 unmodified lines
26Here is a [simple benchmark](https://github.com/immerjs/immer/blob/master/__performance_tests__/todo.js) on the performance of Immer. This test takes 50,000 todo items and updates 5,000 of them. _Freeze_ indicates that the state tree has been frozen after producing it. This is a _development_ best practice, as it prevents developers from accidentally modifying the state tree.2728Something that isn't reflected in the numbers above, but in reality, Immer is sometimes significantly _faster_ than a hand written reducer. The reason for that is that Immer will detect "no-op" state changes, and return the original state if nothing actually changed, which can avoid a lot of re-renderings for example. Cases are known where simply applying immer solved critical performance issues.2930These tests were executed on Node 10.15.1. Use `yarn test:perf` to reproduce them locally.30These tests were executed on Node 10.16.3. Use `yarn test:perf` to reproduce them locally.3132![performance.png](/immer/img/performance.png)3334Most important observation:
5 unmodified lines
modified:src/common.js+133 added-16 removed
18 unmodified lines
1920export function isDraftable(value) {21 if (!value) return false22 return (23 isPlainObject(value) || !!value[DRAFTABLE] || !!value.constructor[DRAFTABLE]23 isPlainObject(value) ||24 !!value[DRAFTABLE] ||25 !!value.constructor[DRAFTABLE] ||26 isMap(value) ||27 isSet(value)28 )29}3031export function isPlainObject(value) {
9 unmodified lines
41 }42 // otherwise return undefined43}4445// We use Maps as `drafts` for Sets, not Objects46// See proxy.js47export function assignSet(target, override) {48 override.forEach(value => {49 // When we add new drafts we have to remove their originals if present50 const prev = original(value)51 if (prev) target.delete(prev)52 target.add(value)53 })54 return target55}5657// We use Maps as `drafts` for Maps, not Objects58// See proxy.js59export function assignMap(target, override) {60 override.forEach((value, key) => target.set(key, value))61 return target62}6364export const assign =65 Object.assign ||43 function assign(target, value) {44 for (let key in value) {45 if (has(value, key)) {46 target[key] = value[key]47 }48 }66 ((target, ...overrides) => {67 overrides.forEach(override =>68 Object.keys(override).forEach(key => (target[key] = override[key]))69 )70 return target50 }71 })7273export const ownKeys =74 typeof Reflect !== "undefined" && Reflect.ownKeys75 ? Reflect.ownKeys
5 unmodified lines
81 : Object.getOwnPropertyNames8283export function shallowCopy(base, invokeGetters = false) {84 if (Array.isArray(base)) return base.slice()85 if (isMap(base)) return new Map(base)86 if (isSet(base)) return new Set(base)87 const clone = Object.create(Object.getPrototypeOf(base))88 ownKeys(base).forEach(key => {89 if (key === DRAFT_STATE) {90 return // Never copy over draft state.
18 unmodified lines
109 })110 return clone111}11290export function each(value, cb) {91 if (Array.isArray(value)) {92 for (let i = 0; i < value.length; i++) cb(i, value[i], value)113export function each(obj, iter) {114 if (Array.isArray(obj) || isMap(obj) || isSet(obj)) {115 obj.forEach((entry, index) => iter(index, entry, obj))116 } else {94 ownKeys(value).forEach(key => cb(key, value[key], value))117 ownKeys(obj).forEach(key => iter(key, obj[key], obj))118 }119}120121export function isEnumerable(base, prop) {
1 unmodified line
123 return !!desc && desc.enumerable124}125126export function has(thing, prop) {127 return isMap(thing)128 ? thing.has(prop)104 return Object.prototype.hasOwnProperty.call(thing, prop)129 : Object.prototype.hasOwnProperty.call(thing, prop)130}131132export function get(thing, prop) {133 return isMap(thing) ? thing.get(prop) : thing[prop]134}135136export function is(x, y) {137 // From: https://github.com/facebook/fbjs/blob/c69904a511b900266935168223063dd8772dfc40/packages/fbjs/src/core/shallowEqual.js138 if (x === y) {139 return x !== 0 || 1 / x === 1 / y
1 unmodified line
141 return x !== x && y !== y142 }143}144145export const hasSymbol = typeof Symbol !== "undefined"146147export const hasMap = typeof Map !== "undefined"148149export function isMap(target) {150 return hasMap && target instanceof Map151}152153export const hasSet = typeof Set !== "undefined"154155export function isSet(target) {156 return hasSet && target instanceof Set157}158159export function makeIterable(next) {160 let self161 return (self = {162 [Symbol.iterator]: () => self,163 next164 })165}166167/** Map.prototype.values _-or-_ Map.prototype.entries */168export function iterateMapValues(state, prop, receiver) {169 const isEntries = prop !== "values"170 return () => {171 const iterator = latest(state)[Symbol.iterator]()172 return makeIterable(() => {173 const result = iterator.next()174 if (!result.done) {175 const [key] = result.value176 const value = receiver.get(key)177 result.value = isEntries ? [key, value] : value178 }179 return result180 })181 }182}183184export function makeIterateSetValues(createProxy) {185 function iterateSetValues(state, prop) {186 const isEntries = prop === "entries"187 return () => {188 const iterator = latest(state)[Symbol.iterator]()189 return makeIterable(() => {190 const result = iterator.next()191 if (!result.done) {192 const value = wrapSetValue(state, result.value)193 result.value = isEntries ? [value, value] : value194 }195 return result196 })197 }198 }199200 function wrapSetValue(state, value) {201 const key = original(value) || value202 let draft = state.drafts.get(key)203 if (!draft) {204 if (state.finalized || !isDraftable(value) || state.finalizing) {205 return value206 }207 draft = createProxy(value, state)208 state.drafts.set(key, draft)209 if (state.modified) {210 state.copy.add(draft)211 }212 }213 return draft214 }215216 return iterateSetValues217}218219function latest(state) {220 return state.copy || state.base221}222223export function clone(obj) {224 if (!isDraftable(obj)) return obj225 if (Array.isArray(obj)) return obj.map(clone)226 if (isMap(obj)) return new Map(obj)227 if (isSet(obj)) return new Set(obj)228 const cloned = Object.create(Object.getPrototypeOf(obj))229 for (const key in obj) cloned[key] = clone(obj[key])230 return cloned231}232124export function deepFreeze(obj) {233export function freeze(obj, deep = false) {234 if (!isDraftable(obj) || isDraft(obj) || Object.isFrozen(obj)) return235 if (isSet(obj)) {236 obj.add = obj.clear = obj.delete = dontMutateFrozenCollections237 } else if (isMap(obj)) {238 obj.set = obj.clear = obj.delete = dontMutateFrozenCollections239 }240 Object.freeze(obj)127 if (Array.isArray(obj)) obj.forEach(deepFreeze)128 else for (const key in obj) deepFreeze(obj[key])241 if (deep) each(obj, (_, value) => freeze(value, true))242}243244function dontMutateFrozenCollections() {245 throw new Error("This object has been frozen and should not be mutated")246}
modified:src/es5.js+219 added-14 removed
4 unmodified lines
5 is,6 isDraft,7 isDraftable,8 isEnumerable,9 isMap,10 isSet,11 hasSymbol,12 shallowCopy,10 DRAFT_STATE13 DRAFT_STATE,14 iterateMapValues,15 makeIterable,16 makeIterateSetValues17} from "./common"18import {ImmerScope} from "./scope"1914// property descriptors are recycled to make sure we don't create a get and set closure per property,15// but share them all instead16const descriptors = {}1720export function willFinalize(scope, result, isReplaced) {21 scope.drafts.forEach(draft => {22 draft[DRAFT_STATE].finalizing = true23 })
12 unmodified lines
3637export function createProxy(base, parent) {38 const isArray = Array.isArray(base)39 const draft = clonePotentialDraft(base)38 each(draft, prop => {39 proxyProperty(draft, prop, isArray || isEnumerable(base, prop))40 })4041 if (isMap(base)) {42 proxyMap(draft)43 } else if (isSet(base)) {44 proxySet(draft)45 } else {46 each(draft, prop => {47 proxyProperty(draft, prop, isArray || isEnumerable(base, prop))48 })49 }5051 // See "proxy.js" for property documentation.52 const scope = parent ? parent.scope : ImmerScope.current53 const state = {54 scope,55 modified: false,56 finalizing: false, // es5 only57 finalized: false,49 assigned: {},58 assigned: isMap(base) ? new Map() : {},59 parent,60 base,61 draft,62 drafts: isSet(base) ? new Map() : null,63 copy: null,64 revoke,65 revoked: false // es5 only66 }
6 unmodified lines
73function revoke() {74 this.revoked = true75}7667function source(state) {77function latest(state) {78 return state.copy || state.base79}8081// Access a property without creating an Immer draft.
9 unmodified lines
91}9293function get(state, prop) {94 assertUnrevoked(state)85 const value = peek(source(state), prop)95 const value = peek(latest(state), prop)96 if (state.finalizing) return value97 // Create a draft if the value is unmodified.98 if (value === peek(state.base, prop) && isDraftable(value)) {99 prepareCopy(state)
5 unmodified lines
105function set(state, prop, value) {106 assertUnrevoked(state)107 state.assigned[prop] = true108 if (!state.modified) {99 if (is(value, peek(source(state), prop))) return109 if (is(value, peek(latest(state), prop))) return110 markChanged(state)111 prepareCopy(state)112 }113 state.copy[prop] = value
20 unmodified lines
134 }135 return shallowCopy(base)136}137138// property descriptors are recycled to make sure we don't create a get and set closure per property,139// but share them all instead140const descriptors = {}141142function proxyProperty(draft, prop, enumerable) {143 let desc = descriptors[prop]144 if (desc) {145 desc.enumerable = enumerable
11 unmodified lines
157 }158 Object.defineProperty(draft, prop, desc)159}160161function proxyMap(target) {162 Object.defineProperties(target, mapTraps)163164 if (hasSymbol) {165 Object.defineProperty(166 target,167 Symbol.iterator,168 proxyMethod(iterateMapValues)169 )170 }171}172173const mapTraps = finalizeTraps({174 size: state => latest(state).size,175 has: state => key => latest(state).has(key),176 set: state => (key, value) => {177 if (latest(state).get(key) !== value) {178 prepareCopy(state)179 markChanged(state)180 state.assigned.set(key, true)181 state.copy.set(key, value)182 }183 return state.draft184 },185 delete: state => key => {186 prepareCopy(state)187 markChanged(state)188 state.assigned.set(key, false)189 state.copy.delete(key)190 return false191 },192 clear: state => () => {193 if (!state.copy) {194 prepareCopy(state)195 }196 markChanged(state)197 state.assigned = new Map()198 for (const key of latest(state).keys()) {199 state.assigned.set(key, false)200 }201 return state.copy.clear()202 },203 forEach: (state, key, reciever) => cb => {204 latest(state).forEach((value, key, map) => {205 cb(reciever.get(key), key, map)206 })207 },208 get: state => key => {209 const value = latest(state).get(key)210211 if (state.finalizing || state.finalized || !isDraftable(value)) {212 return value213 }214215 if (value !== state.base.get(key)) {216 return value217 }218 const draft = createProxy(value, state)219 prepareCopy(state)220 state.copy.set(key, draft)221 return draft222 },223 keys: state => () => latest(state).keys(),224 values: iterateMapValues,225 entries: iterateMapValues226})227228function proxySet(target) {229 Object.defineProperties(target, setTraps)230231 if (hasSymbol) {232 Object.defineProperty(233 target,234 Symbol.iterator,235 proxyMethod(iterateSetValues)236 )237 }238}239240const iterateSetValues = makeIterateSetValues(createProxy)241242const setTraps = finalizeTraps({243 size: state => {244 return latest(state).size245 },246 add: state => value => {247 if (!latest(state).has(value)) {248 markChanged(state)249 if (!state.copy) {250 prepareCopy(state)251 }252 state.copy.add(value)253 }254 return state.draft255 },256 delete: state => value => {257 markChanged(state)258 if (!state.copy) {259 prepareCopy(state)260 }261 return state.copy.delete(value)262 },263 has: state => key => {264 return latest(state).has(key)265 },266 clear: state => () => {267 markChanged(state)268 if (!state.copy) {269 prepareCopy(state)270 }271 return state.copy.clear()272 },273 keys: iterateSetValues,274 entries: iterateSetValues,275 values: iterateSetValues,276 forEach: state => (cb, thisArg) => {277 const iterator = iterateSetValues(state)()278 let result = iterator.next()279 while (!result.done) {280 cb.call(thisArg, result.value, result.value, state.draft)281 result = iterator.next()282 }283 }284})285286function finalizeTraps(traps) {287 return Object.keys(traps).reduce(function(acc, key) {288 const builder = key === "size" ? proxyAttr : proxyMethod289 acc[key] = builder(traps[key], key)290 return acc291 }, {})292}293294function proxyAttr(fn) {295 return {296 get() {297 const state = this[DRAFT_STATE]298 assertUnrevoked(state)299 return fn(state)300 }301 }302}303304function proxyMethod(trap, key) {305 return {306 get() {307 return function(...args) {308 const state = this[DRAFT_STATE]309 assertUnrevoked(state)310 return trap(state, key, state.draft)(...args)311 }312 }313 }314}315316function assertUnrevoked(state) {317 if (state.revoked === true)318 throw new Error(319 "Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? " +151 JSON.stringify(source(state))320 JSON.stringify(latest(state))321 )322}323324// This looks expensive, but only proxies are visited, and only objects without known changes are scanned.
6 unmodified lines
331 const state = drafts[i][DRAFT_STATE]332 if (!state.modified) {333 if (Array.isArray(state.base)) {334 if (hasArrayChanges(state)) markChanged(state)335 } else if (isMap(state.base)) {336 if (hasMapChanges(state)) markChanged(state)337 } else if (isSet(state.base)) {166 } else if (hasObjectChanges(state)) markChanged(state)338 if (hasSetChanges(state)) markChanged(state)339 } else if (hasObjectChanges(state)) {340 markChanged(state)341 }342 }343 }344}345
82 unmodified lines
428 // For all other cases, we don't have to compare, as they would have been picked up by the index setters429 return false430}431432function hasMapChanges(state) {433 const {base, draft} = state434435 if (base.size !== draft.size) return true436437 // IE11 supports only forEach iteration438 let hasChanges = false439 draft.forEach(function(value, key) {440 if (!hasChanges) {441 hasChanges = isDraftable(value) ? value.modified : value !== base.get(key)442 }443 })444 return hasChanges445}446447function hasSetChanges(state) {448 const {base, draft} = state449450 if (base.size !== draft.size) return true451452 // IE11 supports only forEach iteration453 let hasChanges = false454 draft.forEach(function(value, key) {455 if (!hasChanges) {456 hasChanges = isDraftable(value) ? value.modified : !base.has(key)457 }458 })459 return hasChanges460}461462function createHiddenProperty(target, prop, value) {463 Object.defineProperty(target, prop, {464 value: value,465 enumerable: false,
3 unmodified lines
modified:src/immer.d.ts+20 added-2 removed
6 unmodified lines
78/** Object types that should never be mapped */9type AtomicObject =10 | Function11 | Map<any, any>11 | WeakMap<any, any>13 | Set<any>12 | WeakSet<any>13 | Promise<any>14 | Date15 | RegExp
2 unmodified lines
18 | String1920export type Draft<T> = T extends AtomicObject21 ? T22 : T extends Map<infer K, infer V>23 ? DraftMap<K, V>24 : T extends Set<infer V>25 ? DraftSet<V>26 : T extends object27 ? {-readonly [K in keyof T]: Draft<T[K]>}28 : T2930// Inline these in ts 3.731interface DraftMap<K, V> extends Map<Draft<K>, Draft<V>> {}3233// Inline these in ts 3.734interface DraftSet<V> extends Set<Draft<V>> {}3536/** Convert a mutable type into a readonly type */37export type Immutable<T> = T extends AtomicObject38 ? T39 : T extends Map<infer K, infer V>40 ? // Ideally, but wait for TS 3.7: ? Omit<ImmutableMap<K, V>, "set" | "delete" | "clear">41 ImmutableMap<K, V>42 : T extends Set<infer V>43 ? // Ideally, but wait for TS 3.7: ? Omit<ImmutableSet<V>, "add" | "delete" | "clear">44 ImmutableSet<V>45 : T extends object46 ? {readonly [K in keyof T]: Immutable<T[K]>}47 : T4849interface ImmutableMap<K, V> extends Map<Immutable<K>, Immutable<V>> {}5051interface ImmutableSet<V> extends Set<Immutable<V>> {}5253export interface Patch {54 op: "replace" | "remove" | "add"55 path: (string | number)[]56 value?: any
253 unmodified lines
modified:src/immer.js+42 added-20 removed
5 unmodified lines
6 each,7 has,8 is,9 isDraft,10 isSet,11 get,12 isMap,13 isDraftable,14 isEnumerable,15 shallowCopy,16 DRAFT_STATE,17 NOTHING,15 deepFreeze18 freeze19} from "./common"20import {ImmerScope} from "./scope"2122function verifyMinified() {}
16 unmodified lines
39 constructor(config) {40 assign(this, configDefaults, config)41 this.setUseProxies(this.useProxies)42 this.produce = this.produce.bind(this)43 this.produceWithPatches = this.produceWithPatches.bind(this)44 }45 produce(base, recipe, patchListener) {46 // curried invocation47 if (typeof base === "function" && typeof recipe !== "function") {
30 unmodified lines
78 // finally instead of catch + rethrow better preserves original stack79 if (hasError) scope.revoke()80 else scope.leave()81 }78 if (result instanceof Promise) {82 if (typeof Promise !== "undefined" && result instanceof Promise) {83 return result.then(84 result => {85 scope.usePatches(patchListener)86 return this.processResult(result, scope)
139 unmodified lines
226 if (!state.finalized) {227 state.finalized = true228 this.finalizeTree(state.draft, path, scope)229226 if (this.onDelete) {230 // We cannot really delete anything inside of a Set. We can only replace the whole Set.231 if (this.onDelete && !isSet(state.base)) {232 // The `assigned` object is unreliable with ES5 drafts.233 if (this.useProxies) {234 const {assigned} = state230 for (const prop in assigned) {231 if (!assigned[prop]) this.onDelete(state, prop)232 }235 each(assigned, (prop, exists) => {236 if (!exists) this.onDelete(state, prop)237 })238 } else {239 // TODO: Figure it out for Maps and Sets if we need to support ES5240 const {base, copy} = state241 each(base, prop => {242 if (!has(copy, prop)) this.onDelete(state, prop)243 })
5 unmodified lines
249250 // At this point, all descendants of `state.copy` have been finalized,251 // so we can be sure that `scope.canAutoFreeze` is accurate.252 if (this.autoFreeze && scope.canAutoFreeze) {247 Object.freeze(state.copy)253 freeze(state.copy, false)254 }255256 if (path && scope.patches) {257 generatePatches(state, path, scope.patches, scope.inversePatches)
22 unmodified lines
280 }281282 // In the `finalizeTree` method, only the `root` object may be a draft.283 const isDraftProp = !!state && parent === root284 const isSetMember = isSet(parent)285286 if (isDraft(value)) {287 const path =281 isDraftProp && needPatches && !state.assigned[prop]288 isDraftProp &&289 needPatches &&290 !isSetMember && // Set objects are atomic since they have no keys.291 !has(state.assigned, prop) // Skip deep patches for assigned keys.292 ? rootPath.concat(prop)293 : null294295 // Drafts owned by `scope` are finalized here.296 value = this.finalize(value, path, scope)297 replace(parent, prop, value)298299 // Drafts from another scope must prevent auto-freezing.300 if (isDraft(value)) {301 scope.canAutoFreeze = false302 }303293 // Preserve non-enumerable properties.294 if (Array.isArray(parent) || isEnumerable(parent, prop)) {295 parent[prop] = value296 } else {297 Object.defineProperty(parent, prop, {value})298 }299304 // Unchanged drafts are never passed to the `onAssign` hook.301 if (isDraftProp && value === state.base[prop]) return305 if (isDraftProp && value === get(state.base, prop)) return306 }307 // Unchanged draft properties are ignored.304 else if (isDraftProp && is(value, state.base[prop])) {308 else if (isDraftProp && is(value, get(state.base, prop))) {309 return310 }311 // Search new objects for unfinalized drafts. Frozen objects should never contain drafts.312 else if (isDraftable(value) && !Object.isFrozen(value)) {313 each(value, finalizeProperty)314 this.maybeFreeze(value)315 }316313 if (isDraftProp && this.onAssign) {317 if (isDraftProp && this.onAssign && !isSetMember) {318 this.onAssign(state, prop, value)319 }320 }321
1 unmodified line
323 return root324 }325 maybeFreeze(value, deep = false) {326 if (this.autoFreeze && !isDraft(value)) {323 if (deep) deepFreeze(value)324 else Object.freeze(value)327 freeze(value, deep)328 }329 }330}331332function replace(parent, prop, value) {333 if (isMap(parent)) {334 parent.set(prop, value)335 } else if (isSet(parent)) {336 // In this case, the `prop` is actually a draft.337 parent.delete(prop)338 parent.add(value)339 } else if (Array.isArray(parent) || isEnumerable(parent, prop)) {340 // Preserve non-enumerable properties.341 parent[prop] = value342 } else {343 Object.defineProperty(parent, prop, {344 value,345 writable: true,346 configurable: true347 })348 }349}
modified:src/patches.js+82 added-24 removed
1import {each, clone} from "./common"1import {get, each, isMap, isSet, has, clone} from "./common"23export function generatePatches(state, basePath, patches, inversePatches) {4 Array.isArray(state.base)5 ? generateArrayPatches(state, basePath, patches, inversePatches)6 : generateObjectPatches(state, basePath, patches, inversePatches)4 const generatePatchesFn = Array.isArray(state.base)5 ? generateArrayPatches6 : isSet(state.base)7 ? generateSetPatches8 : generatePatchesFromAssigned910 generatePatchesFn(state, basePath, patches, inversePatches)11}1213function generateArrayPatches(state, basePath, patches, inversePatches) {14 let {base, copy, assigned} = state
51 unmodified lines
66 })67 }68}6970// This is used for both Map objects and normal objects.66function generateObjectPatches(state, basePath, patches, inversePatches) {71function generatePatchesFromAssigned(state, basePath, patches, inversePatches) {72 const {base, copy} = state73 each(state.assigned, (key, assignedValue) => {69 const origValue = base[key]70 const value = copy[key]71 const op = !assignedValue ? "remove" : key in base ? "replace" : "add"74 const origValue = get(base, key)75 const value = get(copy, key)76 const op = !assignedValue ? "remove" : has(base, key) ? "replace" : "add"77 if (origValue === value && op === "replace") return78 const path = basePath.concat(key)79 patches.push(op === "remove" ? {op, path} : {op, path, value})80 inversePatches.push(
5 unmodified lines
86 )87 })88}8990function generateSetPatches(state, basePath, patches, inversePatches) {91 let {base, copy} = state9293 let i = 094 for (const value of base) {95 if (!copy.has(value)) {96 const path = basePath.concat([i])97 patches.push({98 op: "remove",99 path,100 value101 })102 inversePatches.unshift({103 op: "add",104 path,105 value106 })107 }108 i++109 }110 i = 0111 for (const value of copy) {112 if (!base.has(value)) {113 const path = basePath.concat([i])114 patches.push({115 op: "add",116 path,117 value118 })119 inversePatches.unshift({120 op: "remove",121 path,122 value123 })124 }125 i++126 }127}128129export const applyPatches = (draft, patches) => {130 for (const patch of patches) {131 const {path, op} = patch88 const value = clone(patch.value) // used to clone patch to ensure original patch is not modified, see #411132133 if (!path.length) throw new Error("Illegal state")134135 let base = draft136 for (let i = 0; i < path.length - 1; i++) {94 base = base[path[i]]137 base = get(base, path[i])138 if (!base || typeof base !== "object")139 throw new Error("Cannot apply patch, path doesn't resolve: " + path.join("/")) // prettier-ignore140 }141142 const value = clone(patch.value) // used to clone patch to ensure original patch is not modified, see #411143144 const key = path[path.length - 1]145 switch (op) {146 case "replace":102 // if value is an object, then it's assigned by reference103 // in the following add or remove ops, the value field inside the patch will also be modifyed104 // so we use value from the cloned patch105 base[key] = value106 break107 case "add":108 if (Array.isArray(base)) {109 // TODO: support "foo/-" paths for appending to an array110 base.splice(key, 0, value)147 if (isMap(base)) {148 base.set(key, value)149 } else if (isSet(base)) {150 throw new Error('Sets cannot have "replace" patches.')151 } else {152 // if value is an object, then it's assigned by reference153 // in the following add or remove ops, the value field inside the patch will also be modifyed154 // so we use value from the cloned patch155 base[key] = value156 }157 break115 case "remove":116 if (Array.isArray(base)) {117 base.splice(key, 1)118 } else {119 delete base[key]158 case "add":159 if (isSet(base)) {160 base.delete(patch.value)161 }162163 Array.isArray(base)164 ? base.splice(key, 0, value)165 : isMap(base)166 ? base.set(key, value)167 : isSet(base)168 ? base.add(value)169 : (base[key] = value)170 break171 case "remove":172 Array.isArray(base)173 ? base.splice(key, 1)174 : isMap(base)175 ? base.delete(key)176 : isSet(base)177 ? base.delete(patch.value)178 : delete base[key]179 break180 default:181 throw new Error("Unsupported patch operation: " + op)182 }183 }
3 unmodified lines
modified:src/proxy.js+265 added-84 removed
4 unmodified lines
5 has,6 is,7 isDraftable,8 isDraft,9 isMap,10 isSet,11 hasSymbol,12 shallowCopy,13 makeIterable,10 DRAFT_STATE14 DRAFT_STATE,15 assignMap,16 assignSet,17 original,18 iterateMapValues,19 makeIterateSetValues20} from "./common"21import {ImmerScope} from "./scope"2223// Do nothing before being finalized.24export function willFinalize() {}2526/**27 * Returns a new draft of the `base` object.28 *29 * The second argument is the parent draft-state (used internally).30 */31export function createProxy(base, parent) {32 const scope = parent ? parent.scope : ImmerScope.current33 const state = {34 // Track which produce call this is associated with.
17 unmodified lines
52 // Called by the `produce` function.53 revoke: null54 }5542 const {revoke, proxy} = Array.isArray(base)43 ? // [state] is used for arrays, to make sure the proxy is array-ish and not violate invariants,44 // although state itself is an object45 Proxy.revocable([state], arrayTraps)46 : Proxy.revocable(state, objectTraps)56 let target = state57 let traps = objectTraps58 if (Array.isArray(base)) {59 target = [state]60 traps = arrayTraps61 }62 // Map drafts must support object keys, so we use Map objects to track changes.63 else if (isMap(base)) {64 traps = mapTraps65 state.drafts = new Map()66 state.assigned = new Map()67 }68 // Set drafts use a Map object to track which of its values are drafted.69 // And we don't need the "assigned" property, because Set objects have no keys.70 else if (isSet(base)) {71 traps = setTraps72 state.drafts = new Map()73 }7475 const {revoke, proxy} = Proxy.revocable(target, traps)7677 state.draft = proxy78 state.revoke = revoke7980 scope.drafts.push(proxy)81 return proxy82}8384/**85 * Object drafts86 */8788const objectTraps = {56 get,57 has(target, prop) {58 return prop in source(target)89 get(state, prop) {90 if (prop === DRAFT_STATE) return state91 let {drafts} = state9293 // Check for existing draft in unmodified state.94 if (!state.modified && has(drafts, prop)) {95 return drafts[prop]96 }9798 const value = latest(state)[prop]99 if (state.finalized || !isDraftable(value)) {100 return value101 }102103 // Check for existing draft in modified state.104 if (state.modified) {105 // Assigned values are never drafted. This catches any drafts we created, too.106 if (value !== peek(state.base, prop)) return value107 // Store drafts on the copy (when one exists).108 drafts = state.copy109 }110111 return (drafts[prop] = createProxy(value, state))112 },60 ownKeys(target) {61 return Reflect.ownKeys(source(target))113 has(state, prop) {114 return prop in latest(state)115 },63 set,64 deleteProperty,65 getOwnPropertyDescriptor,116 ownKeys(state) {117 return Reflect.ownKeys(latest(state))118 },119 set(state, prop, value) {120 if (!state.modified) {121 const baseValue = peek(state.base, prop)122 // Optimize based on value's truthiness. Truthy values are guaranteed to123 // never be undefined, so we can avoid the `in` operator. Lastly, truthy124 // values may be drafts, but falsy values are never drafts.125 const isUnchanged = value126 ? is(baseValue, value) || value === state.drafts[prop]127 : is(baseValue, value) && prop in state.base128 if (isUnchanged) return true129 markChanged(state)130 }131 state.assigned[prop] = true132 state.copy[prop] = value133 return true134 },135 deleteProperty(state, prop) {136 // The `undefined` check is a fast path for pre-existing keys.137 if (peek(state.base, prop) !== undefined || prop in state.base) {138 state.assigned[prop] = false139 markChanged(state)140 } else if (state.assigned[prop]) {141 // if an originally not assigned property was deleted142 delete state.assigned[prop]143 }144 if (state.copy) delete state.copy[prop]145 return true146 },147 // Note: We never coerce `desc.value` into an Immer draft, because we can't make148 // the same guarantee in ES5 mode.149 getOwnPropertyDescriptor(state, prop) {150 const owner = latest(state)151 const desc = Reflect.getOwnPropertyDescriptor(owner, prop)152 if (desc) {153 desc.writable = true154 desc.configurable = !Array.isArray(owner) || prop !== "length"155 }156 return desc157 },158 defineProperty() {159 throw new Error("Object.defineProperty() cannot be used on an Immer draft") // prettier-ignore160 },69 getPrototypeOf(target) {70 return Object.getPrototypeOf(target.base)161 getPrototypeOf(state) {162 return Object.getPrototypeOf(state.base)163 },164 setPrototypeOf() {165 throw new Error("Object.setPrototypeOf() cannot be used on an Immer draft") // prettier-ignore166 }167}168169/**170 * Array drafts171 */172173const arrayTraps = {}174each(objectTraps, (key, fn) => {175 arrayTraps[key] = function() {176 arguments[0] = arguments[0][0]
12 unmodified lines
189 }190 return objectTraps.set.call(this, state[0], prop, value)191}19297// returns the object we should be reading the current value from, which is base, until some change has been made98function source(state) {193// Used by Map and Set drafts194const reflectTraps = makeReflectTraps([195 "ownKeys",196 "has",197 "set",198 "deleteProperty",199 "defineProperty",200 "getOwnPropertyDescriptor",201 "preventExtensions",202 "isExtensible",203 "getPrototypeOf"204])205206/**207 * Map drafts208 */209210const mapTraps = makeTrapsForGetters({211 [DRAFT_STATE]: state => state,212 size: state => latest(state).size,213 has: state => key => latest(state).has(key),214 set: state => (key, value) => {215 const values = latest(state)216 if (!values.has(key) || values.get(key) !== value) {217 markChanged(state)218 state.assigned.set(key, true)219 state.copy.set(key, value)220 }221 return state.draft222 },223 delete: state => key => {224 if (latest(state).has(key)) {225 markChanged(state)226 state.assigned.set(key, false)227 return state.copy.delete(key)228 }229 return false230 },231 clear: state => () => {232 markChanged(state)233 state.assigned = new Map()234 for (const key of latest(state).keys()) {235 state.assigned.set(key, false)236 }237 return state.copy.clear()238 },239 forEach: (state, _, receiver) => (cb, thisArg) =>240 latest(state).forEach((_, key, map) => {241 const value = receiver.get(key)242 cb.call(thisArg, value, key, map)243 }),244 get: state => key => {245 const drafts = state[state.modified ? "copy" : "drafts"]246 if (drafts.has(key)) {247 return drafts.get(key)248 }249250 const value = latest(state).get(key)251 if (state.finalized || !isDraftable(value)) {252 return value253 }254255 const draft = createProxy(value, state)256 drafts.set(key, draft)257 return draft258 },259 keys: state => () => latest(state).keys(),260 values: iterateMapValues,261 entries: iterateMapValues,262 [hasSymbol ? Symbol.iterator : "@@iterator"]: iterateMapValues263})264265const iterateSetValues = makeIterateSetValues(createProxy)266/**267 * Set drafts268 */269270const setTraps = makeTrapsForGetters({271 [DRAFT_STATE]: state => state,272 size: state => latest(state).size,273 has: state => key => latest(state).has(key),274 add: state => value => {275 if (!latest(state).has(value)) {276 markChanged(state)277 state.copy.add(value)278 }279 return state.draft280 },281 delete: state => value => {282 markChanged(state)283 return state.copy.delete(value)284 },285 clear: state => () => {286 markChanged(state)287 return state.copy.clear()288 },289 forEach: state => (cb, thisArg) => {290 const iterator = iterateSetValues(state)()291 let result = iterator.next()292 while (!result.done) {293 cb.call(thisArg, result.value, result.value, state.draft)294 result = iterator.next()295 }296 },297 keys: iterateSetValues,298 values: iterateSetValues,299 entries: iterateSetValues,300 [hasSymbol ? Symbol.iterator : "@@iterator"]: iterateSetValues301})302303/**304 * Helpers305 */306307// Retrieve the latest values of the draft.308function latest(state) {309 return state.copy || state.base310}311312// Access a property without creating an Immer draft.313function peek(draft, prop) {314 const state = draft[DRAFT_STATE]315 const desc = Reflect.getOwnPropertyDescriptor(106 state ? source(state) : draft,316 state ? latest(state) : draft,317 prop318 )319 return desc && desc.value320}321112function get(state, prop) {113 if (prop === DRAFT_STATE) return state114 let {drafts} = state322function markChanged(state) {323 if (!state.modified) {324 state.modified = true325116 // Check for existing draft in unmodified state.117 if (!state.modified && has(drafts, prop)) {118 return drafts[prop]119 }326 const {base, drafts, parent} = state327 const copy = shallowCopy(base)328121 const value = source(state)[prop]122 if (state.finalized || !isDraftable(value)) {123 return value124 }329 if (isSet(base)) {330 // Note: The `drafts` property is preserved for Set objects, since331 // we need to keep track of which values are drafted.332 assignSet(copy, drafts)333 } else {334 // Merge nested drafts into the copy.335 if (isMap(base)) assignMap(copy, drafts)336 else assign(copy, drafts)337 state.drafts = null338 }339126 // Check for existing draft in modified state.127 if (state.modified) {128 // Assigned values are never drafted. This catches any drafts we created, too.129 if (value !== peek(state.base, prop)) return value130 // Store drafts on the copy (when one exists).131 drafts = state.copy340 state.copy = copy341 if (parent) {342 markChanged(parent)343 }344 }133134 return (drafts[prop] = createProxy(value, state))345}346137function set(state, prop, value) {138 if (!state.modified) {139 const baseValue = peek(state.base, prop)140 // Optimize based on value's truthiness. Truthy values are guaranteed to141 // never be undefined, so we can avoid the `in` operator. Lastly, truthy142 // values may be drafts, but falsy values are never drafts.143 const isUnchanged = value144 ? is(baseValue, value) || value === state.drafts[prop]145 : is(baseValue, value) && prop in state.base146 if (isUnchanged) return true147 markChanged(state)148 }149 state.assigned[prop] = true150 state.copy[prop] = value151 return true347/** Create traps that all use the `Reflect` API on the `latest(state)` */348function makeReflectTraps(names) {349 return names.reduce((traps, name) => {350 traps[name] = (state, ...args) => Reflect[name](latest(state), ...args)351 return traps352 }, {})353}354154function deleteProperty(state, prop) {155 // The `undefined` check is a fast path for pre-existing keys.156 if (peek(state.base, prop) !== undefined || prop in state.base) {157 state.assigned[prop] = false158 markChanged(state)159 } else if (state.assigned[prop]) {160 // if an originally not assigned property was deleted161 delete state.assigned[prop]355function makeTrapsForGetters(getters) {356 return {357 ...reflectTraps,358 get(state, prop, receiver) {359 return getters.hasOwnProperty(prop)360 ? getters[prop](state, prop, receiver)361 : Reflect.get(state, prop, receiver)362 },363 setPrototypeOf(state) {364 throw new Error("Object.setPrototypeOf() cannot be used on an Immer draft") // prettier-ignore365 }366 }163 if (state.copy) delete state.copy[prop]164 return true367}166167// Note: We never coerce `desc.value` into an Immer draft, because we can't make168// the same guarantee in ES5 mode.169function getOwnPropertyDescriptor(state, prop) {170 const owner = source(state)171 const desc = Reflect.getOwnPropertyDescriptor(owner, prop)172 if (desc) {173 desc.writable = true174 desc.configurable = !Array.isArray(owner) || prop !== "length"175 }176 return desc177}178179function markChanged(state) {180 if (!state.modified) {181 state.modified = true182 state.copy = assign(shallowCopy(state.base), state.drafts)183 state.drafts = null184 if (state.parent) markChanged(state.parent)185 }186}
modified:website/i18n/en.json+88 added-88 removed
1{2 "_comment": "This file is auto-generated by write-translations.js",3 "localized-strings": {4 "next": "Next",5 "previous": "Previous",6 "tagline": "Create the next immutable state by mutating the current one",7 "docs": {8 "api": {9 "title": "API overview"10 },11 "async": {12 "title": "Async producers & createDraft / finishDraft",13 "sidebar_label": "Async produce / createDraft"14 },15 "built-with": {16 "title": "Built with Immer"17 },18 "complex-objects": {19 "title": "Working with classes"20 },21 "curried-produce": {22 "title": "Curried producers"23 },24 "example-reducer": {25 "title": "Example Reducer"26 },27 "example-setstate": {28 "title": "React setState example"29 },30 "faq": {31 "title": "Frequently Asked Questions",32 "sidebar_label": "FAQ"33 },34 "freezing": {35 "title": "Auto freezing"36 },37 "installation": {38 "title": "Installation"39 },40 "introduction": {41 "title": "Introduction to Immer",42 "sidebar_label": "Introduction"43 },44 "original": {45 "title": "Extracting the original object from a proxied instance",46 "sidebar_label": "Original"47 },48 "patches": {49 "title": "Patches"50 },51 "performance": {52 "title": "Immer performance"53 },54 "pitfalls": {55 "title": "Pitfalls"56 },57 "produce": {58 "title": "Using produce"59 },60 "resources": {61 "title": "External resources"62 },63 "return": {64 "title": "Returning new data from producers"65 },66 "support": {67 "title": "Supporting immer"68 },69 "typescript": {70 "title": "Using TypeScript or Flow",71 "sidebar_label": "TypeScript / Flow"72 }73 },74 "links": {75 "Documentation": "Documentation",76 "GitHub": "GitHub",77 "Support Immer": "Support Immer"78 },79 "categories": {80 "Basics": "Basics",81 "Advanced Features": "Advanced Features",82 "Resources": "Resources"83 }84 },85 "pages-strings": {86 "Help Translate|recruit community translators for your project": "Help Translate",87 "Edit this Doc|recruitment message asking to edit the doc source": "Edit",88 "Translate this Doc|recruitment message asking to translate the docs": "Translate"89 }2 "_comment": "This file is auto-generated by write-translations.js",3 "localized-strings": {4 "next": "Next",5 "previous": "Previous",6 "tagline": "Create the next immutable state by mutating the current one",7 "docs": {8 "api": {9 "title": "API overview"10 },11 "async": {12 "title": "Async producers & createDraft / finishDraft",13 "sidebar_label": "Async produce / createDraft"14 },15 "built-with": {16 "title": "Built with Immer"17 },18 "complex-objects": {19 "title": "Working with classes"20 },21 "curried-produce": {22 "title": "Curried producers"23 },24 "example-reducer": {25 "title": "Example Reducer"26 },27 "example-setstate": {28 "title": "React setState example"29 },30 "faq": {31 "title": "Frequently Asked Questions",32 "sidebar_label": "FAQ"33 },34 "freezing": {35 "title": "Auto freezing"36 },37 "installation": {38 "title": "Installation"39 },40 "introduction": {41 "title": "Introduction to Immer",42 "sidebar_label": "Introduction"43 },44 "original": {45 "title": "Extracting the original object from a proxied instance",46 "sidebar_label": "Original"47 },48 "patches": {49 "title": "Patches"50 },51 "performance": {52 "title": "Immer performance"53 },54 "pitfalls": {55 "title": "Pitfalls"56 },57 "produce": {58 "title": "Using produce"59 },60 "resources": {61 "title": "External resources"62 },63 "return": {64 "title": "Returning new data from producers"65 },66 "support": {67 "title": "Supporting immer"68 },69 "typescript": {70 "title": "Using TypeScript or Flow",71 "sidebar_label": "TypeScript / Flow"72 }73 },74 "links": {75 "Documentation": "Documentation",76 "GitHub": "GitHub",77 "Support Immer": "Support Immer"78 },79 "categories": {80 "Basics": "Basics",81 "Advanced Features": "Advanced Features",82 "Resources": "Resources"83 }84 },85 "pages-strings": {86 "Help Translate|recruit community translators for your project": "Help Translate",87 "Edit this Doc|recruitment message asking to edit the doc source": "Edit",88 "Translate this Doc|recruitment message asking to translate the docs": "Translate"89 }90}
modified:website/static/img/performance.pngbinary

A binary file, modified.

modified:website/package.json+12 added-12 removed
1{2 "scripts": {3 "examples": "docusaurus-examples",4 "start": "docusaurus-start",5 "build": "docusaurus-build",6 "publish-gh-pages": "docusaurus-publish",7 "write-translations": "docusaurus-write-translations",8 "version": "docusaurus-version",9 "rename-version": "docusaurus-rename-version"10 },11 "devDependencies": {12 "docusaurus": "^1.12.0"13 }2 "scripts": {3 "examples": "docusaurus-examples",4 "start": "docusaurus-start",5 "build": "docusaurus-build",6 "publish-gh-pages": "docusaurus-publish",7 "write-translations": "docusaurus-write-translations",8 "version": "docusaurus-version",9 "rename-version": "docusaurus-rename-version"10 },11 "devDependencies": {12 "docusaurus": "^1.12.0"13 }14}
modified:website/sidebars.json+5 added-5 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"],5 "Resources": ["performance", "resources", "faq", "pitfalls", "built-with", "support"]6 }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"],5 "Resources": ["performance", "resources", "faq", "pitfalls", "built-with", "support"]6 }7}
modified:.gitignore+1 added-1 removed
57 unmodified lines
58.env5960.idea61dist/62website/build62website/build
modified:.prettierrc+2 added-1 removed
10 unmodified lines
11 {12 "files": [".prettierrc", "*.json"],13 "options": {14 "printWidth": 200,15 "tabWidth": 215 "tabWidth": 2,16 "useTabs": false17 }18 }19 ]20}
modified:.travis.yml+2 added-2 removed
1language: node_js2node_js:3 - "8"4 - "10"5# - "node"5 # - "node"6env:7 - NODE_ENV=TEST8cache:9 yarn: true
10 unmodified lines
20jobs:21 include:22 - stage: deploy23 if: branch == master && !fork24 node_js: "8.12.0" # pre-installed version24 node_js: "8.16.0" # pre-installed version25 script:26 - yarn build27 - yarn global add semantic-release@^1528 - semantic-release
added:.watchmanconfig+1 added
1{}
added:index.html+23 added
1<!DOCTYPE html>2<html lang="en">3 <head>4 <meta charset="UTF-8" />5 <meta http-equiv="X-UA-Compatible" content="ie=edge" />6 <title>Test in Browser</title>7 <script src="https://cdn.jsdelivr.net/npm/object-assign-polyfill@0.1.0/index.min.js"></script>8 <script src="./dist/immer.umd.js"></script>9 </head>10 <body>11 <script>12 try {13 const result = immer.produce(new Map([[1, 2]]), function(draft) {14 draft.set(1, 3)15 })1617 console.log(result)18 } catch (err) {19 alert(err)20 }21 </script>22 </body>23</html>
modified:package.json+86 added-86 removed
1{2 "name": "immer",3 "version": "0.0.0-development",4 "description": "Create your next immutable state by mutating the current one",5 "main": "dist/immer.js",6 "umd:main": "dist/immer.umd.js",7 "unpkg": "dist/immer.umd.js",8 "jsdelivr": "dist/immer.umd.js",9 "module": "dist/immer.module.js",10 "jsnext:main": "dist/immer.module.js",11 "react-native": "dist/immer.module.js",12 "types": "./dist/immer.d.ts",13 "scripts": {14 "test": "jest",15 "test:perf": "NODE_ENV=production yarn-or-npm build && cd __performance_tests__ && babel-node add-data.js && babel-node todo.js && babel-node incremental.js",16 "test:flow": "yarn-or-npm flow check __tests__/flow",17 "test:dts": "tsc -p __tests__/tsconfig.json --noEmit",18 "watch": "jest --watch",19 "coveralls": "jest --coverage && cat ./coverage/lcov.info | ./node_modules/.bin/coveralls && rm -rf ./coverage",20 "build": "rimraf dist/ && yarn-or-npm bili && yarn-or-npm typed",21 "typed": "cpx 'src/immer.{d.ts,js.flow}' dist -v",22 "publish-docs": "cd website && GIT_USER=mweststrate USE_SSH=true yarn run publish-gh-pages",23 "start": "cd website && yarn start"24 },25 "husky": {26 "hooks": {27 "pre-commit": "pretty-quick --staged"28 }29 },30 "repository": {31 "type": "git",32 "url": "https://github.com/immerjs/immer.git"33 },34 "keywords": [35 "immutable",36 "mutable",37 "copy-on-write"38 ],39 "author": "Michel Weststrate",40 "license": "MIT",41 "bugs": {42 "url": "https://github.com/immerjs/immer/issues"43 },44 "homepage": "https://github.com/immerjs/immer#readme",45 "files": [46 "dist",47 "src"48 ],49 "devDependencies": {50 "@babel/cli": "^7.2.3",51 "@babel/core": "^7.3.4",52 "@babel/node": "^7.2.2",53 "@babel/plugin-external-helpers": "^7.2.0",54 "@babel/preset-env": "^7.3.4",55 "@types/jest": "^24.0.11",56 "babel-jest": "^24.4.0",57 "babel-preset-modern-browsers": "^13.1.0",58 "bili": "^4.7.0",59 "coveralls": "^3.0.0",60 "cpx": "^1.5.0",61 "cross-env": "^5.1.3",62 "deep-freeze": "^0.0.1",63 "expect": "^24.7.1",64 "flow-bin": "^0.68.0",65 "husky": "^1.2.0",66 "immutable": "^3.8.2",67 "jest": "^24.7.1",68 "lodash": "^4.17.4",69 "lodash.clonedeep": "^4.5.0",70 "prettier": "1.17.0",71 "pretty-quick": "^1.8.0",72 "regenerator-runtime": "^0.11.1",73 "rimraf": "^2.6.2",74 "seamless-immutable": "^7.1.3",75 "spec.ts": "^1.1.0",76 "typescript": "3.4.3",77 "yarn-or-npm": "^2.0.4"78 },79 "jest": {80 "moduleFileExtensions": [81 "js"82 ],83 "testURL": "http://localhost",84 "transform": {85 "\\.js$": "babel-jest"86 }87 }2 "name": "immer",3 "version": "4.0.0-beta.0",4 "description": "Create your next immutable state by mutating the current one",5 "main": "dist/immer.js",6 "umd:main": "dist/immer.umd.js",7 "unpkg": "dist/immer.umd.js",8 "jsdelivr": "dist/immer.umd.js",9 "module": "dist/immer.module.js",10 "jsnext:main": "dist/immer.module.js",11 "react-native": "dist/immer.module.js",12 "types": "./dist/immer.d.ts",13 "scripts": {14 "test": "jest",15 "test:perf": "NODE_ENV=production yarn-or-npm build && cd __performance_tests__ && babel-node add-data.js && babel-node todo.js && babel-node incremental.js",16 "test:flow": "yarn-or-npm flow check __tests__/flow",17 "test:dts": "tsc -p __tests__/tsconfig.json --noEmit",18 "watch": "jest --watch",19 "coveralls": "jest --coverage && cat ./coverage/lcov.info | ./node_modules/.bin/coveralls && rm -rf ./coverage",20 "build": "rimraf dist/ && yarn-or-npm bili && yarn-or-npm typed",21 "typed": "cpx 'src/immer.{d.ts,js.flow}' dist -v",22 "publish-docs": "cd website && GIT_USER=mweststrate USE_SSH=true yarn run publish-gh-pages",23 "start": "cd website && yarn start"24 },25 "husky": {26 "hooks": {27 "pre-commit": "pretty-quick --staged"28 }29 },30 "repository": {31 "type": "git",32 "url": "https://github.com/immerjs/immer.git"33 },34 "keywords": [35 "immutable",36 "mutable",37 "copy-on-write"38 ],39 "author": "Michel Weststrate",40 "license": "MIT",41 "bugs": {42 "url": "https://github.com/immerjs/immer/issues"43 },44 "homepage": "https://github.com/immerjs/immer#readme",45 "files": [46 "dist",47 "src"48 ],49 "devDependencies": {50 "@babel/cli": "^7.2.3",51 "@babel/core": "^7.3.4",52 "@babel/node": "^7.2.2",53 "@babel/plugin-external-helpers": "^7.2.0",54 "@babel/preset-env": "^7.3.4",55 "@types/jest": "^24.0.11",56 "babel-jest": "^24.4.0",57 "babel-preset-modern-browsers": "^13.1.0",58 "bili": "^4.7.0",59 "coveralls": "^3.0.0",60 "cpx": "^1.5.0",61 "cross-env": "^5.1.3",62 "deep-freeze": "^0.0.1",63 "expect": "^24.7.1",64 "flow-bin": "^0.68.0",65 "husky": "^1.2.0",66 "immutable": "^3.8.2",67 "jest": "^24.7.1",68 "lodash": "^4.17.4",69 "lodash.clonedeep": "^4.5.0",70 "prettier": "1.17.0",71 "pretty-quick": "^1.8.0",72 "regenerator-runtime": "^0.11.1",73 "rimraf": "^2.6.2",74 "seamless-immutable": "^7.1.3",75 "spec.ts": "^1.1.0",76 "typescript": "3.6.4",77 "yarn-or-npm": "^2.0.4"78 },79 "jest": {80 "moduleFileExtensions": [81 "js"82 ],83 "testURL": "http://localhost",84 "transform": {85 "\\.js$": "babel-jest"86 }87 }88}
modified:yarn.lock+4 added-4 removed
6052 unmodified lines
6053 integrity sha1-WITKtRLPHTVeP7eE8wgEsrUg23I=6054 dependencies:6055 prelude-ls "~1.1.2"60566057typescript@3.4.3:6058 version "3.4.3"6059 resolved "https://registry.yarnpkg.com/typescript/-/typescript-3.4.3.tgz#0eb320e4ace9b10eadf5bc6103286b0f8b7c224f"6060 integrity sha512-FFgHdPt4T/duxx6Ndf7hwgMZZjZpB+U0nMNGVCYPq0rEzWKjEDobm4J6yb3CS7naZ0yURFqdw9Gwc7UOh/P9oQ==6057typescript@3.6.4:6058 version "3.6.4"6059 resolved "https://registry.yarnpkg.com/typescript/-/typescript-3.6.4.tgz#b18752bb3792bc1a0281335f7f6ebf1bbfc5b91d"6060 integrity sha512-unoCll1+l+YK4i4F8f22TaNVPRHcD9PA3yCuZ8g5e0qGqlVlJ/8FSateOLLSagn+Yg5+ZwuPkL8LFUc0Jcvksg==60616062uglify-js@^3.1.4:6063 version "3.5.3"6064 resolved "https://registry.yarnpkg.com/uglify-js/-/uglify-js-3.5.3.tgz#d490bb5347f23025f0c1bc0dee901d98e4d6b063"
301 unmodified lines