Merge branch 'async-recipes'
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Michel Weststrate · committed by Michel Weststrate · parents eabe9db, b79bb97 · Browse files · 12 files·+706 added−188 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
12 files+706 added−188 removed
- tests:+339 added−6 removed
- other:+367 added−182 removed
Provenance
- Commit
ff210d8- Tree
edb6951- Author
Michel Weststrate <mweststrate@gmail.com>- Committer
Michel Weststrate <mweststrate@gmail.com>- Parent 1
eabe9db- Parent 2
b79bb97
12 files changed+706 added−188 removed
added:__tests__/__snapshots__/manual.js.snap+101 added
1+// Jest Snapshot v1, https://goo.gl/fbAQLP2+3+exports[`manual - es5 cannot modify after finish 1`] = `"Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? {\\"a\\":2}"`;4+5+exports[`manual - es5 should check arguments 1`] = `"First argument to createDraft should be a plain object, an array, or an immerable object."`;6+7+exports[`manual - es5 should check arguments 2`] = `"First argument to createDraft should be a plain object, an array, or an immerable object."`;8+9+exports[`manual - es5 should check arguments 3`] = `"First argument to finishDraft should be an object from createDraft."`;10+11+exports[`manual - es5 should not finish drafts from produce 1`] = `"The draft provided was not created using \`createDraft\`"`;12+13+exports[`manual - es5 should not finish twice 1`] = `"The draft provided was has already been finished"`;14+15+exports[`manual - es5 should support patches drafts 1`] = `16+Array [17+ Array [18+ Array [19+ Object {20+ "op": "replace",21+ "path": Array [22+ "a",23+ ],24+ "value": 2,25+ },26+ Object {27+ "op": "add",28+ "path": Array [29+ "b",30+ ],31+ "value": 3,32+ },33+ ],34+ Array [35+ Object {36+ "op": "replace",37+ "path": Array [38+ "a",39+ ],40+ "value": 1,41+ },42+ Object {43+ "op": "remove",44+ "path": Array [45+ "b",46+ ],47+ },48+ ],49+ ],50+]51+`;52+53+exports[`manual - proxy cannot modify after finish 1`] = `"Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? {\\"a\\":2}"`;54+55+exports[`manual - proxy should check arguments 1`] = `"First argument to createDraft should be a plain object, an array, or an immerable object."`;56+57+exports[`manual - proxy should check arguments 2`] = `"First argument to createDraft should be a plain object, an array, or an immerable object."`;58+59+exports[`manual - proxy should check arguments 3`] = `"First argument to finishDraft should be an object from createDraft."`;60+61+exports[`manual - proxy should not finish drafts from produce 1`] = `"The draft provided was not created using \`createDraft\`"`;62+63+exports[`manual - proxy should not finish twice 1`] = `"The draft provided was has already been finished"`;64+65+exports[`manual - proxy should support patches drafts 1`] = `66+Array [67+ Array [68+ Array [69+ Object {70+ "op": "replace",71+ "path": Array [72+ "a",73+ ],74+ "value": 2,75+ },76+ Object {77+ "op": "add",78+ "path": Array [79+ "b",80+ ],81+ "value": 3,82+ },83+ ],84+ Array [85+ Object {86+ "op": "replace",87+ "path": Array [88+ "a",89+ ],90+ "value": 1,91+ },92+ Object {93+ "op": "remove",94+ "path": Array [95+ "b",96+ ],97+ },98+ ],99+ ],100+]101+`;modified:__tests__/base.js+60 added-1 removed
824 unmodified lines825 })826 expect(next.obj).toBe(next.arr[0])827 })828 829- it("can return an object with two references to any pristine draft", () => {829+ it("can return an object with two references to an unmodified draft", () => {830 const base = {a: {}}831 const next = produce(base, d => {832 return [d.a, d.a]833 })9 unmodified lines843 }).toThrow("Immer forbids circular references")844 })845 })846 847+ // TODO: rewrite tests with async/await once node 6 support is dropped848+ describe("async recipe function", () => {849+ it("can modify the draft", () => {850+ const base = {a: 0, b: 0}851+ return produce(base, d => {852+ d.a = 1853+ return Promise.resolve().then(() => {854+ d.b = 1855+ })856+ }).then(res => {857+ expect(res).not.toBe(base)858+ expect(res).toEqual({a: 1, b: 1})859+ })860+ })861+862+ it("works with rejected promises", () => {863+ let draft864+ const base = {a: 0, b: 0}865+ const err = new Error("passed")866+ return produce(base, d => {867+ draft = d868+ draft.b = 1869+ return Promise.reject(err)870+ }).then(871+ () => {872+ throw "failed"873+ },874+ e => {875+ expect(e).toBe(err)876+ expect(() => draft.a).toThrowError(/revoked/)877+ }878+ )879+ })880+881+ it("supports recursive produce calls after await", () => {882+ const base = {obj: {k: 1}}883+ return produce(base, d => {884+ const obj = d.obj885+ delete d.obj886+ return Promise.resolve().then(() => {887+ d.a = produce({}, d => {888+ d.b = obj // Assign a draft owned by the parent scope.889+ })890+891+ // Auto-freezing is prevented when an unowned draft exists.892+ expect(Object.isFrozen(d.a)).toBeFalsy()893+894+ // Ensure `obj` is not revoked.895+ obj.c = 1896+ })897+ }).then(res => {898+ expect(res).not.toBe(base)899+ expect(res).toEqual({900+ a: {b: {k: 1, c: 1}}901+ })902+ })903+ })904+ })905+906 it("throws when the draft is modified and another object is returned", () => {907 const base = {x: 3}908 expect(() => {909 produce(base, draft => {312 unmodified linesadded:__tests__/manual.js+136 added
1+"use strict"2+import {3+ setUseProxies,4+ createDraft,5+ finishDraft,6+ produce,7+ isDraft8+} from "../src/index"9+10+runTests("proxy", true)11+runTests("es5", false)12+13+function runTests(name, useProxies) {14+ describe("manual - " + name, () => {15+ setUseProxies(useProxies)16+17+ it("should check arguments", () => {18+ expect(() => createDraft(3)).toThrowErrorMatchingSnapshot()19+ const buf = new Buffer([])20+ expect(() => createDraft(buf)).toThrowErrorMatchingSnapshot()21+ expect(() => finishDraft({})).toThrowErrorMatchingSnapshot()22+ })23+24+ it("should support manual drafts", () => {25+ const state = [{}, {}, {}]26+27+ const draft = createDraft(state)28+ draft.forEach((item, index) => {29+ item.index = index30+ })31+32+ const result = finishDraft(draft)33+34+ expect(result).not.toBe(state)35+ expect(result).toEqual([{index: 0}, {index: 1}, {index: 2}])36+ expect(state).toEqual([{}, {}, {}])37+ })38+39+ it("cannot modify after finish", () => {40+ const state = {a: 1}41+42+ const draft = createDraft(state)43+ draft.a = 244+ expect(finishDraft(draft)).toEqual({a: 2})45+ expect(() => {46+ draft.a = 347+ }).toThrowErrorMatchingSnapshot()48+ })49+50+ it("should support patches drafts", () => {51+ const state = {a: 1}52+53+ const draft = createDraft(state)54+ draft.a = 255+ draft.b = 356+57+ const listener = jest.fn()58+ const result = finishDraft(draft, listener)59+60+ expect(result).not.toBe(state)61+ expect(result).toEqual({a: 2, b: 3})62+ expect(listener.mock.calls).toMatchSnapshot()63+ })64+65+ it("should handle multiple create draft calls", () => {66+ const state = {a: 1}67+68+ const draft = createDraft(state)69+ draft.a = 270+71+ const draft2 = createDraft(state)72+ draft2.b = 373+74+ const result = finishDraft(draft)75+76+ expect(result).not.toBe(state)77+ expect(result).toEqual({a: 2})78+79+ draft2.a = 480+ const result2 = finishDraft(draft2)81+ expect(result2).not.toBe(result)82+ expect(result2).toEqual({a: 4, b: 3})83+ })84+85+ it("combines with produce - 1", () => {86+ const state = {a: 1}87+88+ const draft = createDraft(state)89+ draft.a = 290+ const res1 = produce(draft, d => {91+ d.b = 392+ })93+ draft.b = 494+ const res2 = finishDraft(draft)95+ expect(res1).toEqual({a: 2, b: 3})96+ expect(res2).toEqual({a: 2, b: 4})97+ })98+99+ it("combines with produce - 2", () => {100+ const state = {a: 1}101+102+ const res1 = produce(state, draft => {103+ draft.b = 3104+ const draft2 = createDraft(draft)105+ draft.c = 4106+ draft2.d = 5107+ const res2 = finishDraft(draft2)108+ expect(res2).toEqual({109+ a: 1,110+ b: 3,111+ d: 5112+ })113+ draft.d = 2114+ })115+ expect(res1).toEqual({116+ a: 1,117+ b: 3,118+ c: 4,119+ d: 2120+ })121+ })122+123+ it("should not finish drafts from produce", () => {124+ produce({x: 1}, draft => {125+ expect(() => finishDraft(draft)).toThrowErrorMatchingSnapshot()126+ })127+ })128+129+ it("should not finish twice", () => {130+ const draft = createDraft({a: 1})131+ draft.a++132+ finishDraft(draft)133+ expect(() => finishDraft(draft)).toThrowErrorMatchingSnapshot()134+ })135+ })136+}modified:__tests__/produce.ts+42 added-5 removed
194 unmodified lines195 })196 exactType(result, {} as any[])197 })198 199-it("can produce nothing", () => {200- let result = produce({}, _ => nothing)199+it("can produce an undefined value", () => {200+ let base = {} as {readonly a: number}201+202+ // Return only nothing.203+ let result = produce(base, _ => nothing)204 exactType(result, undefined)205+206+ // Return maybe nothing.207+ let result2 = produce(base, draft => {208+ if (draft.a > 0) return nothing209+ })210+ exactType(result2, {} as typeof base | undefined)211 })212 213+it("can return the draft itself", () => {214+ let base = {} as {readonly a: number}215+ let result = produce(base, draft => draft)216+217+ // Currently, the `readonly` modifier is lost.218+ exactType(result, {} as {a: number} | undefined)219+})220+221+it("can return a promise", () => {222+ let base = {} as {readonly a: number}223+224+ // Return a promise only.225+ exactType(226+ produce(base, draft => {227+ return Promise.resolve(draft.a > 0 ? null : undefined)228+ }),229+ {} as Promise<{readonly a: number} | null>230+ )231+232+ // Return a promise or undefined.233+ exactType(234+ produce(base, draft => {235+ if (draft.a > 0) return Promise.resolve()236+ }),237+ {} as (Promise<{readonly a: number}> | {readonly a: number})238+ )239+})240+241 it("works with `void` hack", () => {205- let obj = {} as {readonly a: number}206- let res = produce(obj, s => void s.a++)207- exactType(res, obj)242+ let base = {} as {readonly a: number}243+ let copy = produce(base, s => void s.a++)244+ exactType(copy, base)245 })246 247 it("works with generic parameters", () => {248 let insert = <T>(array: ReadonlyArray<T>, index: number, elem: T) => {11 unmodified linesmodified:src/es5.js+21 added-20 removed
1 "use strict"2-// @ts-check3-2 import {3 each,4 has,5 is,2 unmodified lines8 isEnumerable,9 shallowCopy,10 DRAFT_STATE11 } from "./common"12+import {ImmerScope} from "./scope"13 14+// property descriptors are recycled to make sure we don't create a get and set closure per property,15+// but share them all instead16 const descriptors = {}17 17-// For nested produce calls:18-export const scopes = []19-export const currentScope = () => scopes[scopes.length - 1]20-21-export function willFinalize(result, baseDraft, needPatches) {22- const scope = currentScope()23- scope.forEach(state => (state.finalizing = true))24- if (result === undefined || result === baseDraft) {25- if (needPatches) markChangesRecursively(baseDraft)18+export function willFinalize(scope, result, isReplaced) {19+ scope.drafts.forEach(draft => {20+ draft[DRAFT_STATE].finalizing = true21+ })22+ if (!isReplaced) {23+ if (scope.patches) {24+ markChangesRecursively(scope.drafts[0])25+ }26 // This is faster when we don't care about which attributes changed.27- markChangesSweep(scope)27+ markChangesSweep(scope.drafts)28 }29 // When a child draft is returned, look for changes.30 else if (isDraft(result) && result[DRAFT_STATE].scope === scope) {31 markChangesSweep(scope.drafts)32 }33 }34 35-export function createDraft(base, parent) {35+export function createProxy(base, parent) {36 const isArray = Array.isArray(base)37 const draft = clonePotentialDraft(base)38 each(draft, prop => {39 proxyProperty(draft, prop, isArray || isEnumerable(base, prop))40 })41 42 // See "proxy.js" for property documentation.43+ const scope = parent ? parent.scope : ImmerScope.current44 const state = {44- scope: parent ? parent.scope : currentScope(),45+ scope,46 modified: false,47 finalizing: false, // es5 only48 finalized: false,49 assigned: {},5 unmodified lines55 revoked: false // es5 only56 }57 58 createHiddenProperty(draft, DRAFT_STATE, state)58- state.scope.push(state)59+ scope.drafts.push(draft)60 return draft61 }62 63 function revoke() {9 unmodified lines73 const value = source(state)[prop]74 // Drafts are only created for proxyable values that exist in the base state.75 if (!state.finalizing && value === state.base[prop] && isDraftable(value)) {76 prepareCopy(state)76- return (state.copy[prop] = createDraft(value, state))77+ return (state.copy[prop] = createProxy(value, state))78 }79 return value80 }81 57 unmodified lines139 )140 }141 142 // This looks expensive, but only proxies are visited, and only objects without known changes are scanned.142-function markChangesSweep(scope) {143+function markChangesSweep(drafts) {144 // The natural order of drafts in the `scope` array is based on when they145 // were accessed. By processing drafts in reverse natural order, we have a146 // better chance of processing leaf nodes first. When a leaf node is known to147 // have changed, we can avoid any traversal of its ancestor nodes.147- for (let i = scope.length - 1; i >= 0; i--) {148- const state = scope[i]149- if (state.modified === false) {148+ for (let i = drafts.length - 1; i >= 0; i--) {149+ const state = drafts[i][DRAFT_STATE]150+ if (!state.modified) {151 if (Array.isArray(state.base)) {152 if (hasArrayChanges(state)) markChanged(state)153 } else if (hasObjectChanges(state)) markChanged(state)154 }85 unmodified linesmodified:src/immer.d.ts+22 added-8 removed
41 unmodified lines42 }43 44 export type PatchListener = (patches: Patch[], inversePatches: Patch[]) => void45 46-type IsVoidLike<T> = T extends void | undefined ? 1 : 047-46 /** Converts `nothing` into `undefined` */49-type FromNothing<T> = Nothing extends T ? Exclude<T, Nothing> | undefined : T47+type FromNothing<T> = T extends Nothing ? undefined : T48 49 /** The inferred return type of `produce` */52-export type Produced<T, Return> = IsVoidLike<Return> extends 053- ? FromNothing<Return>54- : IsVoidLike<Return> extends 155- ? T56- : T | FromNothing<Exclude<Return, void>>50+export type Produced<Base, Return> = Return extends void51+ ? Base52+ : Return extends Promise<infer Result>53+ ? Promise<Result extends void ? Base : FromNothing<Result>>54+ : FromNothing<Return>55 56 type ImmutableTuple<T extends ReadonlyArray<any>> = {57 readonly [P in keyof T]: Immutable<T[P]>58 }92 unmodified lines151 * This function is a producer, which means copy-on-write is in effect.152 */153 export function applyPatches<S>(base: S, patches: Patch[]): S154 155+/**156+ * Create an Immer draft from the given base state, which may be a draft itself.157+ * The draft can be modified until you finalize it with the `finishDraft` function.158+ */159+export function createDraft<T>(base: T): Draft<T>160+161+/**162+ * Finalize an Immer draft from a `createDraft` call, returning the base state163+ * (if no changes were made) or a modified copy. The draft must *not* be164+ * mutated afterwards.165+ *166+ * Pass a function as the 2nd argument to generate Immer patches based on the167+ * changes that were made.168+ */169+export function finishDraft<T>(draft: T, listener?: PatchListener): Immutable<T>170+171 /** Get the underlying object that is represented by the given draft */172 export function original<T>(value: T): T | void173 174 /** Returns true if the given value is an Immer draft */66 unmodified linesmodified:src/immer.js+128 added-76 removed
11 unmodified lines12 shallowCopy,13 DRAFT_STATE,14 NOTHING15 } from "./common"16+import {ImmerScope} from "./scope"17 18 function verifyMinified() {}19 20 const configDefaults = {30 unmodified lines51 if (patchListener !== undefined && typeof patchListener !== "function") throw new Error("the third argument of a producer should not be set or a function")52 }53 54 let result54- // Only create proxies for plain objects/arrays.55- if (!isDraftable(base)) {56- result = recipe(base)57- if (result === undefined) return base58- }59- // The given value must be proxied.60- else {61- this.scopes.push([])62- const baseDraft = this.createDraft(base)63- try {64- result = recipe.call(baseDraft, baseDraft)65- this.willFinalize(result, baseDraft, !!patchListener)55 67- // Never generate patches when no listener exists.68- var patches = patchListener && [],69- inversePatches = patchListener && []70-71- // Finalize the modified draft...72- if (result === undefined || result === baseDraft) {73- result = this.finalize(74- baseDraft,75- [],76- patches,77- inversePatches78- )79- }80- // ...or use a replacement value.81- else {82- // Users must never modify the draft _and_ return something else.83- if (baseDraft[DRAFT_STATE].modified)84- throw new Error("An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.") // prettier-ignore85-86- // Finalize the replacement in case it contains (or is) a subset of the draft.87- if (isDraftable(result)) result = this.finalize(result)88-89- if (patchListener) {90- patches.push({91- op: "replace",92- path: [],93- value: result94- })95- inversePatches.push({96- op: "replace",97- path: [],98- value: base99- })100- }101- }56+ // Only plain objects, arrays, and "immerable classes" are drafted.57+ if (isDraftable(base)) {58+ const scope = ImmerScope.enter()59+ const proxy = this.createProxy(base)60+ let hasError = true61+ try {62+ result = recipe.call(proxy, proxy)63+ hasError = false64 } finally {103- this.currentScope().forEach(state => state.revoke())104- this.scopes.pop()65+ // finally instead of catch + rethrow better preserves original stack66+ if (hasError) scope.revoke()67+ else scope.leave()68 }106- patchListener && patchListener(patches, inversePatches)69+ if (result instanceof Promise) {70+ return result.then(71+ result => {72+ scope.usePatches(patchListener)73+ return this.processResult(result, scope)74+ },75+ error => {76+ scope.revoke()77+ throw error78+ }79+ )80+ }81+ scope.usePatches(patchListener)82+ return this.processResult(result, scope)83+ } else {84+ result = recipe(base)85+ if (result === undefined) return base86+ return result !== NOTHING ? result : undefined87 }108- // Normalize the result.109- return result === NOTHING ? undefined : result88 }89+ createDraft(base) {90+ if (!isDraftable(base)) throw new Error("First argument to createDraft should be a plain object, an array, or an immerable object.") // prettier-ignore91+ const scope = ImmerScope.enter()92+ const proxy = this.createProxy(base)93+ scope.leave()94+ proxy[DRAFT_STATE].customDraft = true95+ return proxy96+ }97+ finishDraft(draft, patchListener) {98+ if (!isDraft(draft)) throw new Error("First argument to finishDraft should be an object from createDraft.") // prettier-ignore99+ const state = draft[DRAFT_STATE]100+ if (!state.customDraft) throw new Error("The draft provided was not created using `createDraft`") // prettier-ignore101+ if (state.finalized) throw new Error("The draft provided was has already been finished") // prettier-ignore102+ // TODO: check if created with createDraft103+ // TODO: check if not finsihed twice104+ const {scope} = state105+ scope.usePatches(patchListener)106+ return this.processResult(undefined, scope)107+ }108 setAutoFreeze(value) {109 this.autoFreeze = value110 }111 setUseProxies(value) {7 unmodified lines119 }120 // Otherwise, produce a copy of the base state.121 return this.produce(base, draft => applyPatches(draft, patches))122 }123+ /** @internal */124+ processResult(result, scope) {125+ const baseDraft = scope.drafts[0]126+ const isReplaced = result !== undefined && result !== baseDraft127+ this.willFinalize(scope, result, isReplaced)128+ if (isReplaced) {129+ if (baseDraft[DRAFT_STATE].modified) {130+ scope.revoke()131+ throw new Error("An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.") // prettier-ignore132+ }133+ if (isDraftable(result)) {134+ // Finalize the result in case it contains (or is) a subset of the draft.135+ result = this.finalize(result, null, scope)136+ }137+ if (scope.patches) {138+ scope.patches.push({139+ op: "replace",140+ path: [],141+ value: result142+ })143+ scope.inversePatches.push({144+ op: "replace",145+ path: [],146+ value: baseDraft[DRAFT_STATE].base147+ })148+ }149+ } else {150+ // Finalize the base draft.151+ result = this.finalize(baseDraft, [], scope)152+ }153+ scope.revoke()154+ if (scope.patches) {155+ scope.patchListener(scope.patches, scope.inversePatches)156+ }157+ return result !== NOTHING ? result : undefined158+ }159 /**160 * @internal161 * Finalize a draft, returning either the unmodified base state or a modified162 * copy of the base state.163 */131- finalize(draft, path, patches, inversePatches) {164+ finalize(draft, path, scope) {165 const state = draft[DRAFT_STATE]166 if (!state) {167 if (Object.isFrozen(draft)) return draft135- return this.finalizeTree(draft)168+ return this.finalizeTree(draft, null, scope)169 }137- // Never finalize drafts owned by an outer scope.138- if (state.scope !== this.currentScope()) {170+ // Never finalize drafts owned by another scope.171+ if (state.scope !== scope) {172 return draft173 }141- if (!state.modified) return state.base174+ if (!state.modified) {175+ return state.base176+ }177 if (!state.finalized) {178 state.finalized = true144- this.finalizeTree(state.draft, path, patches, inversePatches)179+ this.finalizeTree(state.draft, path, scope)180+181 if (this.onDelete) {182 // The `assigned` object is unreliable with ES5 drafts.183 if (this.useProxies) {184 const {assigned} = state6 unmodified lines191 if (!has(copy, prop)) this.onDelete(state, prop)192 })193 }194 }159- if (this.onCopy) this.onCopy(state)195+ if (this.onCopy) {196+ this.onCopy(state)197+ }198 161- // Nested producers must never auto-freeze their result,162- // because it may contain drafts from parent producers.163- if (this.autoFreeze && this.scopes.length === 1) {199+ // At this point, all descendants of `state.copy` have been finalized,200+ // so we can be sure that `scope.canAutoFreeze` is accurate.201+ if (this.autoFreeze && scope.canAutoFreeze) {202 Object.freeze(state.copy)203 }204 167- if (patches) generatePatches(state, path, patches, inversePatches)205+ if (path && scope.patches) {206+ generatePatches(207+ state,208+ path,209+ scope.patches,210+ scope.inversePatches211+ )212+ }213 }214 return state.copy215 }216 /**217 * @internal218 * Finalize all drafts in the given state tree.219 */175- finalizeTree(root, path, patches, inversePatches) {220+ finalizeTree(root, rootPath, scope) {221 const state = root[DRAFT_STATE]222 if (state) {223 if (!this.useProxies) {224 state.finalizing = true2 unmodified lines227 }228 root = state.copy229 }230 186- const {onAssign} = this231+ const needPatches = !!rootPath && !!scope.patches232 const finalizeProperty = (prop, value, parent) => {233 if (value === parent) {234 throw Error("Immer forbids circular references")235 }236 192- // The only possible draft (in the scope of a `finalizeTree` call) is the `root` object.193- const inDraft = !!state && parent === root237+ // In the `finalizeTree` method, only the `root` object may be a draft.238+ const isDraftProp = !!state && parent === root239 240 if (isDraft(value)) {196- value =197- // Patches are never generated for assigned properties.198- patches && inDraft && !state.assigned[prop]199- ? this.finalize(value, path.concat(prop), patches, inversePatches) // prettier-ignore200- : this.finalize(value)241+ const path =242+ isDraftProp && needPatches && !state.assigned[prop]243+ ? rootPath.concat(prop)244+ : null245 246+ // Drafts owned by `scope` are finalized here.247+ value = this.finalize(value, path, scope)248+249+ // Drafts from another scope must prevent auto-freezing.250+ if (isDraft(value)) {251+ scope.canAutoFreeze = false252+ }253+254 // Preserve non-enumerable properties.255 if (Array.isArray(parent) || isEnumerable(parent, prop)) {256 parent[prop] = value257 } else {258 Object.defineProperty(parent, prop, {value})259 }260 261 // Unchanged drafts are never passed to the `onAssign` hook.210- if (inDraft && value === state.base[prop]) return262+ if (isDraftProp && value === state.base[prop]) return263 }264 // Unchanged draft properties are ignored.213- else if (inDraft && is(value, state.base[prop])) {265+ else if (isDraftProp && is(value, state.base[prop])) {266 return267 }268 // Search new objects for unfinalized drafts. Frozen objects should never contain drafts.269 else if (isDraftable(value) && !Object.isFrozen(value)) {270 each(value, finalizeProperty)271 }272 221- if (inDraft && onAssign) {222- onAssign(state, prop, value)273+ if (isDraftProp && this.onAssign) {274+ this.onAssign(state, prop, value)275 }276 }277 278 each(root, finalizeProperty)3 unmodified linesmodified:src/immer.js.flow+13 added
88 unmodified lines89 90 declare export function original<S>(value: S): ?S91 92 declare export function isDraft(value: any): boolean93+94+/**95+ * Creates a mutable draft from an (immutable) object / array. 96+ * The draft can be modified until `finishDraft` is called97+ */98+declare export function createDraft<T>(base: T): T99+100+/**101+ * Given a draft that was created using `createDraft`, 102+ * finalizes the draft into a new immutable object.103+ * Optionally a patch-listener can be provided to gather the patches that are needed to construct the object.104+ */105+declare export function finishDraft<T>(base: T, listener?: PatchListener): Tmodified:src/index.js+16 added
44 unmodified lines4546474849505152535455565758596061626364656667685 unmodified lines44 unmodified lines * This function is a producer, which means copy-on-write is in effect. */export const applyPatches = immer.applyPatches.bind(immer)
/** * Create an Immer draft from the given base state, which may be a draft itself. * The draft can be modified until you finalize it with the `finishDraft` function. */export const createDraft = immer.createDraft.bind(immer)
/** * Finalize an Immer draft from a `createDraft` call, returning the base state * (if no changes were made) or a modified copy. The draft must *not* be * mutated afterwards. * * Pass a function as the 2nd argument to generate Immer patches based on the * changes that were made. */export const finishDraft = immer.finishDraft.bind(immer)
export { original, isDraft, isDraftable,5 unmodified linesmodified:src/proxy.js+10 added-11 removed
1 "use strict"2-// @ts-check3-2 import {3 assign,4 each,5 has,2 unmodified lines8 isDraft,9 shallowCopy,10 DRAFT_STATE11 } from "./common"12+import {ImmerScope} from "./scope"13 15-// For nested produce calls:16-export const scopes = []17-export const currentScope = () => scopes[scopes.length - 1]18-14 // Do nothing before being finalized.15 export function willFinalize() {}16 22-export function createDraft(base, parent) {17+export function createProxy(base, parent) {18+ const scope = parent ? parent.scope : ImmerScope.current19 const state = {20 // Track which produce call this is associated with.25- scope: parent ? parent.scope : currentScope(),21+ scope,22 // True for both shallow and deep changes.23 modified: false,24 // Used during finalization.25 finalized: false,13 unmodified lines39 revoke: null40 }41 42 const {revoke, proxy} = Array.isArray(base)43+ ? // [state] is used for arrays, to make sure the proxy is array-ish and not violate invariants,44+ // although state itself is an object47- ? Proxy.revocable([state], arrayTraps)45+ Proxy.revocable([state], arrayTraps)46 : Proxy.revocable(state, objectTraps)47 48 state.draft = proxy49 state.revoke = revoke50 53- state.scope.push(state)51+ scope.drafts.push(proxy)52 return proxy53 }54 55 const objectTraps = {37 unmodified lines93 }94 return objectTraps.set.call(this, state[0], prop, value)95 }96 97+// returns the object we should be reading the current value from, which is base, until some change has been made98 function source(state) {99 return state.copy || state.base100 }101 16 unmodified lines118 // Store drafts on the copy (when one exists).119 drafts = state.copy120 }121 123- return (drafts[prop] = createDraft(value, state))122+ return (drafts[prop] = createProxy(value, state))123 }124 125 function set(state, prop, value) {126 if (!state.modified) {42 unmodified linesadded:src/scope.js+42 added
1+import {DRAFT_STATE} from "./common"2+3+/** Each scope represents a `produce` call. */4+export class ImmerScope {5+ constructor(parent) {6+ this.drafts = []7+ this.parent = parent8+9+ // Whenever the modified draft contains a draft from another scope, we10+ // need to prevent auto-freezing so the unowned draft can be finalized.11+ this.canAutoFreeze = true12+13+ // To avoid prototype lookups:14+ this.patches = null15+ }16+ usePatches(patchListener) {17+ if (patchListener) {18+ this.patches = []19+ this.inversePatches = []20+ this.patchListener = patchListener21+ }22+ }23+ revoke() {24+ this.leave()25+ this.drafts.forEach(revoke)26+ this.drafts = null // Make draft-related methods throw.27+ }28+ leave() {29+ if (this === ImmerScope.current) {30+ ImmerScope.current = this.parent31+ }32+ }33+}34+35+ImmerScope.current = null36+ImmerScope.enter = function() {37+ return (this.current = new ImmerScope(this.current))38+}39+40+function revoke(draft) {41+ draft[DRAFT_STATE].revoke()42+}modified:readme.md+115 added-67 removed
333 unmodified lines334 For a more in-depth study, see [Distributing patches and rebasing actions using Immer](https://medium.com/@mweststrate/distributing-state-changes-using-snapshots-patches-and-actions-part-2-2f50d8363988)335 336 Tip: Check this trick to [compress patches](https://medium.com/@david.b.edelstein/using-immer-to-compress-immer-patches-f382835b6c69) produced over time.337 338-## Auto freezing338+## Async producers339 340-Immer automatically freezes any state trees that are modified using `produce`. This protects against accidental modifications of the state tree outside of a producer. This comes with a performance impact, so it is recommended to disable this option in production. It is by default enabled. By default, it is turned on during local development and turned off in production. Use `setAutoFreeze(true / false)` to explicitly turn this feature on or off.340+It is allowed to return Promise objects from recipes. Or, in other words, to use `async / await`. This can be pretty useful for long running processes, that only produce the new object once the promise chain resolves. Note that `produce` itself (even in the curried form) will return a promise if the producer is async. Example:341 342+```javascript343+import produce from "immer"344+345+const user = {346+ name: "michel",347+ todos: []348+}349+350+const loadedUser = await produce(user, async function(draft) {351+ user.todos = await (await window.fetch("http://host/" + draft.name)).json()352+})353+```354+355+_Warning: please note that the draft shouldn't be 'leaked' from the async process and stored else where. The draft will still be revoked as soon as the async process completes._356+357+## `createDraft` and `finishDraft`358+359+`createDraft` and `finishDraft` are two low-level functions that are mostly useful for libraries that build abstractions on top of immer. It avoids the need to always create a function in order to work with drafts. Instead, one can create a draft, modify it, and at some time in the future finish the draft, in which case the next immutable state will be produced. We could for example rewrite our above example as:360+361+```javascript362+import {createDraft, finishDraft} from "immer"363+364+const user = {365+ name: "michel",366+ todos: []367+}368+369+const draft = createDraft(user)370+draft.todos = await (await window.fetch("http://host/" + draft.name)).json()371+const loadedUser = finishDraft(draft)372+```373+374+Note: `finishDraft` takes a `patchListener` as second argument, which can be used to record the patches, similarly to `produce`.375+376+_Warning: in general, we recommend to use `produce` instead of the `createDraft` / `finishDraft` combo, `produce` is less error prone in usage, and more clearly separates the concepts of mutability and immutability in your code base._377+378 ## Returning data from producers379 380 It is not needed to return anything from a producer, as Immer will return the (finalized) version of the `draft` anyway. However, it is allowed to just `return draft`.381 75 unmodified lines457 ```458 459 N.B. Note that this problem is specific for the `undefined` value, any other value, including `null`, doesn't suffer from this issue.460 461+## Inline shortcuts using `void`462+463+Draft mutations in Immer usually warrant a code block, since a return denotes an overwrite. Sometimes that can stretch code a little more than you might be comfortable with.464+465+In such cases, you can use javascripts [`void`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/void) operator, which evaluates expressions and returns `undefined`.466+467+```javascript468+// Single mutation469+produce(draft => void (draft.user.age += 1))470+471+// Multiple mutations472+produce(draft => void ((draft.user.age += 1), (draft.user.height = 186)))473+```474+475+Code style is highly personal, but for code bases that are to be understood by many, we recommend to stick to the classic `draft => { draft.user.age += 1}` to avoid cognitive overhead.476+477 ## Extracting the original object from a proxied instance478 479 Immer exposes a named export `original` that will get the original object from the proxied instance inside `produce` (or return `undefined` for unproxied values). A good example of when this can be useful is when searching for nodes in a tree-like state using strict equality.480 17 unmodified lines498 })499 isDraft(nextState) // => false500 ```501 450-## Using `this`502+## Auto freezing503 452-The recipe will be always invoked with the `draft` as `this` context.504+Immer automatically freezes any state trees that are modified using `produce`. This protects against accidental modifications of the state tree outside of a producer. This comes with a performance impact, so it is recommended to disable this option in production. It is by default enabled. By default, it is turned on during local development and turned off in production. Use `setAutoFreeze(true / false)` to explicitly turn this feature on or off.505 454-This means that the following constructions are also valid:455-456-```javascript457-const base = {counter: 0}458-459-const next = produce(base, function() {460- this.counter++461-})462-console.log(next.counter) // 1463-464-// OR465-const increment = produce(function() {466- this.counter++467-})468-console.log(increment(base).counter) // 1469-```470-471-## Inline shortcuts using `void`472-473-Draft mutations in Immer usually warrant a code block, since a return denotes an overwrite. Sometimes that can stretch code a little more than you might be comfortable with.474-475-In such cases, you can use javascripts [`void`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/void) operator, which evaluates expressions and returns `undefined`.476-477-```javascript478-// Single mutation479-produce(draft => void (draft.user.age += 1))480-481-// Multiple mutations482-produce(draft => void ((draft.user.age += 1), (draft.user.height = 186)))483-```484-485-Code style is highly personal, but for code bases that are to be understood by many, we recommend to stick to the classic `draft => { draft.user.age += 1}` to avoid cognitive overhead.486-487-## TypeScript or Flow488-489-The Immer package ships with type definitions inside the package, which should be picked up by TypeScript and Flow out of the box and without further configuration.490-491-The TypeScript typings automatically remove `readonly` modifiers from your draft types and return a value that matches your original type. See this practical example:492-493-```ts494-import produce from "immer"495-496-interface State {497- readonly x: number498-}499-500-// `x` cannot be modified here501-const state: State = {502- x: 0503-}504-505-const newState = produce<State>(state, draft => {506- // `x` can be modified here507- draft.x++508-})509-510-// `newState.x` cannot be modified here511-```512-513-This ensures that the only place you can modify your state is in your produce callbacks. It even works recursively and with `ReadonlyArray`s!514-515-**Note:** Immer v1.9+ supports Typescript v3.1+ only.516-506 ## Immer on older JavaScript environments?507 508 By default `produce` tries to use proxies for optimal performance. However, on older JavaScript engines `Proxy` is not available. For example, when running Microsoft Internet Explorer or React Native on Android. In such cases, Immer will fallback to an ES5 compatible implementation which works identical, but is a bit slower.509 54 unmodified lines564 draft.map = newMap565 })566 ```567 568+## TypeScript or Flow569+570+The Immer package ships with type definitions inside the package, which should be picked up by TypeScript and Flow out of the box and without further configuration.571+572+The TypeScript typings automatically remove `readonly` modifiers from your draft types and return a value that matches your original type. See this practical example:573+574+```ts575+import produce from "immer"576+577+interface State {578+ readonly x: number579+}580+581+// `x` cannot be modified here582+const state: State = {583+ x: 0584+}585+586+const newState = produce<State>(state, draft => {587+ // `x` can be modified here588+ draft.x++589+})590+591+// `newState.x` cannot be modified here592+```593+594+This ensures that the only place you can modify your state is in your produce callbacks. It even works recursively and with `ReadonlyArray`s!595+596+**Note:** Immer v1.9+ supports Typescript v3.1+ only.597+598+## Using `this`599+600+_Deprecated, this will probably be removed in a next major version, see [#308](https://github.com/mweststrate/immer/issues/308)_601+602+The recipe will be always invoked with the `draft` as `this` context.603+604+This means that the following constructions are also valid:605+606+```javascript607+const base = {counter: 0}608+609+const next = produce(base, function() {610+ this.counter++611+})612+console.log(next.counter) // 1613+614+// OR615+const increment = produce(function() {616+ this.counter++617+})618+console.log(increment(base).counter) // 1619+```620+621 # Pitfalls622 623 1. Don't redefine draft like, `draft = myCoolNewState`. Instead, either modify the `draft` or return a new state. See [Returning data from producers](#returning-data-from-producers).624 1. Immer assumes your state to be a unidirectional tree. That is, no object should appear twice in the tree, and there should be no circular references.85 unmodified lines710 - Immer is roughly as fast as ImmutableJS. However, the _immutableJS + toJS_ makes clear the cost that often needs to be paid later; converting the immutableJS objects back to plain objects, to be able to pass them to components, over the network etc... (And there is also the upfront cost of converting data received from e.g. the server to immutable JS)711 - Generating patches doesn't significantly slow immer down712 - The ES5 fallback implementation is roughly twice as slow as the proxy implementation, in some cases worse.713 714+## Migration715+716+**Immer 1.\* -> 2.0**717+718+Make sure you don't return any promises as state, because `produce` will actually invoke the promise and wait until it settles.719+720 ## FAQ721 722 _(for those who skimmed the above instead of actually reading)_723 35 unmodified lines