Skip to content
Myr

feat: rewrote Map and Set implementation, code base cleanup

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

Fixes #472, #466, #449, #492. Also drops bundle size with ~10%.

authored by Michel Weststrate · committed by Michel Weststrate · parents 98794b8, f4a4701 · Browse files · 20 files+1624 added−1088 removed
This commit

State

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

Diff stats

20 files+1624 added−1088 removed

  • tests:+510 added−55 removed
  • other:+1114 added−1033 removed

20 files+1624 added−1088 removed

modified:__tests__/base.js+177 added-21 removed
186 unmodified lines
187 expect(nextState).toBe(baseState)188 })189190 it("supports iteration", () => {191 const base = [{id: 1, a: 1}, {id: 2, a: 1}]191 const base = [192 {id: 1, a: 1},193 {id: 2, a: 1}194 ]195 const findById = (collection, id) => {196 for (const item of collection) {197 if (item.id === id) return item198 }
189 unmodified lines
388 expect(result.get("second").a).toEqual(2)389 })390391 it("supports 'keys", () => {389 const base = new Map([["first", Symbol()], ["second", Symbol()]])392 const base = new Map([393 ["first", Symbol()],394 ["second", Symbol()]395 ])396 const result = produce(base, draft => {397 expect([...draft.keys()]).toEqual(["first", "second"])398 draft.set("third", Symbol())399 expect([...draft.keys()]).toEqual(["first", "second", "third"])
95 unmodified lines
495496 it("can use 'delete' to remove items", () => {497 const nextState = produce(baseState, s => {498 expect(s.aMap.has("jedi")).toBe(true)493 s.aMap.delete("jedi")499 expect(s.aMap.delete("jedi")).toBe(true)500 expect(s.aMap.has("jedi")).toBe(false)501 })502 expect(nextState.aMap).not.toBe(baseState.aMap)503 expect(nextState.aMap.size).toBe(baseState.aMap.size - 1)
36 unmodified lines
540 )541 expect(base.get("first").get("second").prop).toBe("test")542 expect(result.get("first").get("second").prop).toBe("test1")543 })544545 it("treats void deletes as no-op", () => {546 const base = new Map([["x", 1]])547 const next = produce(base, d => {548 expect(d.delete("y")).toBe(false)549 })550 expect(next).toBe(base)551 })552553 it("revokes map proxies", () => {554 let m555 produce(baseState, s => {556 m = s.aMap557 })558 expect(() => m.get("x")).toThrow(559 "Cannot use a proxy that has been revoked"560 )561 expect(() => m.set("x", 3)).toThrow(562 "Cannot use a proxy that has been revoked"563 )564 })565566 it("does not draft map keys", () => {567 // anything else would be terribly confusing568 const key = {a: 1}569 const map = new Map([[key, 2]])570 const next = produce(map, d => {571 const dKey = Array.from(d.keys())[0]572 expect(isDraft(dKey)).toBe(false)573 expect(dKey).toBe(key)574 dKey.a += 1575 d.set(dKey, d.get(dKey) + 1)576 d.set(key, d.get(key) + 1)577 expect(d.get(key)).toBe(4)578 expect(key.a).toBe(2)579 })580 const entries = Array.from(next.entries())581 expect(entries).toEqual([[key, 4]])582 expect(entries[0][0]).toBe(key)583 expect(entries[0][0].a).toBe(2)584 })585 })586587 describe("set drafts", () => {588 it("supports iteration", () => {542 const base = new Set([{id: 1, a: 1}, {id: 2, a: 1}])589 const base = new Set([590 {id: 1, a: 1},591 {id: 2, a: 1}592 ])593 const findById = (set, id) => {594 for (const item of set) {595 if (item.id === id) return item596 }
5 unmodified lines
602 obj1.a = 2603 obj2.a = 2604 })605 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}]))606 expect(base).toEqual(607 new Set([608 {id: 1, a: 1},609 {id: 2, a: 1}610 ])611 )612 expect(result).toEqual(613 new Set([614 {id: 1, a: 2},615 {id: 2, a: 2}616 ])617 )618 })619620 it("supports 'entries'", () => {561 const base = new Set([{id: 1, a: 1}, {id: 2, a: 1}])621 const base = new Set([622 {id: 1, a: 1},623 {id: 2, a: 1}624 ])625 const findById = (set, id) => {626 for (const [item1, item2] of set.entries()) {627 expect(item1).toBe(item2)628 if (item1.id === id) return item1
6 unmodified lines
635 obj1.a = 2636 obj2.a = 2637 })638 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}]))639 expect(base).toEqual(640 new Set([641 {id: 1, a: 1},642 {id: 2, a: 1}643 ])644 )645 expect(result).toEqual(646 new Set([647 {id: 1, a: 2},648 {id: 2, a: 2}649 ])650 )651 })652653 it("supports 'values'", () => {581 const base = new Set([{id: 1, a: 1}, {id: 2, a: 1}])654 const base = new Set([655 {id: 1, a: 1},656 {id: 2, a: 1}657 ])658 const findById = (set, id) => {659 for (const item of set.values()) {660 if (item.id === id) return item661 }
5 unmodified lines
667 obj1.a = 2668 obj2.a = 2669 })670 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}]))671 expect(base).toEqual(672 new Set([673 {id: 1, a: 1},674 {id: 2, a: 1}675 ])676 )677 expect(result).toEqual(678 new Set([679 {id: 1, a: 2},680 {id: 2, a: 2}681 ])682 )683 })684685 it("supports 'keys'", () => {600 const base = new Set([{id: 1, a: 1}, {id: 2, a: 1}])686 const base = new Set([687 {id: 1, a: 1},688 {id: 2, a: 1}689 ])690 const findById = (set, id) => {691 for (const item of set.keys()) {692 if (item.id === id) return item693 }
5 unmodified lines
699 obj1.a = 2700 obj2.a = 2701 })702 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}]))703 expect(base).toEqual(704 new Set([705 {id: 1, a: 1},706 {id: 2, a: 1}707 ])708 )709 expect(result).toEqual(710 new Set([711 {id: 1, a: 2},712 {id: 2, a: 2}713 ])714 )715 })716717 it("supports forEach with mutation after reads", () => {619 const base = new Set([{id: 1, a: 1}, {id: 2, a: 2}])718 const base = new Set([719 {id: 1, a: 1},720 {id: 2, a: 2}721 ])722 const result = produce(base, draft => {723 let sum1 = 0724 draft.forEach(({a}) => {725 sum1 += a
6 unmodified lines
732 })733 expect(sum2).toBe(23)734 })735 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}]))736 expect(base).toEqual(737 new Set([738 {id: 1, a: 1},739 {id: 2, a: 2}740 ])741 )742 expect(result).toEqual(743 new Set([744 {id: 1, a: 11},745 {id: 2, a: 12}746 ])747 )748 })749750 it("state stays the same if the same item is added", () => {751 const nextState = produce(baseState, s => {
28 unmodified lines
780781 it("can use 'delete' to remove items", () => {782 const nextState = produce(baseState, s => {783 expect(s.aSet.has("Luke")).toBe(true)672 s.aSet.delete("Luke")784 expect(s.aSet.delete("Luke")).toBe(true)785 expect(s.aSet.delete("Luke")).toBe(false)786 expect(s.aSet.has("Luke")).toBe(false)787 })788 expect(nextState.aSet).not.toBe(baseState.aSet)676 expect(nextState.aSet.size).toBe(baseState.aSet.size - 1)789 expect(baseState.aSet.has("Luke")).toBe(true)790 expect(nextState.aSet.has("Luke")).toBe(false)791 expect(nextState.aSet.size).toBe(baseState.aSet.size - 1)792 })793794 it("can use 'clear' to remove items", () => {795 const nextState = produce(baseState, s => {
26 unmodified lines
822 expect(result).not.toBe(base)823 expect(base).toEqual(new Set([new Set(["Serenity"])]))824 expect(result).toEqual(new Set([new Set(["Serenity", "Firefly"])]))825 })826827 it("supports has / delete on elements from the original", () => {828 const obj = {}829 const set = new Set([obj])830 const next = produce(set, d => {831 expect(d.has(obj)).toBe(true)832 d.add(3)833 expect(d.has(obj)).toBe(true)834 d.delete(obj)835 expect(d.has(obj)).toBe(false)836 })837 expect(next).toEqual(new Set([3]))838 })839840 it("revokes sets", () => {841 let m842 produce(baseState, s => {843 m = s.aSet844 })845 expect(() => m.has("x")).toThrow(846 "Cannot use a proxy that has been revoked"847 )848 expect(() => m.add("x")).toThrow(849 "Cannot use a proxy that has been revoked"850 )851 })852 })853854 it("supports `immerable` symbol on constructor", () => {855 class One {}
518 unmodified lines
1374 expect(base[0].a).toEqual(1)1375 expect(result[0].a).toEqual(2)1376 })13771378 it("does not draft external data", () => {1379 const externalData = {x: 3}1380 const base = {}1381 const next = produce(base, draft => {1382 // potentially, we *could* draft external data automatically, but only if those statements are not switched...1383 draft.y = externalData1384 draft.y.x += 11385 externalData.x += 11386 })1387 expect(next).toEqual({y: {x: 5}})1388 expect(externalData.x).toBe(5)1389 expect(next.y).toBe(externalData)1390 })13911392 autoFreeze &&1393 test("issue #469, state not frozen", () => {1394 const project = produce(1395 {
354 unmodified lines
1750 const b = {b: 2}1751 const c = {c: 3}1752 const set1 = new Set([a, b])1753 const set2 = new Set([c])1601 const map = new Map([["set1", set1], ["set2", set2]])1754 const map = new Map([1755 ["set1", set1],1756 ["set2", set2]1757 ])1758 const base = {map}17591760 function first(set) {1761 return Array.from(set.values())[0]
166 unmodified lines
modified:__tests__/empty.ts+134 added-6 removed
added:__tests__/map-set.js+197 added
1"use strict"2import {Immer, nothing, original, isDraft, immerable} from "../src/index"3import {each, shallowCopy, isEnumerable, DRAFT_STATE} from "../src/common"45jest.setTimeout(1000)67runBaseTest("proxy (no freeze)", true, false)8// runBaseTest("proxy (autofreeze)", true, true)9// runBaseTest("proxy (autofreeze)(patch listener)", true, true, true)10// runBaseTest("es5 (no freeze)", false, false)11// runBaseTest("es5 (autofreeze)", false, true)12// runBaseTest("es5 (autofreeze)(patch listener)", false, true, true)1314function runBaseTest(name, useProxies, autoFreeze, useListener) {15 const listener = useListener ? function() {} : undefined16 const {produce, produceWithPatches} = createPatchedImmer({17 useProxies,18 autoFreeze19 })2021 // When `useListener` is true, append a function to the arguments of every22 // uncurried `produce` call in every test. This makes tests easier to read.23 function createPatchedImmer(options) {24 const immer = new Immer(options)2526 const {produce} = immer27 immer.produce = function(...args) {28 return typeof args[1] === "function" && args.length < 329 ? produce(...args, listener)30 : produce(...args)31 }3233 return immer34 }3536 describe("map issues " + name, () => {37 test("#472 ", () => {38 const project = produce(new Map(), draft => {39 draft.set("bar1", {blocked: false})40 draft.set("bar2", {blocked: false})41 })4243 // Read before write -- no error44 produce(project, draft => {45 const bar1 = draft.get("bar1")46 const bar2 = draft.get("bar2")47 bar1.blocked = true48 bar2.blocked = true49 })5051 // Read/write interleaved -- error52 produce(project, draft => {53 const bar1 = draft.get("bar1")54 bar1.blocked = true55 const bar2 = draft.get("bar2")56 bar2.blocked = true // TypeError: "blocked" is read-only57 })58 })5960 test("#466 - setNoPatches", () => {61 const obj = {62 set: new Set()63 }6465 const result = produceWithPatches(obj, draft => {66 draft.set.add("abc")67 })68 expect(result).toEqual([69 {set: new Set(["abc"])},70 [{op: "add", path: ["set", 0], value: "abc"}],71 [{op: "remove", path: ["set", 0], value: "abc"}]72 ])73 })7475 test("#466 - mapChangeBug ", () => {76 const obj = {77 map: new Map([78 ["a", new Map([["b", true], ["c", true], ["d", true]])],79 ["b", new Map([["a", true]])],80 ["c", new Map([["a", true]])],81 ["d", new Map([["a", true]])]82 ])83 }84 const result = produceWithPatches(obj, draft => {85 const aMap = draft.map.get("a")86 aMap.forEach((_, other) => {87 const otherMap = draft.map.get(other)88 otherMap.delete("a")89 })90 })91 expect(result).toEqual([92 {93 map: new Map([94 ["a", new Map([["b", true], ["c", true], ["d", true]])],95 ["b", new Map()],96 ["c", new Map()],97 ["d", new Map()]98 ])99 },100 [101 {102 op: "remove",103 path: ["map", "b", "a"]104 },105 {106 op: "remove",107 path: ["map", "c", "a"]108 },109 {110 op: "remove",111 path: ["map", "d", "a"]112 }113 ],114 [115 {116 op: "add",117 path: ["map", "b", "a"],118 value: true119 },120 {121 op: "add",122 path: ["map", "c", "a"],123 value: true124 },125 {126 op: "add",127 path: ["map", "d", "a"],128 value: true129 }130 ]131 ])132 })133134 test("#466 - mapChangeBug2 ", () => {135 const obj = {136 map: new Map([137 ["a", new Map([["b", true], ["c", true], ["d", true]])],138 ["b", new Map([["a", true]])],139 ["c", new Map([["a", true]])],140 ["d", new Map([["a", true]])]141 ])142 }143 const obj1 = produce(obj, draft => {})144 const [result, p, ip] = produceWithPatches(obj1, draft => {145 const aMap = draft.map.get("a")146 aMap.forEach((_, other) => {147 const otherMap = draft.map.get(other)148 otherMap.delete("a")149 })150 })151 expect(result).toEqual(152 {153 map: new Map([154 ["a", new Map([["b", true], ["c", true], ["d", true]])],155 ["b", new Map([])],156 ["c", new Map([])],157 ["d", new Map([])]158 ])159 }160 )161 expect(p).toEqual(162 [163 {164 op: "remove",165 path: ["map", "b", "a"]166 },167 {168 op: "remove",169 path: ["map", "c", "a"]170 },171 {172 op: "remove",173 path: ["map", "d", "a"]174 }175 ])176 expect(ip).toEqual(177 [178 {179 op: "add",180 path: ["map", "b", "a"],181 value: true182 },183 {184 op: "add",185 path: ["map", "c", "a"],186 value: true187 },188 {189 op: "add",190 path: ["map", "d", "a"],191 value: true192 }193 ]194 )195 })196 })197}
modified:__tests__/polyfills.js-27 removed
modified:__tests__/tsconfig.json+2 added-1 removed
modified:docs/complex-objects.md+2 added
70 unmodified lines
7172When working with `Date` objects, you should always create a new `Date` instance instead of mutating an existing `Date` object.7374Maps 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.7576_Note: The **keys** of a map are never drafted! This is done to avoid confusing semantics and keep keys always referentially equal_
modified:docs/pitfalls.md+17 added
modified:src/common.ts+144 added-182 removed
1import {Objectish, ObjectishNoSet, ImmerState} from "./types"1import {2 Objectish,3 Drafted,4 AnyObject,5 AnyArray,6 AnyMap,7 AnySet,8 ImmerState,9 ProxyType,10 Archtype11} from "./types"1213/** Use a class type for `nothing` so its type is unique */14export class Nothing {15 // This lets us do `Exclude<T, Nothing>`6 // TODO: do this better, use unique symbol instead7 private _: any16 // @ts-ignore17 private _!: unique symbol18}1920const hasSymbol = typeof Symbol !== "undefined"21export const hasMap = typeof Map !== "undefined"22export const hasSet = typeof Set !== "undefined"2324/**25 * The sentinel value returned by producers to replace the draft with undefined.26 */13export const NOTHING: Nothing =14 typeof Symbol !== "undefined"15 ? Symbol("immer-nothing")16 : ({["immer-nothing"]: true} as any)27export const NOTHING: Nothing = hasSymbol28 ? Symbol("immer-nothing")29 : ({["immer-nothing"]: true} as any)3031/**32 * To let Immer treat your class instances as plain immutable objects33 * (albeit with a custom prototype), you must define either an instance property
1 unmodified line
35 *36 * Otherwise, your class instance will never be drafted, which means it won't be37 * safe to mutate in a produce callback.38 */26export const DRAFTABLE: unique symbol =27 typeof Symbol !== "undefined" && Symbol.for28 ? Symbol.for("immer-draftable")29 : ("__$immer_draftable" as any)39export const DRAFTABLE: unique symbol = hasSymbol40 ? Symbol("immer-draftable")41 : ("__$immer_draftable" as any)4231export const DRAFT_STATE: unique symbol =32 typeof Symbol !== "undefined" && Symbol.for33 ? Symbol.for("immer-state")34 : ("__$immer_state" as any)43export const DRAFT_STATE: unique symbol = hasSymbol44 ? Symbol("immer-state")45 : ("__$immer_state" as any)4647export const iteratorSymbol: typeof Symbol.iterator = hasSymbol48 ? Symbol.iterator49 : ("@@iterator" as any)5051/** Returns true if the given value is an Immer draft */52export function isDraft(value: any): boolean {53 return !!value && !!value[DRAFT_STATE]54}
2 unmodified lines
57export function isDraftable(value: any): boolean {58 if (!value) return false59 return (60 isPlainObject(value) ||61 Array.isArray(value) ||62 !!value[DRAFTABLE] ||63 !!value.constructor[DRAFTABLE] ||64 isMap(value) ||65 isSet(value)66 )67}6853export function isPlainObject(value): boolean {69export function isPlainObject(value: any): boolean {70 if (!value || typeof value !== "object") return false55 if (Array.isArray(value)) return true71 const proto = Object.getPrototypeOf(value)72 return !proto || proto === Object.prototype73}7475/** Get the underlying object that is represented by the given draft */61export function original<T>(value: T): T | undefined {76export function original<T>(value: Drafted<T>): T | undefined {77 if (value && value[DRAFT_STATE]) {63 return value[DRAFT_STATE].base78 return value[DRAFT_STATE].base as any79 }80 // otherwise return undefined81}8268// We use Maps as `drafts` for Sets, not Objects69// See proxy.js70export function assignSet(target: Map<any, any>, override) {71 override.forEach(value => {72 // When we add new drafts we have to remove their originals if present73 const prev = original(value)74 if (prev) target.delete(prev)75 // @ts-ignore TODO investigate76 target.add(value)77 })78 return target79}8081// We use Maps as `drafts` for Maps, not Objects82// See proxy.js83export function assignMap(target: Map<any, any>, override: Map<any, any>) {84 override.forEach((value, key) => target.set(key, value))85 return target86}8788export const assign =89 Object.assign ||90 ((target, ...overrides) => {91 overrides.forEach(override => {92 if (typeof override === "object" && override !== null)93 Object.keys(override).forEach(key => (target[key] = override[key]))94 })95 return target96 })9798export const ownKeys: (target) => PropertyKey[] =83export const ownKeys: (target: AnyObject) => PropertyKey[] =84 typeof Reflect !== "undefined" && Reflect.ownKeys85 ? Reflect.ownKeys86 : typeof Object.getOwnPropertySymbols !== "undefined"87 ? obj =>103 Object.getOwnPropertyNames(obj).concat(Object.getOwnPropertySymbols(104 obj105 ) as any)106 : Object.getOwnPropertyNames88 Object.getOwnPropertyNames(obj).concat(89 Object.getOwnPropertySymbols(obj) as any90 )91 : /* istanbul ignore next */ Object.getOwnPropertyNames92108export function shallowCopy<T extends Objectish>(109 base: T,110 invokeGetters?: boolean111): T112export function shallowCopy(base, invokeGetters = false) {113 if (Array.isArray(base)) return base.slice()114 if (isMap(base)) return new Map(base)115 if (isSet(base)) return new Set(base)116 const clone = Object.create(Object.getPrototypeOf(base))117 ownKeys(base).forEach(key => {118 if (key === DRAFT_STATE) {119 return // Never copy over draft state.120 }121 const desc = Object.getOwnPropertyDescriptor(base, key)!122 let {value} = desc123 if (desc.get) {124 if (!invokeGetters) {125 throw new Error("Immer drafts cannot have computed properties")126 }127 value = desc.get.call(base)128 }129 if (desc.enumerable) {130 clone[key] = value131 } else {132 Object.defineProperty(clone, key, {133 value,134 writable: true,135 configurable: true136 })137 }138 })139 return clone140}14193export function each<T extends Objectish>(94 obj: T,144 iter: (key: PropertyKey, value: any, source: T) => void145)146export function each(obj, iter) {147 if (Array.isArray(obj) || isMap(obj) || isSet(obj)) {148 obj.forEach((entry, index) => iter(index, entry, obj))149 } else {95 iter: (key: string | number, value: any, source: T) => void96): void97export function each(obj: any, iter: any) {98 if (getArchtype(obj) === Archtype.Object) {99 ownKeys(obj).forEach(key => iter(key, obj[key], obj))100 } else {101 obj.forEach((entry: any, index: any) => iter(index, entry, obj))102 }103}104154export function isEnumerable(base: {}, prop: PropertyKey): boolean {105export function isEnumerable(base: AnyObject, prop: PropertyKey): boolean {106 const desc = Object.getOwnPropertyDescriptor(base, prop)107 return desc && desc.enumerable ? true : false108}109159export function has(thing: ObjectishNoSet, prop: PropertyKey): boolean {160 return isMap(thing)110export function getArchtype(thing: any): Archtype {111 /* istanbul ignore next */112 if (!thing) die()113 if (thing[DRAFT_STATE]) {114 switch ((thing as Drafted)[DRAFT_STATE].type) {115 case ProxyType.ES5Object:116 case ProxyType.ProxyObject:117 return Archtype.Object118 case ProxyType.ES5Array:119 case ProxyType.ProxyArray:120 return Archtype.Array121 case ProxyType.Map:122 return Archtype.Map123 case ProxyType.Set:124 return Archtype.Set125 }126 }127 return Array.isArray(thing)128 ? Archtype.Array129 : isMap(thing)130 ? Archtype.Map131 : isSet(thing)132 ? Archtype.Set133 : Archtype.Object134}135136export function has(thing: any, prop: PropertyKey): boolean {137 return getArchtype(thing) === Archtype.Map138 ? thing.has(prop)139 : Object.prototype.hasOwnProperty.call(thing, prop)140}141165export function get(thing: ObjectishNoSet, prop: PropertyKey) {166 return isMap(thing) ? thing.get(prop) : thing[prop]142export function get(thing: AnyMap | AnyObject, prop: PropertyKey): any {143 // @ts-ignore144 return getArchtype(thing) === Archtype.Map ? thing.get(prop) : thing[prop]145}146147export function set(thing: any, propOrOldValue: PropertyKey, value: any) {148 switch (getArchtype(thing)) {149 case Archtype.Map:150 thing.set(propOrOldValue, value)151 break152 case Archtype.Set:153 thing.delete(propOrOldValue)154 thing.add(value)155 break156 default:157 thing[propOrOldValue] = value158 }159}160169export function is(x, y): boolean {161export function is(x: any, y: any): boolean {162 // From: https://github.com/facebook/fbjs/blob/c69904a511b900266935168223063dd8772dfc40/packages/fbjs/src/core/shallowEqual.js163 if (x === y) {164 return x !== 0 || 1 / x === 1 / y165 } else {166 return x !== x && y !== y167 }168}169178export const hasSymbol = typeof Symbol !== "undefined"179180export const hasMap = typeof Map !== "undefined"181182export function isMap(target): target is Map<any, any> {170export function isMap(target: any): target is AnyMap {171 return hasMap && target instanceof Map172}173186export const hasSet = typeof Set !== "undefined"187188export function isSet(target): target is Set<any> {174export function isSet(target: any): target is AnySet {175 return hasSet && target instanceof Set176}177192export function makeIterable(next: () => {done: boolean; value: any}) {193 let self194 return (self = {195 [Symbol.iterator]: () => self,196 next197 })178export function latest(state: ImmerState): any {179 return state.copy || state.base180}181200/** Map.prototype.values _-or-_ Map.prototype.entries */201export function iterateMapValues(state, prop, receiver) {202 const isEntries = prop !== "values"203 return () => {204 const iterator = latest(state)[Symbol.iterator]()205 return makeIterable(() => {206 const result = iterator.next()207 if (!result.done) {208 const [key] = result.value209 const value = receiver.get(key)210 result.value = isEntries ? [key, value] : value211 }212 return result213 })214 }215}216217export function makeIterateSetValues(createProxy) {218 function iterateSetValues(state, prop?) {219 const isEntries = prop === "entries"220 return () => {221 const iterator = latest(state)[Symbol.iterator]()222 return makeIterable(() => {223 const result = iterator.next()224 if (!result.done) {225 const value = wrapSetValue(state, result.value)226 result.value = isEntries ? [value, value] : value227 }228 return result229 })182export function shallowCopy<T extends AnyObject | AnyArray>(183 base: T,184 invokeGetters?: boolean185): T186export function shallowCopy(base: any, invokeGetters = false) {187 if (Array.isArray(base)) return base.slice()188 const clone = Object.create(Object.getPrototypeOf(base))189 ownKeys(base).forEach(key => {190 if (key === DRAFT_STATE) {191 return // Never copy over draft state.192 }231 }232233 function wrapSetValue(state, value) {234 const key = original(value) || value235 let draft = state.drafts.get(key)236 if (!draft) {237 if (state.finalized || !isDraftable(value) || state.finalizing) {238 return value193 const desc = Object.getOwnPropertyDescriptor(base, key)!194 let {value} = desc195 if (desc.get) {196 if (!invokeGetters) {197 throw new Error("Immer drafts cannot have computed properties")198 }240 draft = createProxy(value, state)241 state.drafts.set(key, draft)242 if (state.modified) {243 state.copy.add(draft)244 }199 value = desc.get.call(base)200 }246 return draft247 }248249 return iterateSetValues201 if (desc.enumerable) {202 clone[key] = value203 } else {204 Object.defineProperty(clone, key, {205 value,206 writable: true,207 configurable: true208 })209 }210 })211 return clone212}213252function latest<T = any>(state: ImmerState<T>): T {253 return state.copy || state.base254}255256export function clone<T extends Objectish>(obj: T): T257export function clone(obj) {258 if (!isDraftable(obj)) return obj259 if (Array.isArray(obj)) return obj.map(clone)260 if (isMap(obj)) return new Map(obj)261 if (isSet(obj)) return new Set(obj)262 const cloned = Object.create(Object.getPrototypeOf(obj))263 for (const key in obj) cloned[key] = clone(obj[key])264 return cloned265}266267export function freeze<T extends Objectish>(268 obj: T,269 deep: boolean = false270): void {214export function freeze(obj: any, deep: boolean): void {215 if (!isDraftable(obj) || isDraft(obj) || Object.isFrozen(obj)) return272 if (isSet(obj)) {216 const type = getArchtype(obj)217 if (type === Archtype.Set) {218 obj.add = obj.clear = obj.delete = dontMutateFrozenCollections as any274 } else if (isMap(obj)) {219 } else if (type === Archtype.Map) {220 obj.set = obj.clear = obj.delete = dontMutateFrozenCollections as any221 }222 Object.freeze(obj)223 if (deep) each(obj, (_, value) => freeze(value, true))
1 unmodified line
225226function dontMutateFrozenCollections() {227 throw new Error("This object has been frozen and should not be mutated")228}229230export function createHiddenProperty(231 target: AnyObject,232 prop: PropertyKey,233 value: any234) {235 Object.defineProperty(target, prop, {236 value: value,237 enumerable: false,238 writable: true239 })240}241242/* istanbul ignore next */243export function die(): never {244 throw new Error("Illegal state, please file a bug")245}
modified:src/es5.ts+94 added-283 removed
4 unmodified lines
5 is,6 isDraft,7 isDraftable,8 isEnumerable,9 isMap,10 isSet,11 hasSymbol,9 shallowCopy,10 DRAFT_STATE,14 iterateMapValues,15 makeIterable,16 makeIterateSetValues11 latest,12 createHiddenProperty13} from "./common"1415import {ImmerScope} from "./scope"19import {ImmerState} from "./types"16import {17 ImmerState,18 Drafted,19 AnyObject,20 Objectish,21 ImmerBaseState,22 AnyArray,23 ProxyType24} from "./types"25import {MapState} from "./map"26import {SetState} from "./set"2721interface ES5Draft {22 [DRAFT_STATE]: ES5State23}2425// TODO: merge with ImmerState?26interface ES5State<T = any> {27 scope: ImmerScope28 modified: boolean28interface ES5BaseState extends ImmerBaseState {29 finalizing: boolean30 finalized: boolean31 assigned: Map<any, any> | {[key: string]: any}32 parent: ES5State30 assigned: {[key: string]: any}31 parent?: ImmerState33 base: T34 draft: T & ES5Draft35 drafts: Map<any, any> | null36 copy: T | null37 revoke()32 revoked: boolean33}3435export interface ES5ObjectState extends ES5BaseState {36 type: ProxyType.ES5Object37 draft: Drafted<AnyObject, ES5ObjectState>38 base: AnyObject39 copy: AnyObject | null40}4142export interface ES5ArrayState extends ES5BaseState {43 type: ProxyType.ES5Array44 draft: Drafted<AnyObject, ES5ArrayState>45 base: AnyArray46 copy: AnyArray | null47}4849type ES5State = ES5ArrayState | ES5ObjectState5041export function willFinalize(51export function willFinalizeES5(52 scope: ImmerScope,53 result: any,54 isReplaced: boolean55) {
12 unmodified lines
68 markChangesSweep(scope.drafts)69 }70}7162export function createProxy<T>(base: T, parent: ES5State): ES5Draft {72export function createES5Proxy<T>(73 base: T,74 parent?: ImmerState75): Drafted<T, ES5ObjectState | ES5ArrayState> {76 const isArray = Array.isArray(base)77 const draft = clonePotentialDraft(base)7866 if (isMap(base)) {67 proxyMap(draft)68 } else if (isSet(base)) {69 proxySet(draft)70 } else {71 each(draft, prop => {72 proxyProperty(draft, prop, isArray || isEnumerable(base, prop))73 })79 each(draft, prop => {80 proxyProperty(draft, prop, isArray || isEnumerable(base, prop))81 })74 }8276 // See "proxy.js" for property documentation.77 const scope = parent ? parent.scope : ImmerScope.current!78 const state: ES5State<T> = {79 scope,83 const state: ES5ObjectState | ES5ArrayState = {84 type: isArray ? ProxyType.ES5Array : (ProxyType.ES5Object as any),85 scope: parent ? parent.scope : ImmerScope.current!,86 modified: false,81 finalizing: false, // es5 only87 finalizing: false,88 finalized: false,83 assigned: isMap(base) ? new Map() : {},89 assigned: {},90 parent,91 base,92 draft,87 drafts: isSet(base) ? new Map() : null,93 copy: null,89 revoke,90 revoked: false // es5 only94 revoked: false,95 isManual: false96 }9798 createHiddenProperty(draft, DRAFT_STATE, state)94 scope.drafts!.push(draft)99 return draft100}10198function revoke(this: ES5State) {99 this.revoked = true100}101102function latest(state) {103 return state.copy || state.base104}105102// Access a property without creating an Immer draft.107function peek(draft, prop) {103function peek(draft: Drafted, prop: PropertyKey) {104 const state = draft[DRAFT_STATE]105 if (state && !state.finalizing) {106 state.finalizing = true107 const value = draft[prop]
2 unmodified lines
110 }111 return draft[prop]112}113118function get(state, prop) {114function get(state: ES5State, prop: string | number) {115 assertUnrevoked(state)116 const value = peek(latest(state), prop)117 if (state.finalizing) return value118 // Create a draft if the value is unmodified.119 if (value === peek(state.base, prop) && isDraftable(value)) {120 prepareCopy(state)121 // @ts-ignore125 return (state.copy[prop] = createProxy(value, state))122 return (state.copy![prop] = state.scope.immer.createProxy(value, state))123 }124 return value125}126130function set(state, prop, value) {127function set(state: ES5State, prop: string | number, value: any) {128 assertUnrevoked(state)129 state.assigned[prop] = true130 if (!state.modified) {131 if (is(value, peek(latest(state), prop))) return135 markChanged(state)132 markChangedES5(state)133 prepareCopy(state)134 }135 // @ts-ignore138 state.copy[prop] = value136 state.copy![prop] = value137}138141function markChanged(state) {139export function markChangedES5(state: ImmerState) {140 if (!state.modified) {141 state.modified = true144 if (state.parent) markChanged(state.parent)142 if (state.parent) markChangedES5(state.parent)143 }144}145148function prepareCopy(state) {146function prepareCopy(state: ES5State) {147 if (!state.copy) state.copy = clonePotentialDraft(state.base)148}149152function clonePotentialDraft(base) {153 const state = base && base[DRAFT_STATE]150function clonePotentialDraft(base: Objectish) {151 const state = base && (base as any)[DRAFT_STATE]152 if (state) {153 state.finalizing = true154 const draft = shallowCopy(state.draft, true)155 state.finalizing = false
3 unmodified lines
159}160161// property descriptors are recycled to make sure we don't create a get and set closure per property,162// but share them all instead165const descriptors = {}163const descriptors: {[prop: string]: PropertyDescriptor} = {}164167function proxyProperty(draft, prop, enumerable) {165function proxyProperty(166 draft: Drafted<any, ES5State>,167 prop: string | number,168 enumerable: boolean169) {170 let desc = descriptors[prop]171 if (desc) {172 desc.enumerable = enumerable173 } else {174 descriptors[prop] = desc = {175 configurable: true,176 enumerable,175 get() {177 get(this: any) {178 return get(this[DRAFT_STATE], prop)179 },178 set(value) {180 set(this: any, value) {181 set(this[DRAFT_STATE], prop, value)182 }183 }184 }185 Object.defineProperty(draft, prop, desc)186}187186function proxyMap(target) {187 Object.defineProperties(target, mapTraps)188189 if (hasSymbol) {190 Object.defineProperty(191 target,192 Symbol.iterator,193 // @ts-ignore194 proxyMethod(iterateMapValues) //TODO: , Symbol.iterator)195 )196 }197}198199const mapTraps = finalizeTraps({200 size: state => latest(state).size,201 has: state => key => latest(state).has(key),202 set: state => (key, value) => {203 if (latest(state).get(key) !== value) {204 prepareCopy(state)205 markChanged(state)206 state.assigned.set(key, true)207 state.copy.set(key, value)208 }209 return state.draft210 },211 delete: state => key => {212 prepareCopy(state)213 markChanged(state)214 state.assigned.set(key, false)215 state.copy.delete(key)216 return false217 },218 clear: state => () => {219 if (!state.copy) {220 prepareCopy(state)221 }222 markChanged(state)223 state.assigned = new Map()224 for (const key of latest(state).keys()) {225 state.assigned.set(key, false)226 }227 return state.copy.clear()228 },229 forEach: (state, key, reciever) => cb => {230 latest(state).forEach((value, key, map) => {231 cb(reciever.get(key), key, map)232 })233 },234 get: state => key => {235 const value = latest(state).get(key)236237 if (state.finalizing || state.finalized || !isDraftable(value)) {238 return value239 }240241 if (value !== state.base.get(key)) {242 return value243 }244 const draft = createProxy(value, state)245 prepareCopy(state)246 state.copy.set(key, draft)247 return draft248 },249 keys: state => () => latest(state).keys(),250 values: iterateMapValues,251 entries: iterateMapValues252})253254function proxySet(target) {255 Object.defineProperties(target, setTraps)256257 if (hasSymbol) {258 Object.defineProperty(259 target,260 Symbol.iterator,261 // @ts-ignore262 proxyMethod(iterateSetValues) //TODO: , Symbol.iterator)263 )264 }265}266267const iterateSetValues = makeIterateSetValues(createProxy)268269const setTraps = finalizeTraps({270 size: state => {271 return latest(state).size272 },273 add: state => value => {274 if (!latest(state).has(value)) {275 markChanged(state)276 if (!state.copy) {277 prepareCopy(state)278 }279 state.copy.add(value)280 }281 return state.draft282 },283 delete: state => value => {284 markChanged(state)285 if (!state.copy) {286 prepareCopy(state)287 }288 return state.copy.delete(value)289 },290 has: state => key => {291 return latest(state).has(key)292 },293 clear: state => () => {294 markChanged(state)295 if (!state.copy) {296 prepareCopy(state)297 }298 return state.copy.clear()299 },300 keys: iterateSetValues,301 entries: iterateSetValues,302 values: iterateSetValues,303 forEach: state => (cb, thisArg) => {304 const iterator = iterateSetValues(state)()305 let result = iterator.next()306 while (!result.done) {307 cb.call(thisArg, result.value, result.value, state.draft)308 result = iterator.next()309 }310 }311})312313function finalizeTraps(traps) {314 return Object.keys(traps).reduce(function(acc, key) {315 const builder = key === "size" ? proxyAttr : proxyMethod316 acc[key] = builder(traps[key], key)317 return acc318 }, {})319}320321function proxyAttr(fn) {322 return {323 get() {324 const state = this[DRAFT_STATE]325 assertUnrevoked(state)326 return fn(state)327 }328 }329}330331function proxyMethod(trap, key) {332 return {333 get() {334 return function(this: ES5Draft, ...args) {335 const state = this[DRAFT_STATE]336 assertUnrevoked(state)337 return trap(state, key, state.draft)(...args)338 }339 }340 }341}342343function assertUnrevoked(state) {188export function assertUnrevoked(state: ES5State | MapState | SetState) {189 if (state.revoked === true)190 throw new Error(191 "Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? " +192 JSON.stringify(latest(state))193 )194}195196// This looks expensive, but only proxies are visited, and only objects without known changes are scanned.352function markChangesSweep(drafts) {197function markChangesSweep(drafts: Drafted<any, ImmerState>[]) {198 // The natural order of drafts in the `scope` array is based on when they199 // were accessed. By processing drafts in reverse natural order, we have a200 // better chance of processing leaf nodes first. When a leaf node is known to201 // have changed, we can avoid any traversal of its ancestor nodes.202 for (let i = drafts.length - 1; i >= 0; i--) {203 const state = drafts[i][DRAFT_STATE]204 if (!state.modified) {360 if (Array.isArray(state.base)) {361 if (hasArrayChanges(state)) markChanged(state)362 } else if (isMap(state.base)) {363 if (hasMapChanges(state)) markChanged(state)364 } else if (isSet(state.base)) {365 if (hasSetChanges(state)) markChanged(state)366 } else if (hasObjectChanges(state)) {367 markChanged(state)205 switch (state.type) {206 case ProxyType.ES5Array:207 if (hasArrayChanges(state)) markChangedES5(state)208 break209 case ProxyType.ES5Object:210 if (hasObjectChanges(state)) markChangedES5(state)211 break212 }213 }214 }215}216373function markChangesRecursively(object) {217function markChangesRecursively(object: any) {218 if (!object || typeof object !== "object") return219 const state = object[DRAFT_STATE]220 if (!state) return377 const {base, draft, assigned} = state378 if (!Array.isArray(object)) {221 const {base, draft, assigned, type} = state222 if (type === ProxyType.ES5Object) {223 // Look for added keys.380 Object.keys(draft).forEach(key => {224 // TODO: looks quite duplicate to hasObjectChanges,225 // probably there is a faster way to detect changes, as sweep + recurse seems to do some226 // unnecessary work.227 // also: probably we can store the information we detect here, to speed up tree finalization!228 each(draft, key => {229 if ((key as any) === DRAFT_STATE) return230 // The `undefined` check is a fast path for pre-existing keys.231 if (base[key] === undefined && !has(base, key)) {232 assigned[key] = true384 markChanged(state)233 markChangedES5(state)234 } else if (!assigned[key]) {235 // Only untouched properties trigger recursion.236 markChangesRecursively(draft[key])237 }238 })239 // Look for removed keys.391 Object.keys(base).forEach(key => {240 each(base, key => {241 // The `undefined` check is a fast path for pre-existing keys.242 if (draft[key] === undefined && !has(draft, key)) {243 assigned[key] = false395 markChanged(state)244 markChangedES5(state)245 }246 })398 } else if (hasArrayChanges(state)) {399 markChanged(state)247 } else if (type === ProxyType.ES5Array && hasArrayChanges(state)) {248 markChangedES5(state)249 assigned.length = true250 if (draft.length < base.length) {251 for (let i = draft.length; i < base.length; i++) assigned[i] = false252 } else {
5 unmodified lines
258 }259 }260}261413function hasObjectChanges(state) {262function hasObjectChanges(state: ES5ObjectState) {263 const {base, draft} = state264265 // Search for added keys and changed keys. Start at the back, because266 // non-numeric keys are ordered by time of definition on the object.
20 unmodified lines
287 // Compare key count to determine if keys were deleted.288 return keys.length !== Object.keys(base).length289}290442function hasArrayChanges(state) {291function hasArrayChanges(state: ES5ArrayState) {292 const {draft} = state293 if (draft.length !== state.base.length) return true294 // See #116295 // If we first shorten the length, our array interceptors will be removed.
7 unmodified lines
303 if (descriptor && !descriptor.get) return true304 // For all other cases, we don't have to compare, as they would have been picked up by the index setters305 return false306}458459function hasMapChanges(state) {460 const {base, draft} = state461462 if (base.size !== draft.size) return true463464 // IE11 supports only forEach iteration465 let hasChanges = false466 draft.forEach(function(value, key) {467 if (!hasChanges) {468 hasChanges = isDraftable(value) ? value.modified : value !== base.get(key)469 }470 })471 return hasChanges472}473474function hasSetChanges(state) {475 const {base, draft} = state476477 if (base.size !== draft.size) return true478479 // IE11 supports only forEach iteration480 let hasChanges = false481 draft.forEach(function(value, key) {482 if (!hasChanges) {483 hasChanges = isDraftable(value) ? value.modified : !base.has(key)484 }485 })486 return hasChanges487}488489function createHiddenProperty(target, prop, value) {490 Object.defineProperty(target, prop, {491 value: value,492 enumerable: false,493 writable: true494 })495}
added:src/finalize.ts+203 added
1import {Immer} from "./immer"2import {ImmerState, Drafted, ProxyType} from "./types"3import {ImmerScope} from "./scope"4import {5 isSet,6 has,7 is,8 get,9 each,10 DRAFT_STATE,11 NOTHING,12 freeze,13 shallowCopy,14 set15} from "./common"16import {isDraft, isDraftable} from "./index"17import {SetState} from "./set"18import {generatePatches, PatchPath} from "./patches"1920export function processResult(immer: Immer, result: any, scope: ImmerScope) {21 const baseDraft = scope.drafts![0]22 const isReplaced = result !== undefined && result !== baseDraft23 immer.willFinalize(scope, result, isReplaced)24 if (isReplaced) {25 if (baseDraft[DRAFT_STATE].modified) {26 scope.revoke()27 throw new Error("An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.") // prettier-ignore28 }29 if (isDraftable(result)) {30 // Finalize the result in case it contains (or is) a subset of the draft.31 result = finalize(immer, result, scope)32 maybeFreeze(immer, result)33 }34 if (scope.patches) {35 scope.patches.push({36 op: "replace",37 path: [],38 value: result39 })40 scope.inversePatches!.push({41 op: "replace",42 path: [],43 value: baseDraft[DRAFT_STATE].base44 })45 }46 } else {47 // Finalize the base draft.48 result = finalize(immer, baseDraft, scope, [])49 }50 scope.revoke()51 if (scope.patches) {52 scope.patchListener!(scope.patches, scope.inversePatches!)53 }54 return result !== NOTHING ? result : undefined55}5657function finalize(58 immer: Immer,59 draft: Drafted,60 scope: ImmerScope,61 path?: PatchPath62) {63 const state = draft[DRAFT_STATE]64 if (!state) {65 if (Object.isFrozen(draft)) return draft66 return finalizeTree(immer, draft, scope)67 }68 // Never finalize drafts owned by another scope.69 if (state.scope !== scope) {70 return draft71 }72 if (!state.modified) {73 maybeFreeze(immer, state.base, true)74 return state.base75 }76 if (!state.finalized) {77 state.finalized = true78 finalizeTree(immer, state.draft, scope, path)7980 // We cannot really delete anything inside of a Set. We can only replace the whole Set.81 if (immer.onDelete && state.type !== ProxyType.Set) {82 // The `assigned` object is unreliable with ES5 drafts.83 if (immer.useProxies) {84 const {assigned} = state85 each(assigned, (prop, exists) => {86 if (!exists) immer.onDelete!(state, prop as any)87 })88 } else {89 const {base, copy} = state90 each(base, prop => {91 if (!has(copy, prop)) immer.onDelete!(state, prop as any)92 })93 }94 }95 if (immer.onCopy) {96 immer.onCopy(state)97 }9899 // At this point, all descendants of `state.copy` have been finalized,100 // so we can be sure that `scope.canAutoFreeze` is accurate.101 if (immer.autoFreeze && scope.canAutoFreeze) {102 freeze(state.copy, false)103 }104105 if (path && scope.patches) {106 generatePatches(state, path, scope.patches, scope.inversePatches!)107 }108 }109 return state.copy110}111112function finalizeTree(113 immer: Immer,114 root: Drafted,115 scope: ImmerScope,116 rootPath?: PatchPath117) {118 const state = root[DRAFT_STATE]119 if (state) {120 if (121 state.type === ProxyType.ES5Object ||122 state.type === ProxyType.ES5Array123 ) {124 // Create the final copy, with added keys and without deleted keys.125 state.copy = shallowCopy(state.draft, true)126 }127 root = state.copy128 }129 each(root, (key, value) =>130 finalizeProperty(immer, scope, root, state, root, key, value, rootPath)131 )132 return root133}134135function finalizeProperty(136 immer: Immer,137 scope: ImmerScope,138 root: Drafted,139 rootState: ImmerState,140 parentValue: Drafted,141 prop: string | number,142 childValue: any,143 rootPath?: PatchPath144) {145 if (childValue === parentValue) {146 throw Error("Immer forbids circular references")147 }148149 // In the `finalizeTree` method, only the `root` object may be a draft.150 const isDraftProp = !!rootState && parentValue === root151 const isSetMember = isSet(parentValue)152153 if (isDraft(childValue)) {154 const path =155 rootPath &&156 isDraftProp &&157 !isSetMember && // Set objects are atomic since they have no keys.158 !has((rootState as Exclude<ImmerState, SetState>).assigned!, prop) // Skip deep patches for assigned keys.159 ? rootPath!.concat(prop)160 : undefined161162 // Drafts owned by `scope` are finalized here.163 childValue = finalize(immer, childValue, scope, path)164 set(parentValue, prop, childValue)165166 // Drafts from another scope must prevent auto-freezing.167 if (isDraft(childValue)) {168 scope.canAutoFreeze = false169 }170 }171 // Unchanged draft properties are ignored.172 else if (isDraftProp && is(childValue, get(rootState.base, prop))) {173 return174 }175 // Search new objects for unfinalized drafts. Frozen objects should never contain drafts.176 // TODO: the recursion over here looks weird, shouldn't non-draft stuff have it's own recursion?177 // especially the passing on of root and rootState doesn't make sense...178 else if (isDraftable(childValue) && !Object.isFrozen(childValue)) {179 each(childValue, (key, grandChild) =>180 finalizeProperty(181 immer,182 scope,183 root,184 rootState,185 childValue,186 key,187 grandChild,188 rootPath189 )190 )191 maybeFreeze(immer, childValue)192 }193194 if (isDraftProp && immer.onAssign && !isSetMember) {195 immer.onAssign(rootState, prop, childValue)196 }197}198199export function maybeFreeze(immer: Immer, value: any, deep = false) {200 if (immer.autoFreeze && !isDraft(value)) {201 freeze(value, deep)202 }203}
modified:src/immer.ts+82 added-223 removed
1import * as legacyProxy from "./es5"2import * as modernProxy from "./proxy"3import {applyPatches, generatePatches} from "./patches"1import {createES5Proxy, willFinalizeES5, markChangedES5} from "./es5"2import {createProxy, markChanged} from "./proxy"34import {applyPatches} from "./patches"5import {5 assign,6 each,7 has,8 is,7 isDraft,8 isSet,11 get,9 isMap,10 isDraftable,14 isEnumerable,15 shallowCopy,11 DRAFT_STATE,12 NOTHING,18 freeze13 die14} from "./common"15import {ImmerScope} from "./scope"21import {ImmerState, IProduce, IProduceWithPatches, Objectish, PatchListener, Draft, Patch} from "./types"16import {17 ImmerState,18 IProduce,19 IProduceWithPatches,20 Objectish,21 PatchListener,22 Draft,23 Patch,24 Drafted25} from "./types"26import {proxyMap} from "./map"27import {proxySet} from "./set"28import {processResult, maybeFreeze} from "./finalize"2930/* istanbul ignore next */31function verifyMinified() {}3233const configDefaults = {34 useProxies:
2 unmodified lines
37 typeof Reflect !== "undefined",38 autoFreeze:39 typeof process !== "undefined"40 ? process.env.NODE_ENV !== "production"41 : /* istanbul ignore next */33 : verifyMinified.name === "verifyMinified",42 verifyMinified.name === "verifyMinified",43 onAssign: null,44 onDelete: null,45 onCopy: null37}46} as const4748interface ProducersFns {49 produce: IProduce50 produceWithPatches: IProduceWithPatches
1 unmodified line
5253export class Immer implements ProducersFns {54 useProxies: boolean = false55 autoFreeze: boolean = false47 onAssign?: (48 state: ImmerState,49 prop: string | number,50 value: unknown51 ) => void56 onAssign?: (state: ImmerState, prop: string | number, value: unknown) => void57 onDelete?: (state: ImmerState, prop: string | number) => void58 onCopy?: (state: ImmerState) => void54 createProxy!:<T>(value: T) => T;55 willFinalize!: (scope: ImmerScope, thing: any, isReplaced: boolean) => void;5960 constructor(config?: {61 useProxies?: boolean62 autoFreeze?: boolean
4 unmodified lines
67 ) => void68 onDelete?: (state: ImmerState, prop: string | number) => void69 onCopy?: (state: ImmerState) => void70 }) {68 assign(this, configDefaults, config)71 each(configDefaults, (key, value) => {72 // @ts-ignore73 this[key] = config?.[key] ?? value74 })75 this.setUseProxies(this.useProxies)76 this.produce = this.produce.bind(this)77 this.produceWithPatches = this.produceWithPatches.bind(this)78 }
16 unmodified lines
95 * @param {Function} producer - function that receives a proxy of the base state as first argument and which can be freely modified96 * @param {Function} patchListener - optional function that will be called with all the patches produced here97 * @returns {any} a new state, or the initial state if nothing was modified98 */93 produce(base, recipe?, patchListener?) {99 produce(base: any, recipe?: any, patchListener?: any) {100 // curried invocation101 if (typeof base === "function" && typeof recipe !== "function") {102 const defaultBase = recipe103 recipe = base104105 const self = this100 return function curriedProduce(this: any, base = defaultBase, ...args) {101 return self.produce(base, draft => recipe.call(this, draft, ...args)) // prettier-ignore106 return function curriedProduce(107 this: any,108 base = defaultBase,109 ...args: any[]110 ) {111 return self.produce(base, (draft: Drafted) => recipe.call(this, draft, ...args)) // prettier-ignore112 }113 }114115 // prettier-ignore
9 unmodified lines
125 let result126127 // Only plain objects, arrays, and "immerable classes" are drafted.128 if (isDraftable(base)) {119 const scope = ImmerScope.enter()120 const proxy = this.createProxy(base)129 const scope = ImmerScope.enter(this)130 const proxy = this.createProxy(base, undefined)131 let hasError = true132 try {133 result = recipe(proxy)134 hasError = false
5 unmodified lines
140 if (typeof Promise !== "undefined" && result instanceof Promise) {141 return result.then(142 result => {143 scope.usePatches(patchListener)134 return this.processResult(result, scope)144 return processResult(this, result, scope)145 },146 error => {147 scope.revoke()148 throw error149 }150 )151 }152 scope.usePatches(patchListener)143 return this.processResult(result, scope)153 return processResult(this, result, scope)154 } else {155 result = recipe(base)156 if (result === NOTHING) return undefined157 if (result === undefined) result = base148 this.maybeFreeze(result, true)158 maybeFreeze(this, result, true)159 return result160 }161 }162153 produceWithPatches(arg1, arg2?, arg3?): any {163 produceWithPatches(arg1: any, arg2?: any, arg3?: any): any {164 if (typeof arg1 === "function") {155 const self = this156 return (state, ...args) =>157 this.produceWithPatches(state, draft => arg1(draft, ...args))165 return (state: any, ...args: any[]) =>166 this.produceWithPatches(state, (draft: any) => arg1(draft, ...args))167 }168 // non-curried form160 if (arg3)161 throw new Error("A patch listener cannot be passed to produceWithPatches")162 let patches, inversePatches163 const nextState = this.produce(arg1, arg2, (p, ip) => {169 /* istanbul ignore next */170 if (arg3) die()171 let patches: Patch[], inversePatches: Patch[]172 const nextState = this.produce(arg1, arg2, (p: Patch[], ip: Patch[]) => {173 patches = p174 inversePatches = ip175 })167 return [nextState, patches, inversePatches]176 return [nextState, patches!, inversePatches!]177 }178170 createDraft<T extends Objectish>(base: T): Draft<T> {179 createDraft<T extends Objectish>(base: T): Drafted<T> {180 if (!isDraftable(base)) {181 throw new Error("First argument to `createDraft` must be a plain object, an array, or an immerable object") // prettier-ignore182 }174 const scope = ImmerScope.enter()175 const proxy = this.createProxy(base)183 const scope = ImmerScope.enter(this)184 const proxy = this.createProxy(base, undefined)185 proxy[DRAFT_STATE].isManual = true186 scope.leave()178 return proxy as any187 return proxy188 }189181 finishDraft<D extends Draft<any>>(draft: D, patchListener: PatchListener): D extends Draft<infer T> ? T : never {182 const state = draft && draft[DRAFT_STATE]190 finishDraft<D extends Draft<any>>(191 draft: D,192 patchListener?: PatchListener193 ): D extends Draft<infer T> ? T : never {194 const state: ImmerState = draft && draft[DRAFT_STATE]195 if (!state || !state.isManual) {196 throw new Error("First argument to `finishDraft` must be a draft returned by `createDraft`") // prettier-ignore197 }198 if (state.finalized) {199 throw new Error("The given draft is already finalized") // prettier-ignore200 }201 const {scope} = state202 scope.usePatches(patchListener)191 return this.processResult(undefined, scope)203 return processResult(this, undefined, scope)204 }205206 /**207 * Pass true to automatically freeze all copies created by Immer.
11 unmodified lines
219 * By default, feature detection is used, so calling this is rarely necessary.220 */221 setUseProxies(value: boolean) {222 this.useProxies = value211 assign(this, value ? modernProxy : legacyProxy)223 }224225 applyPatches(base: Objectish, patches: Patch[]) {226 // If a patch replaces the entire state, take that replacement as base227 // before applying patches217 let i228 let i: number229 for (i = patches.length - 1; i >= 0; i--) {230 const patch = patches[i]231 if (patch.path.length === 0 && patch.op === "replace") {232 base = patch.value
5 unmodified lines
238 // N.B: never hits if some patch a replacement, patches are never drafts239 return applyPatches(base, patches)240 }241 // Otherwise, produce a copy of the base state.231 return this.produce(base, draft =>242 return this.produce(base, (draft: Drafted) =>243 applyPatches(draft, patches.slice(i + 1))244 )245 }246236 /** @internal */237 processResult(result: any, scope: ImmerScope) {238 const baseDraft = scope.drafts![0]239 const isReplaced = result !== undefined && result !== baseDraft240 this.willFinalize(scope, result, isReplaced)241 if (isReplaced) {242 if (baseDraft[DRAFT_STATE].modified) {243 scope.revoke()244 throw new Error("An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.") // prettier-ignore245 }246 if (isDraftable(result)) {247 // Finalize the result in case it contains (or is) a subset of the draft.248 result = this.finalize(result, null, scope)249 this.maybeFreeze(result)250 }251 if (scope.patches) {252 scope.patches.push({253 op: "replace",254 path: [],255 value: result256 })257 scope.inversePatches!.push({258 op: "replace",259 path: [],260 value: baseDraft[DRAFT_STATE].base261 })262 }263 } else {264 // Finalize the base draft.265 result = this.finalize(baseDraft, [], scope)266 }267 scope.revoke()268 if (scope.patches) {269 scope.patchListener!(scope.patches, scope.inversePatches!)270 }271 return result !== NOTHING ? result : undefined247 createProxy<T extends Objectish>(248 value: T,249 parent?: ImmerState250 ): Drafted<T, ImmerState> {251 // precondition: createProxy should be guarded by isDraftable, so we know we can safely draft252 const draft: Drafted = isMap(value)253 ? proxyMap(value, parent)254 : isSet(value)255 ? proxySet(value, parent)256 : this.useProxies257 ? createProxy(value, parent)258 : createES5Proxy(value, parent)259260 const scope = parent ? parent.scope : ImmerScope.current!261 scope.drafts.push(draft)262 return draft263 }264274 /**275 * @internal276 * Finalize a draft, returning either the unmodified base state or a modified277 * copy of the base state.278 */279 finalize(draft: any, path: string[] | null, scope: ImmerScope) {280 const state = draft[DRAFT_STATE]281 if (!state) {282 if (Object.isFrozen(draft)) return draft283 return this.finalizeTree(draft, null, scope)284 }285 // Never finalize drafts owned by another scope.286 if (state.scope !== scope) {287 return draft288 }289 if (!state.modified) {290 this.maybeFreeze(state.base, true)291 return state.base292 }293 if (!state.finalized) {294 state.finalized = true295 this.finalizeTree(state.draft, path, scope)296297 // We cannot really delete anything inside of a Set. We can only replace the whole Set.298 if (this.onDelete && !isSet(state.base)) {299 // The `assigned` object is unreliable with ES5 drafts.300 if (this.useProxies) {301 const {assigned} = state302 each(assigned, (prop, exists) => {303 if (!exists) this.onDelete?.(state, prop as any)304 })305 } else {306 // TODO: Figure it out for Maps and Sets if we need to support ES5307 const {base, copy} = state308 each(base, prop => {309 if (!has(copy, prop)) this.onDelete?.(state, prop as any)310 })311 }312 }313 if (this.onCopy) {314 this.onCopy(state)315 }316317 // At this point, all descendants of `state.copy` have been finalized,318 // so we can be sure that `scope.canAutoFreeze` is accurate.319 if (this.autoFreeze && scope.canAutoFreeze) {320 freeze(state.copy, false)321 }322323 if (path && scope.patches) {324 generatePatches(state, path, scope.patches, scope.inversePatches!)325 }326 }327 return state.copy265 willFinalize(scope: ImmerScope, thing: any, isReplaced: boolean) {266 if (!this.useProxies) willFinalizeES5(scope, thing, isReplaced)267 }268330 /**331 * @internal332 * Finalize all drafts in the given state tree.333 */334 finalizeTree(root: any, rootPath: string[] | null, scope: ImmerScope) {335 const state = root[DRAFT_STATE]336 if (state) {337 if (!this.useProxies) {338 // Create the final copy, with added keys and without deleted keys.339 state.copy = shallowCopy(state.draft, true)340 }341 root = state.copy269 markChanged(state: ImmerState) {270 if (this.useProxies) {271 markChanged(state)272 } else {273 markChangedES5(state)274 }343344 const needPatches = !!rootPath && !!scope.patches345 const finalizeProperty = (prop, value, parent) => {346 if (value === parent) {347 throw Error("Immer forbids circular references")348 }349350 // In the `finalizeTree` method, only the `root` object may be a draft.351 const isDraftProp = !!state && parent === root352 const isSetMember = isSet(parent)353354 if (isDraft(value)) {355 const path =356 isDraftProp &&357 needPatches &&358 !isSetMember && // Set objects are atomic since they have no keys.359 !has(state.assigned, prop) // Skip deep patches for assigned keys.360 ? rootPath!.concat(prop)361 : null362363 // Drafts owned by `scope` are finalized here.364 value = this.finalize(value, path, scope)365 replace(parent, prop, value)366367 // Drafts from another scope must prevent auto-freezing.368 if (isDraft(value)) {369 scope.canAutoFreeze = false370 }371372 // Unchanged drafts are never passed to the `onAssign` hook.373 if (isDraftProp && value === get(state.base, prop)) return374 }375 // Unchanged draft properties are ignored.376 else if (isDraftProp && is(value, get(state.base, prop))) {377 return378 }379 // Search new objects for unfinalized drafts. Frozen objects should never contain drafts.380 else if (isDraftable(value) && !Object.isFrozen(value)) {381 each(value, finalizeProperty)382 this.maybeFreeze(value)383 }384385 if (isDraftProp && this.onAssign && !isSetMember) {386 this.onAssign(state, prop, value)387 }388 }389390 each(root, finalizeProperty)391 return root275 }393 maybeFreeze(value, deep = false) {394 if (this.autoFreeze && !isDraft(value)) {395 freeze(value, deep)396 }397 }276}399400function replace(parent, prop, value) {401 if (isMap(parent)) {402 parent.set(prop, value)403 } else if (isSet(parent)) {404 // In this case, the `prop` is actually a draft.405 parent.delete(prop)406 parent.add(value)407 } else if (Array.isArray(parent) || isEnumerable(parent, prop)) {408 // Preserve non-enumerable properties.409 parent[prop] = value410 } else {411 Object.defineProperty(parent, prop, {412 value,413 writable: true,414 configurable: true415 })416 }417}
added:src/map.ts+163 added
1import {isDraftable, DRAFT_STATE, latest, iteratorSymbol} from "./common"23import {ImmerScope} from "./scope"4import {AnyMap, Drafted, ImmerState, ImmerBaseState, ProxyType} from "./types"5import {assertUnrevoked} from "./es5"67export interface MapState extends ImmerBaseState {8 type: ProxyType.Map9 copy: AnyMap | undefined10 assigned: Map<any, boolean> | undefined11 base: AnyMap12 revoked: boolean13 draft: Drafted<AnyMap, MapState>14}1516// Make sure DraftMap declarion doesn't die if Map is not avialable...17/* istanbul ignore next */18const MapBase: MapConstructor =19 typeof Map !== "undefined" ? Map : (function FakeMap() {} as any)2021export class DraftMap<K, V> extends MapBase implements Map<K, V> {22 [DRAFT_STATE]: MapState23 constructor(target: AnyMap, parent?: ImmerState) {24 super()25 this[DRAFT_STATE] = {26 type: ProxyType.Map,27 parent,28 scope: parent ? parent.scope : ImmerScope.current!,29 modified: false,30 finalized: false,31 copy: undefined,32 assigned: undefined,33 base: target,34 draft: this,35 isManual: false,36 revoked: false37 }38 }3940 get size(): number {41 return latest(this[DRAFT_STATE]).size42 }4344 has(key: K): boolean {45 return latest(this[DRAFT_STATE]).has(key)46 }4748 set(key: K, value: V): this {49 const state = this[DRAFT_STATE]50 assertUnrevoked(state)51 if (latest(state).get(key) !== value) {52 prepareCopy(state)53 state.scope.immer.markChanged(state)54 state.assigned!.set(key, true)55 state.copy!.set(key, value)56 state.assigned!.set(key, true)57 }58 return this59 }6061 delete(key: K): boolean {62 if (!this.has(key)) {63 return false64 }6566 const state = this[DRAFT_STATE]67 assertUnrevoked(state)68 prepareCopy(state)69 state.scope.immer.markChanged(state)70 state.assigned!.set(key, false)71 state.copy!.delete(key)72 return true73 }7475 clear() {76 const state = this[DRAFT_STATE]77 assertUnrevoked(state)78 prepareCopy(state)79 state.scope.immer.markChanged(state)80 state.assigned = new Map()81 for (const key of latest(state).keys()) {82 state.assigned.set(key, false)83 }84 return state.copy!.clear()85 }8687 forEach(cb: (value: V, key: K, self: this) => void, thisArg?: any) {88 const state = this[DRAFT_STATE]89 latest(state).forEach((_value: V, key: K, _map: this) => {90 cb.call(thisArg, this.get(key), key, this)91 })92 }9394 get(key: K): V {95 const state = this[DRAFT_STATE]96 assertUnrevoked(state)97 const value = latest(state).get(key)98 if (state.finalized || !isDraftable(value)) {99 return value100 }101 if (value !== state.base.get(key)) {102 return value // either already drafted or reassigned103 }104 // despite what it looks, this creates a draft only once, see above condition105 const draft = state.scope.immer.createProxy(value, state)106 prepareCopy(state)107 state.copy!.set(key, draft)108 return draft109 }110111 keys(): IterableIterator<K> {112 return latest(this[DRAFT_STATE]).keys()113 }114115 values(): IterableIterator<V> {116 const iterator = this.keys()117 return {118 [iteratorSymbol]: () => this.values(),119 next: () => {120 const r = iterator.next()121 /* istanbul ignore next */122 if (r.done) return r123 const value = this.get(r.value)124 return {125 done: false,126 value127 }128 }129 } as any130 }131132 entries(): IterableIterator<[K, V]> {133 const iterator = this.keys()134 return {135 [iteratorSymbol]: () => this.entries(),136 next: () => {137 const r = iterator.next()138 /* istanbul ignore next */139 if (r.done) return r140 const value = this.get(r.value)141 return {142 done: false,143 value: [r.value, value]144 }145 }146 } as any147 }148149 [iteratorSymbol]() {150 return this.entries()151 }152}153154export function proxyMap(target: AnyMap, parent?: ImmerState) {155 return new DraftMap(target, parent)156}157158function prepareCopy(state: MapState) {159 if (!state.copy) {160 state.assigned = new Map()161 state.copy = new Map(state.base)162 }163}
modified:src/patches.ts+98 added-55 removed
1import {get, each, isMap, isSet, has, clone} from "./common"2import {Patch, ImmerState} from "./types"1import {get, each, isMap, has, die, getArchtype} from "./common"2import {Patch, ImmerState, ProxyType, Archtype} from "./types"3import {SetState} from "./set"4import {ES5ArrayState, ES5ObjectState} from "./es5"5import {ProxyArrayState, ProxyObjectState} from "./proxy"6import {MapState} from "./map"78export type PatchPath = (string | number)[]910export function generatePatches(11 state: ImmerState,6 basePath: (string | number)[],12 basePath: PatchPath,13 patches: Patch[],14 inversePatches: Patch[]9) {10 const generatePatchesFn = Array.isArray(state.base)11 ? generateArrayPatches12 : isSet(state.base)13 ? generateSetPatches14 : generatePatchesFromAssigned1516 generatePatchesFn(state, basePath, patches, inversePatches)15): void {16 switch (state.type) {17 case ProxyType.ProxyObject:18 case ProxyType.ES5Object:19 case ProxyType.Map:20 return generatePatchesFromAssigned(21 state,22 basePath,23 patches,24 inversePatches25 )26 case ProxyType.ES5Array:27 case ProxyType.ProxyArray:28 return generateArrayPatches(state, basePath, patches, inversePatches)29 case ProxyType.Set:30 return generateSetPatches(31 (state as any) as SetState,32 basePath,33 patches,34 inversePatches35 )36 }37}3839function generateArrayPatches(20 state: ImmerState,21 basePath: (string | number)[],40 state: ES5ArrayState | ProxyArrayState,41 basePath: PatchPath,42 patches: Patch[],43 inversePatches: Patch[]44) {25 let {base, copy, assigned} = state45 let {base, assigned, copy} = state46 /* istanbul ignore next */47 if (!copy) die()4849 // Reduce complexity by ensuring `base` is never longer.50 if (copy.length < base.length) {51 // @ts-ignore52 ;[base, copy] = [copy, base]53 ;[patches, inversePatches] = [inversePatches, patches]54 }55
46 unmodified lines
102}103104// This is used for both Map objects and normal objects.105function generatePatchesFromAssigned(83 state: ImmerState,84 basePath: (number | string)[],106 state: MapState | ES5ObjectState | ProxyObjectState,107 basePath: PatchPath,108 patches: Patch[],109 inversePatches: Patch[]110) {111 const {base, copy} = state89 each(state.assigned, (key, assignedValue) => {112 each(state.assigned!, (key, assignedValue) => {113 const origValue = get(base, key)91 const value = get(copy, key)114 const value = get(copy!, key)115 const op = !assignedValue ? "remove" : has(base, key) ? "replace" : "add"116 if (origValue === value && op === "replace") return117 const path = basePath.concat(key as any)118 patches.push(op === "remove" ? {op, path} : {op, path, value})
7 unmodified lines
126 })127}128129function generateSetPatches(107 state: ImmerState,108 basePath: (number | string)[],130 state: SetState,131 basePath: PatchPath,132 patches: Patch[],133 inversePatches: Patch[]134) {135 let {base, copy} = state136137 let i = 0138 base.forEach(value => {116 if (!copy.has(value)) {139 if (!copy!.has(value)) {140 const path = basePath.concat([i])141 patches.push({142 op: "remove",143 path,
7 unmodified lines
151 }152 i++153 })154 i = 0132 copy.forEach(value => {155 copy!.forEach(value => {156 if (!base.has(value)) {157 const path = basePath.concat([i])158 patches.push({159 op: "add",
13 unmodified lines
173export function applyPatches<T>(draft: T, patches: Patch[]): T {174 patches.forEach(patch => {175 const {path, op} = patch176154 if (!path.length) throw new Error("Illegal state")177 /* istanbul ignore next */178 if (!path.length) die()179156 let base = draft180 let base: any = draft181 for (let i = 0; i < path.length - 1; i++) {182 base = get(base, path[i])183 if (!base || typeof base !== "object")184 throw new Error("Cannot apply patch, path doesn't resolve: " + path.join("/")) // prettier-ignore185 }186163 const value = clone(patch.value) // used to clone patch to ensure original patch is not modified, see #411164187 const type = getArchtype(base)188 const value = deepClonePatchValue(patch.value) // used to clone patch to ensure original patch is not modified, see #411189 const key = path[path.length - 1]190 switch (op) {191 case "replace":168 if (isMap(base)) {169 base.set(key, value)170 } else if (isSet(base)) {171 throw new Error('Sets cannot have "replace" patches.')172 } else {173 // if value is an object, then it's assigned by reference174 // in the following add or remove ops, the value field inside the patch will also be modifyed175 // so we use value from the cloned patch176 base[key] = value192 switch (type) {193 case Archtype.Map:194 return base.set(key, value)195 /* istanbul ignore next */196 case Archtype.Set:197 throw new Error('Sets cannot have "replace" patches.')198 default:199 // if value is an object, then it's assigned by reference200 // in the following add or remove ops, the value field inside the patch will also be modifyed201 // so we use value from the cloned patch202 // @ts-ignore203 return (base[key] = value)204 }178 break205 case "add":180 if (isSet(base)) {181 base.delete(patch.value)206 switch (type) {207 case Archtype.Array:208 return base.splice(key as any, 0, value)209 case Archtype.Map:210 return base.set(key, value)211 case Archtype.Set:212 return base.add(value)213 default:214 return (base[key] = value)215 }183184 Array.isArray(base)185 ? base.splice(key as any, 0, value)186 : isMap(base)187 ? base.set(key, value)188 : isSet(base)189 ? base.add(value)190 : (base[key] = value)191 break216 case "remove":193 Array.isArray(base)194 ? base.splice(key as any, 1)195 : isMap(base)196 ? base.delete(key)197 : isSet(base)198 ? base.delete(patch.value)199 : delete base[key]200 break217 switch (type) {218 case Archtype.Array:219 return base.splice(key as any, 1)220 case Archtype.Map:221 return base.delete(key)222 case Archtype.Set:223 return base.delete(patch.value)224 default:225 return delete base[key]226 }227 default:228 throw new Error("Unsupported patch operation: " + op)229 }230 })231232 return draft233}234235// TODO: optimize: this is quite a performance hit, can we detect intelligently when it is needed?236// E.g. auto-draft when new objects from outside are assigned and modified?237// (See failing test when deepClone just returns obj)238function deepClonePatchValue<T>(obj: T): T239function deepClonePatchValue(obj: any) {240 if (!obj || typeof obj !== "object") return obj241 if (Array.isArray(obj)) return obj.map(deepClonePatchValue)242 if (isMap(obj))243 return new Map(244 Array.from(obj.entries()).map(([k, v]) => [k, deepClonePatchValue(v)])245 )246 // Not needed: if (isSet(obj)) return new Set(Array.from(obj.values()).map(deepClone))247 const cloned = Object.create(Object.getPrototypeOf(obj))248 for (const key in obj) cloned[key] = deepClonePatchValue(obj[key])249 return cloned250}
modified:src/proxy.ts+81 added-252 removed
1"use strict"2import {3 assign,3 each,4 has,5 is,6 isDraftable,8 isDraft,9 isMap,10 isSet,11 hasSymbol,7 shallowCopy,13 makeIterable,8 DRAFT_STATE,15 assignMap,16 assignSet,17 original,18 iterateMapValues,19 makeIterateSetValues9 latest10} from "./common"11import {ImmerScope} from "./scope"12import {13 AnyObject,14 Drafted,15 ImmerState,16 AnyArray,17 Objectish,18 ImmerBaseState,19 ProxyType20} from "./types"2123// Do nothing before being finalized.24export function willFinalize() {}22interface ProxyBaseState extends ImmerBaseState {23 assigned: {24 [property: string]: boolean25 }26 parent?: ImmerState27 drafts?: {28 [property: string]: Drafted<any, any>29 }30 revoke(): void31}3226interface ES6Draft {}33export interface ProxyObjectState extends ProxyBaseState {34 type: ProxyType.ProxyObject35 base: AnyObject36 copy: AnyObject | null37 draft: Drafted<AnyObject, ProxyObjectState>38}3928interface ES6State<T = any> {29 scope: ImmerScope30 modified: boolean31 finalized: boolean32 assigned:33 | {34 [property: string]: boolean35 }36 | Map<string, boolean> // TODO: always use a Map?37 parent: ES6State38 base: T39 draft: ES6Draft | null40 drafts:41 | {42 [property: string]: ES6Draft43 }44 | Map<string, ES6Draft> // TODO: always use a Map?45 copy: T | null46 revoke: null | (() => void)40export interface ProxyArrayState extends ProxyBaseState {41 type: ProxyType.ProxyArray42 base: AnyArray43 copy: AnyArray | null44 draft: Drafted<AnyArray, ProxyArrayState>45}4647type ProxyState = ProxyObjectState | ProxyArrayState4849/**50 * Returns a new draft of the `base` object.51 *52 * The second argument is the parent draft-state (used internally).53 */54export function createProxy<T extends object>(54export function createProxy<T extends Objectish>(55 base: T,56 parent: ES6State57): ES6Draft {58 const scope = parent ? parent.scope : ImmerScope.current!59 const state: ES6State<T> = {56 parent?: ImmerState57): Drafted<T, ProxyState> {58 const isArray = Array.isArray(base)59 const state: ProxyState = {60 type: isArray ? ProxyType.ProxyArray : (ProxyType.ProxyObject as any),61 // Track which produce call this is associated with.61 scope,62 scope: parent ? parent.scope : ImmerScope.current!,63 // True for both shallow and deep changes.64 modified: false,65 // Used during finalization.66 finalized: false,
3 unmodified lines
70 parent,71 // The base state.72 base,73 // The base proxy.73 draft: null,74 draft: null as any, // set below75 // Any property proxies.76 drafts: {},77 // The base copy with any updated values.78 copy: null,79 // Called by the `produce` function.79 revoke: null80 revoke: null as any,81 isManual: false82 }8384 // the traps must target something, a bit like the 'real' base.85 // but also, we need to be able to determine from the target what the relevant state is
2 unmodified lines
88 // So the trick is to use 'state' as the actual 'target'! (and make sure we intercept everything)89 // Note that in the case of an array, we put the state in an array to have better Reflect defaults ootb90 let target: T = state as any91 let traps: ProxyHandler<object | Array<any>> = objectTraps90 if (Array.isArray(base)) {92 if (isArray) {93 target = [state] as any94 traps = arrayTraps95 }94 // Map drafts must support object keys, so we use Map objects to track changes.95 else if (isMap(base)) {96 traps = mapTraps97 state.drafts = new Map()98 state.assigned = new Map()99 }100 // Set drafts use a Map object to track which of its values are drafted.101 // And we don't need the "assigned" property, because Set objects have no keys.102 else if (isSet(base)) {103 traps = setTraps104 state.drafts = new Map()105 }9697 // TODO: optimization: might be faster, cheaper if we created a non-revocable proxy98 // and administrate revoking ourselves99 const {revoke, proxy} = Proxy.revocable(target, traps)108109 state.draft = proxy100 state.draft = proxy as any101 state.revoke = revoke111112 scope.drafts!.push(proxy)113 return proxy102 return proxy as any103}104105/**106 * Object drafts107 */119const objectTraps: ProxyHandler<ES6State> = {108const objectTraps: ProxyHandler<ProxyState> = {109 get(state, prop) {110 if (prop === DRAFT_STATE) return state111 let {drafts} = state112113 // Check for existing draft in unmodified state.114 if (!state.modified && has(drafts, prop)) {126 return drafts[prop]115 return drafts![prop as any]116 }117118 const value = latest(state)[prop]119 if (state.finalized || !isDraftable(value)) {
4 unmodified lines
124 if (state.modified) {125 // Assigned values are never drafted. This catches any drafts we created, too.126 if (value !== peek(state.base, prop)) return value127 // Store drafts on the copy (when one exists).128 // @ts-ignore129 drafts = state.copy130 }131142 return (drafts[prop] = createProxy(value, state))132 return (drafts![prop as any] = state.scope.immer.createProxy(value, state))133 },134 has(state, prop) {135 return prop in latest(state)136 },137 ownKeys(state) {138 return Reflect.ownKeys(latest(state))139 },150 set(state, prop, value) {140 set(state, prop: string /* strictly not, but helps TS */, value) {141 if (!state.modified) {142 const baseValue = peek(state.base, prop)143 // Optimize based on value's truthiness. Truthy values are guaranteed to144 // never be undefined, so we can avoid the `in` operator. Lastly, truthy145 // values may be drafts, but falsy values are never drafts.146 const isUnchanged = value157 ? is(baseValue, value) || value === state.drafts[prop]147 ? is(baseValue, value) || value === state.drafts![prop]148 : is(baseValue, value) && prop in state.base149 if (isUnchanged) return true150 prepareCopy(state)151 markChanged(state)152 }153 state.assigned[prop] = true154 // @ts-ignore163 state.copy[prop] = value155 state.copy![prop] = value156 return true157 },166 deleteProperty(state, prop) {158 deleteProperty(state, prop: string) {159 // The `undefined` check is a fast path for pre-existing keys.160 if (peek(state.base, prop) !== undefined || prop in state.base) {161 state.assigned[prop] = false162 prepareCopy(state)163 markChanged(state)164 } else if (state.assigned[prop]) {165 // if an originally not assigned property was deleted166 delete state.assigned[prop]167 }168 // @ts-ignore169 if (state.copy) delete state.copy[prop]170 return true171 },172 // Note: We never coerce `desc.value` into an Immer draft, because we can't make
2 unmodified lines
175 const owner = latest(state)176 const desc = Reflect.getOwnPropertyDescriptor(owner, prop)177 if (desc) {178 desc.writable = true185 desc.configurable = !Array.isArray(owner) || prop !== "length"179 desc.configurable =180 state.type !== ProxyType.ProxyArray || prop !== "length"181 }182 return desc183 },184 defineProperty() {
10 unmodified lines
195/**196 * Array drafts197 */198204const arrayTraps: ProxyHandler<[ES6State]> = {}199const arrayTraps: ProxyHandler<[ProxyArrayState]> = {}200each(objectTraps, (key, fn) => {201 // @ts-ignore202 arrayTraps[key] = function() {203 arguments[0] = arguments[0][0]204 return fn.apply(this, arguments)205 }
10 unmodified lines
216 }217 return objectTraps.set!.call(this, state[0], prop, value, state[0])218}219224// Used by Map and Set drafts225const reflectTraps = makeReflectTraps([226 "ownKeys",227 "has",228 "set",229 "deleteProperty",230 "defineProperty",231 "getOwnPropertyDescriptor",232 "preventExtensions",233 "isExtensible",234 "getPrototypeOf"235])236220/**221 * Map drafts222 */223241const mapTraps = makeTrapsForGetters<Map<any, any>>({242 [DRAFT_STATE]: state => state,243 size: state => latest(state).size,244 has: state => key => latest(state).has(key),245 set: state => (key, value) => {246 const values = latest(state)247 if (!values.has(key) || values.get(key) !== value) {248 markChanged(state)249 // @ts-ignore250 state.assigned.set(key, true)251 state.copy!.set(key, value)252 }253 return state.draft254 },255 delete: state => key => {256 if (latest(state).has(key)) {257 markChanged(state)258 // @ts-ignore259 state.assigned.set(key, false)260 return state.copy!.delete(key)261 }262 return false263 },264 clear: state => () => {265 markChanged(state)266 state.assigned = new Map()267 each(latest(state).keys(), (_, key) => {268 // @ts-ignore269 state.assigned.set(key, false)270 })271 return state.copy!.clear()272 },273 // @ts-ignore274 forEach: (state, _, receiver) => (cb, thisArg) =>275 latest(state).forEach((_, key, map) => {276 const value = receiver.get(key)277 cb.call(thisArg, value, key, map)278 }),279 get: state => key => {280 const drafts = state.modified ? state.copy : state.drafts281282 // @ts-ignore TODO: ...or fix by using different ES6Draft types (but better just unify to maps)283 if (drafts!.has(key)) {284 // @ts-ignore285 const value = drafts.get(key)286287 if (isDraft(value) || !isDraftable(value)) return value288289 const draft = createProxy(value, state)290 // @ts-ignore291 drafts.set(key, draft)292 return draft293 }294295 const value = latest(state).get(key)296 if (state.finalized || !isDraftable(value)) {297 return value298 }299300 const draft = createProxy(value, state)301 //@ts-ignore302 drafts.set(key, draft)303 return draft304 },305 keys: state => () => latest(state).keys(),306 //@ts-ignore307 values: iterateMapValues,308 //@ts-ignore309 entries: iterateMapValues,310 [hasSymbol ? Symbol.iterator : "@@iterator"]: iterateMapValues311})312313const iterateSetValues = makeIterateSetValues(createProxy)314/**315 * Set drafts316 */317318const setTraps = makeTrapsForGetters<Set<any>>({319 //@ts-ignore320 [DRAFT_STATE]: state => state,321 size: state => latest(state).size,322 has: state => key => latest(state).has(key),323 add: state => value => {324 if (!latest(state).has(value)) {325 markChanged(state)326 //@ts-ignore327 state.copy.add(value)328 }329 return state.draft330 },331 delete: state => value => {332 markChanged(state)333 //@ts-ignore334 return state.copy.delete(value)335 },336 clear: state => () => {337 markChanged(state)338 //@ts-ignore339 return state.copy.clear()340 },341 forEach: state => (cb, thisArg) => {342 const iterator = iterateSetValues(state)()343 let result = iterator.next()344 while (!result.done) {345 cb.call(thisArg, result.value, result.value, state.draft)346 result = iterator.next()347 }348 },349 keys: iterateSetValues,350 values: iterateSetValues,351 entries: iterateSetValues,352 [hasSymbol ? Symbol.iterator : "@@iterator"]: iterateSetValues353})354355/**356 * Helpers357 */358359// Retrieve the latest values of the draft.360function latest(state) {361 return state.copy || state.base362}363224// Access a property without creating an Immer draft.365function peek(draft, prop) {225function peek(draft: Drafted, prop: PropertyKey): any {226 const state = draft[DRAFT_STATE]227 const desc = Reflect.getOwnPropertyDescriptor(228 state ? latest(state) : draft,229 prop230 )231 return desc && desc.value232}233374function markChanged(state) {234export function markChanged(state: ImmerState) {235 if (!state.modified) {236 state.modified = true377378 const {base, drafts, parent} = state379 const copy = shallowCopy(base)380381 if (isSet(base)) {382 // Note: The `drafts` property is preserved for Set objects, since383 // we need to keep track of which values are drafted.384 assignSet(copy, drafts)385 } else {386 // Merge nested drafts into the copy.387 if (isMap(base)) assignMap(copy, drafts)388 else assign(copy, drafts)389 state.drafts = null237 if (238 state.type === ProxyType.ProxyObject ||239 state.type === ProxyType.ProxyArray240 ) {241 const copy = (state.copy = shallowCopy(state.base))242 each(state.drafts!, (key, value) => {243 // @ts-ignore244 copy[key] = value245 })246 state.drafts = undefined247 }248392 state.copy = copy393 if (parent) {394 markChanged(parent)249 if (state.parent) {250 markChanged(state.parent)251 }252 }253}254399/** Create traps that all use the `Reflect` API on the `latest(state)` */400function makeReflectTraps<T extends object>(401 names: (keyof typeof Reflect)[]402): ProxyHandler<T> {403 return names.reduce(404 (traps, name) => {405 // @ts-ignore406 traps[name] = (state, ...args) => Reflect[name](latest(state), ...args)407 return traps408 },409 {} as any410 )411}412413function makeTrapsForGetters<T extends object>(414 getters: {415 [K in keyof T]: (416 state: ES6State<T>417 ) => /* Skip first arg of: ProxyHandler<T>[K] */ any255function prepareCopy(state: ProxyState) {256 if (!state.copy) {257 state.copy = shallowCopy(state.base)258 }419): ProxyHandler<T> {420 return assign({}, reflectTraps, {421 get(state, prop, receiver) {422 return getters.hasOwnProperty(prop)423 ? getters[prop](state, prop, receiver)424 : Reflect.get(state, prop, receiver)425 },426 setPrototypeOf(state) {427 throw new Error("Object.setPrototypeOf() cannot be used on an Immer draft") // prettier-ignore428 }429 })259}
modified:src/scope.ts+17 added-11 removed
1import {DRAFT_STATE} from "./common"2import {ImmerState, Patch, PatchListener} from "./types"2import {Patch, PatchListener, Drafted, ProxyType} from "./types"3import {Immer} from "./immer"45/** Each scope represents a `produce` call. */6export class ImmerScope {7 static current?: ImmerScope
3 unmodified lines
11 canAutoFreeze: boolean12 drafts: any[]13 parent?: ImmerScope14 patchListener?: PatchListener15 immer: Immer1615 constructor(parent?: ImmerScope) {17 constructor(parent: ImmerScope | undefined, immer: Immer) {18 this.drafts = []19 this.parent = parent20 this.immer = immer2122 // Whenever the modified draft contains a draft from another scope, we23 // need to prevent auto-freezing so the unowned draft can be finalized.24 this.canAutoFreeze = true2223 // To avoid prototype lookups:24 this.patches = null as any // TODO:25 }2627 usePatches(patchListener: PatchListener) {27 usePatches(patchListener?: PatchListener) {28 if (patchListener) {29 this.patches = []30 this.inversePatches = []31 this.patchListener = patchListener
3 unmodified lines
35 revoke() {36 this.leave()37 this.drafts.forEach(revoke)38 // @ts-ignore39 this.drafts = null // TODO: // Make draft-related methods throw.39 this.drafts = null40 }4142 leave() {43 if (this === ImmerScope.current) {44 ImmerScope.current = this.parent45 }46 }4748 static enter() {49 const scope = new ImmerScope(ImmerScope.current)48 static enter(immer: Immer) {49 const scope = new ImmerScope(ImmerScope.current, immer)50 ImmerScope.current = scope51 return scope52 }53}5455function revoke(draft) {56 draft[DRAFT_STATE].revoke()55function revoke(draft: Drafted) {56 const state = draft[DRAFT_STATE]57 if (58 state.type === ProxyType.ProxyObject ||59 state.type === ProxyType.ProxyArray60 )61 state.revoke()62 else state.revoked = true63}
added:src/set.ts+145 added
1import {DRAFT_STATE, latest, isDraftable, iteratorSymbol} from "./common"23import {ImmerScope} from "./scope"4import {AnySet, Drafted, ImmerState, ImmerBaseState, ProxyType} from "./types"5import {assertUnrevoked} from "./es5"67export interface SetState extends ImmerBaseState {8 type: ProxyType.Set9 copy: AnySet | undefined10 base: AnySet11 drafts: Map<any, Drafted> // maps the original value to the draft value in the new set12 revoked: boolean13 draft: Drafted<AnySet, SetState>14}1516// Make sure DraftSet declarion doesn't die if Map is not avialable...17/* istanbul ignore next */18const SetBase: SetConstructor =19 typeof Set !== "undefined" ? Set : (function FakeSet() {} as any)2021export class DraftSet<K, V> extends SetBase implements Set<V> {22 [DRAFT_STATE]: SetState23 constructor(target: AnySet, parent?: ImmerState) {24 super()25 this[DRAFT_STATE] = {26 type: ProxyType.Set,27 parent,28 scope: parent ? parent.scope : ImmerScope.current!,29 modified: false,30 finalized: false,31 copy: undefined,32 base: target,33 draft: this,34 drafts: new Map(),35 revoked: false,36 isManual: false37 }38 }3940 get size(): number {41 return latest(this[DRAFT_STATE]).size42 }4344 has(value: V): boolean {45 const state = this[DRAFT_STATE]46 assertUnrevoked(state)47 // bit of trickery here, to be able to recognize both the value, and the draft of its value48 if (!state.copy) {49 return state.base.has(value)50 }51 if (state.copy.has(value)) return true52 if (state.drafts.has(value) && state.copy.has(state.drafts.get(value)))53 return true54 return false55 }5657 add(value: V): this {58 const state = this[DRAFT_STATE]59 assertUnrevoked(state)60 if (state.copy) {61 state.copy.add(value)62 } else if (!state.base.has(value)) {63 prepareCopy(state)64 state.scope.immer.markChanged(state)65 state.copy!.add(value)66 }67 return this68 }6970 delete(value: V): boolean {71 if (!this.has(value)) {72 return false73 }7475 const state = this[DRAFT_STATE]76 assertUnrevoked(state)77 prepareCopy(state)78 state.scope.immer.markChanged(state)79 return (80 state.copy!.delete(value) ||81 (state.drafts.has(value)82 ? state.copy!.delete(state.drafts.get(value))83 : /* istanbul ignore next */ false)84 )85 }8687 clear() {88 const state = this[DRAFT_STATE]89 assertUnrevoked(state)90 prepareCopy(state)91 state.scope.immer.markChanged(state)92 return state.copy!.clear()93 }9495 values(): IterableIterator<V> {96 const state = this[DRAFT_STATE]97 assertUnrevoked(state)98 prepareCopy(state)99 return state.copy!.values()100 }101102 entries(): IterableIterator<[V, V]> {103 const state = this[DRAFT_STATE]104 assertUnrevoked(state)105 prepareCopy(state)106 return state.copy!.entries()107 }108109 keys(): IterableIterator<V> {110 return this.values()111 }112113 [iteratorSymbol]() {114 return this.values()115 }116117 forEach(cb: (value: V, key: V, self: this) => void, thisArg?: any) {118 const iterator = this.values()119 let result = iterator.next()120 while (!result.done) {121 cb.call(thisArg, result.value, result.value, this)122 result = iterator.next()123 }124 }125}126127export function proxySet(target: AnySet, parent?: ImmerState) {128 return new DraftSet(target, parent)129}130131function prepareCopy(state: SetState) {132 if (!state.copy) {133 // create drafts for all entries to preserve insertion order134 state.copy = new Set()135 state.base.forEach(value => {136 if (isDraftable(value)) {137 const draft = state.scope.immer.createProxy(value, state)138 state.drafts.set(value, draft)139 state.copy!.add(draft)140 } else {141 state.copy!.add(value)142 }143 })144 }145}
modified:src/types.ts+47 added-18 removed
1import {Nothing} from "./common"1import {Nothing, DRAFT_STATE} from "./common"2import {SetState} from "./set"3import {MapState} from "./map"4import {ProxyObjectState, ProxyArrayState} from "./proxy"5import {ES5ObjectState, ES5ArrayState} from "./es5"6import {ImmerScope} from "./scope"73export type Objectish = any[] | Map<any, any> | Set<any> | {}8export type Objectish = AnyObject | AnyArray | AnyMap | AnySet9export type ObjectishNoSet = AnyObject | AnyArray | AnyMap105export type ObjectishNoSet = any[] | Map<any, any> | {}11export type AnyObject = {[key: string]: any}12export type AnyArray = Array<any>13export type AnySet = Set<any>14export type AnyMap = Map<any, any>15export enum Archtype {16 Object,17 Array,18 Map,19 Set20}217export interface ImmerState<T = any> {22export enum ProxyType {23 ProxyObject,24 ProxyArray,25 ES5Object,26 ES5Array,27 Map,28 Set29}3031export interface ImmerBaseState {32 parent?: ImmerState9 base: T10 copy: T11 assigned: {[prop: string]: boolean; [index: number]: boolean}33 scope: ImmerScope34 modified: boolean35 finalized: boolean36 isManual: boolean37}3839export type ImmerState =40 | ProxyObjectState41 | ProxyArrayState42 | ES5ObjectState43 | ES5ArrayState44 | MapState45 | SetState4647// The _internal_ type used for drafts (not to be confused with Draft, which is public facing)48export type Drafted<Base = any, T extends ImmerState = ImmerState> = {49 [DRAFT_STATE]: T50} & Base5114type Tail<T extends any[]> = ((...t: T) => any) extends ((52type Tail<T extends any[]> = ((...t: T) => any) extends (53 _: any,54 ...tail: infer TT17) => any)55) => any56 ? TT57 : []5859/** Object types that should never be mapped */
153 unmodified lines
213 base: Base,214 recipe: (draft: D) => Return215 ): [Produced<Base, Return>, Patch[], Patch[]]216}179180// Backward compatibility with --target es5181// TODO: still needed?182// declare global {183// interface Set<T> {}184// interface Map<K, V> {}185// interface WeakSet<T> {}186// interface WeakMap<K extends object, V> {}187// }
modified:package.json+9 added-2 removed
68 unmodified lines
69 "immutable": "^3.8.2",70 "jest": "^24.7.1",71 "lodash": "^4.17.4",72 "lodash.clonedeep": "^4.5.0",73 "prettier": "1.17.0",73 "prettier": "1.19.1",74 "pretty-quick": "^1.8.0",75 "regenerator-runtime": "^0.11.1",76 "rimraf": "^2.6.2",77 "rollup-plugin-typescript2": "^0.25.3",
12 unmodified lines
90 "transform": {91 "\\.js$": "babel-jest",92 "\\.ts$": "ts-jest"93 },94 "preset": "ts-jest/presets/js-with-babel"94 "preset": "ts-jest/presets/js-with-babel",95 "globals": {96 "ts-jest": {97 "tsConfig": {98 "noUnusedLocals": false99 }100 }101 }102 }103}
modified:tsconfig.json+8 added-3 removed
1{2 "include": ["src"],2 "compilerOptions": {3 "lib": ["es2015"],4 "target": "ES6",5 "strict": true,6 "declaration": true,7 "importHelpers": false,8 "noImplicitAny": true,9 "esModuleInterop": true,10 "noUnusedLocals": true,11 "sourceMap": true,12 "declarationMap": true,10 "noImplicitAny": false // TODO: true,11 }13 "noEmit": true,14 "moduleResolution": "node"15 },16 "files": ["./src/index.ts"]17}
modified:yarn.lock+4 added-4 removed
5874 unmodified lines
5875 version "0.2.0"5876 resolved "https://registry.yarnpkg.com/preserve/-/preserve-0.2.0.tgz#815ed1f6ebc65926f865b310c0713bcb3315ce4b"5877 integrity sha1-gV7R9uvGWSb4ZbMQwHE7yzMVzks=58785879prettier@1.17.0:5880 version "1.17.0"5881 resolved "https://registry.yarnpkg.com/prettier/-/prettier-1.17.0.tgz#53b303676eed22cc14a9f0cec09b477b3026c008"5882 integrity sha512-sXe5lSt2WQlCbydGETgfm1YBShgOX4HxQkFPvbxkcwgDvGDeqVau8h+12+lmSVlP3rHPz0oavfddSZg/q+Szjw==5879prettier@1.19.1:5880 version "1.19.1"5881 resolved "https://registry.yarnpkg.com/prettier/-/prettier-1.19.1.tgz#f7d7f5ff8a9cd872a7be4ca142095956a60797cb"5882 integrity sha512-s7PoyDv/II1ObgQunCbB9PdLmUcBZcnWOcxDh7O0N/UwDEsHyqkW+Qh28jW+mVuCdx7gLB0BotYI1Y6uI9iyew==58835884pretty-format@^24.7.0:5885 version "24.7.0"5886 resolved "https://registry.yarnpkg.com/pretty-format/-/pretty-format-24.7.0.tgz#d23106bc2edcd776079c2daa5da02bcb12ed0c10"
1486 unmodified lines