feat: add `Immer` class
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Every instance of the `Immer` class provides a bound `produce` function. As explained in #254, this class makes room for advanced configuration (if we need it) and allows for interop between Immer-using libraries that have different needs. I took the time to refactor while I was implementing this, so the diff may look more overwhelming than it is. :) Summary: 1. Renamed `immer.js` to `index.js` so the `Immer` class can have `immer.js` 2. Use the word "draft" in place of "proxy" in most places, because "draft" is a higher level of abstraction. It also makes sense to use the same semantics both internally and externally. 3. Moved `finalize` logic to the `Immer` class 4. Inlined the `freeze` function as only one callsite existed 5. Inlined the `createState` functions in both `proxy.js` and `es5.js` 6. Extract repeated code from `produceEs5` and `produceProxy` (which have since been removed) into the `Immer` class 7. The `es5.js` and `proxy.js` modules now have different exports: - `scopes`: an array of nested `produce` calls, where each value is an array of unrevoked proxies - `currentScope()`: shortcut for getting the last value of the `scopes` array - `createDraft()`: a renamed `createProxy` with the arguments swapped - `willFinalize()`: called right after the recipe function returns (only used by ES5 proxies) 8. Changed some "draft state" properties: - removed `hasCopy` in ES5 state (checking for truthiness of `copy` does the job) - renamed `proxy` to `draft` in ES5 state - renamed `finished` to `revoked` in ES5 state - renamed `proxies` to `drafts` in Proxy state - added `revoke` method (called by the `Immer` class) - added `draft` property to Proxy state - use null literals instead of undefined 9. Delay creation of `patches` and `inversePatches` arrays until the recipe function returns. This avoids array allocations when a rollback is performed by throwing. 10. Simplified `generatePatches` by removing the last two arguments, since they can be obtained from the `state` argument.
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
13 files+607 added−661 removed
- tests:+6 added−6 removed
- other:+601 added−655 removed
Provenance
- Commit
ecd04dc- Tree
04482b9- Author
aleclarson <alec.stanford.larson@gmail.com>- Committer
aleclarson <alec.stanford.larson@gmail.com>- Parent
66e51e1
13 files changed+607 added−661 removed
modified:__tests__/curry.js+5 added-5 removed
7 unmodified lines891011121213141516171819161718192021222356 unmodified lines7 unmodified lines describe("curry - " + name, () => { setUseProxies(useProxies)
it("should check arguments", () => { let error = /if first argument is not a function, the second argument to produce should be a function/ expect(() => produce()).toThrow(/produce expects 1 to 3 arguments/) expect(() => produce()).toThrow(error) expect(() => produce({})).toThrow(error)
expect(() => produce({}, {})).toThrow(/should be a function/) expect(() => produce({}, () => {}, [])).toThrow( /third argument of a producer/ ) expect(() => produce({}, {})).toThrow(/should be a function/) expect(() => produce({})).toThrow( /if first argument is not a function, the second argument to produce should be a function/ ) })
it("should support currying", () => { const state = [{}, {}, {}]56 unmodified linesmodified:__tests__/patch.js+1 added-1 removed
67 unmodified lines68 // Splice is unsupported69 expect(() => {70 const patch = {op: "remove", path: [0]}71 applyPatches([1, 2], [patch])72- }).toThrowError(/^Remove can only remove the last key of an array/)72+ }).toThrowError(/^Only the last index of an array can be removed/)73 })74 })75 76 describe("simple assignment - 1", () => {260 unmodified linesmodified:src/common.js+9 added-113 removed
12123458910116781314151617181920212223242526272829303132333491011123738394041424344454647484913141516171819205758596061626321656622232425262715 unmodified lines43444546904748924950515253545556100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160575859604 unmodified linesimport {generatePatches} from "./patches"
export const NOTHING = typeof Symbol !== "undefined" ? Symbol("immer-nothing") : {["immer-nothing"]: true}
export const PROXY_STATE = typeof Symbol !== "undefined" ? Symbol("immer-proxy-state") : "__$immer_state"export const DRAFT_STATE = typeof Symbol !== "undefined" ? Symbol("immer-state") : "__$immer_state"
export const RETURNED_AND_MODIFIED_ERROR = "An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft."
function verifyMinified() {}
const inProduction = (typeof process !== "undefined" && process.env.NODE_ENV === "production") || verifyMinified.name !== "verifyMinified"
let autoFreeze = !inProductionlet useProxies = typeof Proxy !== "undefined" && typeof Reflect !== "undefined"
/** * Automatically freezes any state trees generated by immer. * This protects against accidental modifications of the state tree outside of an immer function. * This comes with a performance impact, so it is recommended to disable this option in production. * It is by default enabled. * * @returns {void} */export function setAutoFreeze(enableAutoFreeze) { autoFreeze = enableAutoFreezeexport function isDraft(value) { return !!value && !!value[DRAFT_STATE]}
export function setUseProxies(value) { useProxies = value}
export function getUseProxies() { return useProxies}
export function isProxy(value) { return !!value && !!value[PROXY_STATE]}
export function isProxyable(value) {export function isDraftable(value) { if (!value) return false if (typeof value !== "object") return false if (Array.isArray(value)) return true const proto = Object.getPrototypeOf(value) return proto === null || proto === Object.prototype}
export function freeze(value) { if (autoFreeze) { Object.freeze(value) } return value}
export function original(value) { if (value && value[PROXY_STATE]) { return value[PROXY_STATE].base if (value && value[DRAFT_STATE]) { return value[DRAFT_STATE].base } // otherwise return undefined}
15 unmodified lines}
export function each(value, cb) { if (Array.isArray(value)) { for (let i = 0; i < value.length; i++) cb(i, value[i]) for (let i = 0; i < value.length; i++) cb(i, value[i], value) } else { for (let key in value) cb(key, value[key]) for (let key in value) cb(key, value[key], value) }}
export function has(thing, prop) { return Object.prototype.hasOwnProperty.call(thing, prop)}
// given a base object, returns it if unmodified, or return the changed cloned if modifiedexport function finalize(base, path, patches, inversePatches) { if (isProxy(base)) { const state = base[PROXY_STATE] if (state.modified === true) { if (state.finalized === true) return state.copy state.finalized = true const result = finalizeObject( useProxies ? state.copy : (state.copy = shallowCopy(base)), state, path, patches, inversePatches ) generatePatches( state, path, patches, inversePatches, state.base, result ) return result } else { return state.base } } finalizeNonProxiedObject(base) return base}
function finalizeObject(copy, state, path, patches, inversePatches) { const base = state.base each(copy, (prop, value) => { if (value !== base[prop]) { // if there was an assignment on this property, we don't need to generate // patches for the subtree const generatePatches = patches && !has(state.assigned, prop) copy[prop] = finalize( value, generatePatches && path.concat(prop), generatePatches && patches, inversePatches ) } }) return freeze(copy)}
function finalizeNonProxiedObject(parent) { // If finalize is called on an object that was not a proxy, it means that it is an object that was not there in the original // tree and it could contain proxies at arbitrarily places. Let's find and finalize them as well if (!isProxyable(parent)) return if (Object.isFrozen(parent)) return each(parent, (i, child) => { if (isProxy(child)) { parent[i] = finalize(child) } else finalizeNonProxiedObject(child) })}
export function is(x, y) { // From: https://github.com/facebook/fbjs/blob/c69904a511b900266935168223063dd8772dfc40/packages/fbjs/src/core/shallowEqual.js if (x === y) { return x !== 0 || 1 / x === 1 / y4 unmodified linesmodified:src/es5.js+76 added-106 removed
1 "use strict"2 // @ts-check3 4 import {5+ each,6+ has,7 is,6- isProxyable,7- PROXY_STATE,8+ isDraft,9+ isDraftable,10 shallowCopy,9- RETURNED_AND_MODIFIED_ERROR,10- has,11- each,12- finalize11+ DRAFT_STATE12 } from "./common"13 14 const descriptors = {}16-let states = null15 18-function createState(parent, proxy, base) {19- return {16+// For nested produce calls:17+export const scopes = []18+export const currentScope = () => scopes[scopes.length - 1]19+20+export function willFinalize(result, baseDraft, needPatches) {21+ const scope = currentScope()22+ scope.forEach(state => (state.finalizing = true))23+ if (result === undefined || result === baseDraft) {24+ if (needPatches) markChangesRecursively(baseDraft)25+ // This is faster when we don't care about which attributes changed.26+ markChangesSweep(scope)27+ }28+}29+30+export function createDraft(base, parent) {31+ if (isDraft(base)) throw new Error("This should never happen. Please report: https://github.com/mweststrate/immer/issues/new") // prettier-ignore32+33+ const draft = shallowCopy(base)34+ each(base, prop => {35+ Object.defineProperty(draft, "" + prop, createPropertyProxy("" + prop))36+ })37+38+ const state = {39 modified: false,40+ finalizing: false,41+ finalized: false,42 assigned: {}, // true: value was assigned to these props, false: was removed22- hasCopy: false,43 parent,44 base,25- proxy,26- copy: undefined,27- finished: false,28- finalizing: false,29- finalized: false45+ draft,46+ copy: null,47+ revoke,48+ revoked: false49 }50+51+ createHiddenProperty(draft, DRAFT_STATE, state)52+ currentScope().push(state)53+ return draft54 }55 56+function revoke() {57+ this.revoked = true58+}59+60 function source(state) {34- return state.hasCopy ? state.copy : state.base61+ return state.copy || state.base62 }63 64 function get(state, prop) {38- assertUnfinished(state)65+ assertUnrevoked(state)66 const value = source(state)[prop]40- if (!state.finalizing && value === state.base[prop] && isProxyable(value)) {41- // only create a proxy if the value is proxyable, and the value was in the base state42- // if it wasn't in the base state, the object is already modified and we will process it in finalize67+ // Drafts are only created for proxyable values that exist in the base state.68+ if (!state.finalizing && value === state.base[prop] && isDraftable(value)) {69 prepareCopy(state)44- return (state.copy[prop] = createProxy(state, value))70+ return (state.copy[prop] = createDraft(value, state))71 }72 return value73 }74 75 function set(state, prop, value) {50- assertUnfinished(state)76+ assertUnrevoked(state)77 state.assigned[prop] = true // optimization; skip this if there is no listener78 if (!state.modified) {79 if (is(source(state)[prop], value)) return80 markChanged(state)9 unmodified lines90 }91 }92 93 function prepareCopy(state) {68- if (state.hasCopy) return69- state.hasCopy = true70- state.copy = shallowCopy(state.base)94+ if (!state.copy) state.copy = shallowCopy(state.base)95 }96 73-// creates a proxy for plain objects / arrays74-function createProxy(parent, base) {75- const proxy = shallowCopy(base)76- each(base, i => {77- Object.defineProperty(proxy, "" + i, createPropertyProxy("" + i))78- })79- const state = createState(parent, proxy, base)80- createHiddenProperty(proxy, PROXY_STATE, state)81- states.push(state)82- return proxy83-}84-97 function createPropertyProxy(prop) {98 return (99 descriptors[prop] ||100 (descriptors[prop] = {101 configurable: true,102 enumerable: true,103 get() {92- return get(this[PROXY_STATE], prop)104+ return get(this[DRAFT_STATE], prop)105 },106 set(value) {95- set(this[PROXY_STATE], prop, value)107+ set(this[DRAFT_STATE], prop, value)108 }109 })110 )111 }112 101-function assertUnfinished(state) {102- if (state.finished === true)113+function assertUnrevoked(state) {114+ if (state.revoked === true)115 throw new Error(116 "Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? " +117 JSON.stringify(state.copy || state.base)118 )119 }120 109-// this sounds very expensive, but actually it is not that expensive in practice110-// as it will only visit proxies, and only do key-based change detection for objects for111-// which it is not already know that they are changed (that is, only object for which no known key was changed)112-function markChangesSweep() {113- // intentionally we process the proxies in reverse order;114- // ideally we start by processing leafs in the tree, because if a child has changed, we don't have to check the parent anymore115- // reverse order of proxy creation approximates this116- for (let i = states.length - 1; i >= 0; i--) {117- const state = states[i]121+// This looks expensive, but only proxies are visited, and only objects without known changes are scanned.122+function markChangesSweep(scope) {123+ // The natural order of drafts in the `scope` array is based on when they124+ // were accessed. By processing drafts in reverse natural order, we have a125+ // better chance of processing leaf nodes first. When a leaf node is known to126+ // have changed, we can avoid any traversal of its ancestor nodes.127+ for (let i = scope.length - 1; i >= 0; i--) {128+ const state = scope[i]129 if (state.modified === false) {130 if (Array.isArray(state.base)) {131 if (hasArrayChanges(state)) markChanged(state)132 } else if (hasObjectChanges(state)) markChanged(state)2 unmodified lines135 }136 137 function markChangesRecursively(object) {138 if (!object || typeof object !== "object") return128- const state = object[PROXY_STATE]139+ const state = object[DRAFT_STATE]140 if (!state) return130- const {proxy, base, assigned} = state141+ const {base, draft, assigned} = state142 if (!Array.isArray(object)) {143 // Look for added keys.133- Object.keys(proxy).forEach(key => {144+ Object.keys(draft).forEach(key => {145 // The `undefined` check is a fast path for pre-existing keys.146 if (base[key] === undefined && !has(base, key)) {147 assigned[key] = true148 markChanged(state)149 } else if (!assigned[key]) {150 // Only untouched properties trigger recursion.140- markChangesRecursively(proxy[key])151+ markChangesRecursively(draft[key])152 }153 })154 // Look for removed keys.155 Object.keys(base).forEach(key => {156 // The `undefined` check is a fast path for pre-existing keys.146- if (proxy[key] === undefined && !has(proxy, key)) {157+ if (draft[key] === undefined && !has(draft, key)) {158 assigned[key] = false159 markChanged(state)160 }161 })162 } else if (hasArrayChanges(state)) {163 markChanged(state)164 assigned.length = true154- if (proxy.length < base.length) {155- for (let i = proxy.length; i < base.length; i++) assigned[i] = false165+ if (draft.length < base.length) {166+ for (let i = draft.length; i < base.length; i++) assigned[i] = false167 } else {157- for (let i = base.length; i < proxy.length; i++) assigned[i] = true168+ for (let i = base.length; i < draft.length; i++) assigned[i] = true169 }159- for (let i = 0; i < proxy.length; i++) {170+ for (let i = 0; i < draft.length; i++) {171 // Only untouched indices trigger recursion.161- if (assigned[i] === undefined) markChangesRecursively(proxy[i])172+ if (assigned[i] === undefined) markChangesRecursively(draft[i])173 }174 }175 }176 177 function hasObjectChanges(state) {167- const {base, proxy} = state178+ const {base, draft} = state179 180 // Search for added keys. Start at the back, because non-numeric keys181 // are ordered by time of definition on the object.171- const keys = Object.keys(proxy)182+ const keys = Object.keys(draft)183 for (let i = keys.length - 1; i >= 0; i--) {184 // The `undefined` check is a fast path for pre-existing keys.185 if (base[keys[i]] === undefined && !has(base, keys[i])) {186 return true5 unmodified lines192 return keys.length !== Object.keys(base).length193 }194 195 function hasArrayChanges(state) {185- const {proxy} = state186- if (proxy.length !== state.base.length) return true196+ const {draft} = state197+ if (draft.length !== state.base.length) return true198 // See #116199 // If we first shorten the length, our array interceptors will be removed.200 // If after that new items are added, result in the same original length,201 // those last items will have no intercepting property.202 // So if there is no own descriptor on the last position, we know that items were removed and added203 // N.B.: splice, unshift, etc only shift values around, but not prop descriptors, so we only have to check204 // the last one194- const descriptor = Object.getOwnPropertyDescriptor(proxy, proxy.length - 1)205+ const descriptor = Object.getOwnPropertyDescriptor(draft, draft.length - 1)206 // descriptor can be null, but only for newly created sparse arrays, eg. new Array(10)207 if (descriptor && !descriptor.get) return true208 // For all other cases, we don't have to compare, as they would have been picked up by the index setters209 return false210 }211 201-export function produceEs5(baseState, producer, patchListener) {202- const prevStates = states203- states = []204- const patches = patchListener && []205- const inversePatches = patchListener && []206- try {207- // create proxy for root208- const rootProxy = createProxy(undefined, baseState)209- // execute the thunk210- const returnValue = producer.call(rootProxy, rootProxy)211- // and finalize the modified proxy212- each(states, (_, state) => {213- state.finalizing = true214- })215- let result216- // check whether the draft was modified and/or a value was returned217- if (returnValue !== undefined && returnValue !== rootProxy) {218- // something was returned, and it wasn't the proxy itself219- if (rootProxy[PROXY_STATE].modified)220- throw new Error(RETURNED_AND_MODIFIED_ERROR)221- result = finalize(returnValue)222- if (patches) {223- patches.push({op: "replace", path: [], value: result})224- inversePatches.push({op: "replace", path: [], value: baseState})225- }226- } else {227- if (patchListener) markChangesRecursively(rootProxy)228- markChangesSweep() // this one is more efficient if we don't need to know which attributes have changed229- result = finalize(rootProxy, [], patches, inversePatches)230- }231- // make sure all proxies become unusable232- each(states, (_, state) => {233- state.finished = true234- })235- patchListener && patchListener(patches, inversePatches)236- return result237- } finally {238- states = prevStates239- }240-}241-212 function createHiddenProperty(target, prop, value) {213 Object.defineProperty(target, prop, {214 value: value,215 enumerable: false,3 unmodified linesdeleted:src/immer.d.ts-115 removed
1-/** Object types that should never be mapped */2-type AtomicObject =3- | Function4- | Map<any, any>5- | WeakMap<any, any>6- | Set<any>7- | WeakSet<any>8- | Promise<any>9- | Date10- | RegExp11- | Boolean12- | Number13- | String14-15-/** Use type inference to know when an array is finite */16-type IsFinite<T extends any[]> = T extends never[]17- ? true18- : T extends ReadonlyArray<infer U>19- ? (U[] extends T ? false : true)20- : true21-22-export type DraftObject<T> = T extends object23- ? T extends AtomicObject24- ? T25- : {-readonly [P in keyof T]: Draft<T[P]>}26- : T27-28-export type DraftArray<T> = Array<29- T extends ReadonlyArray<any>30- ? {[P in keyof T]: Draft<T>}[keyof T]31- : DraftObject<T>32->33-34-export type DraftTuple<T extends any[]> = {35- [P in keyof T]: T[P] extends T[number] ? Draft<T[P]> : never36-}37-38-export type Draft<T> = T extends any[]39- ? IsFinite<T> extends true40- ? DraftTuple<T>41- : DraftArray<T[number]>42- : T extends ReadonlyArray<any>43- ? DraftArray<T[number]>44- : T extends object45- ? DraftObject<T>46- : T47-48-export interface Patch {49- op: "replace" | "remove" | "add"50- path: (string | number)[]51- value?: any52-}53-54-export type PatchListener = (patches: Patch[], inversePatches: Patch[]) => void55-56-export interface IProduce {57- /**58- * Immer takes a state, and runs a function against it.59- * That function can freely mutate the state, as it will create copies-on-write.60- * This means that the original state will stay unchanged, and once the function finishes, the modified state is returned.61- *62- * If the first argument is a function, this is interpreted as the recipe, and will create a curried function that will execute the recipe63- * any time it is called with the current state.64- *65- * @param currentState - the state to start with66- * @param recipe - function that receives a proxy of the current state as first argument and which can be freely modified67- * @param initialState - if a curried function is created and this argument was given, it will be used as fallback if the curried function is called with a state of undefined68- * @returns The next state: a new state, or the current state if nothing was modified69- */70- <S = any, R = never>(71- currentState: S,72- recipe: (this: Draft<S>, draftState: Draft<S>) => void | R,73- listener?: PatchListener74- ): R75-76- /** Curried producer with an initial state */77- <S = any, R = never>(78- recipe: (this: Draft<S>, draftState: Draft<S>) => void | R,79- initialState: S80- ): (currentState: S | undefined) => R81-82- /** Curried producer with no initial state */83- <S = any, R = never, Args extends any[] = any[]>(84- recipe: (85- this: Draft<S>,86- draftState: Draft<S>,87- ...extraArgs: Args88- ) => void | R89- ): (currentState: S, ...extraArgs: Args) => R90-}91-92-export const produce: IProduce93-export default produce94-95-export const nothing: undefined96-97-/**98- * Automatically freezes any state trees generated by immer.99- * This protects against accidental modifications of the state tree outside of an immer function.100- * This comes with a performance impact, so it is recommended to disable this option in production.101- * It is by default enabled.102- */103-export function setAutoFreeze(autoFreeze: boolean): void104-105-/**106- * Manually override whether proxies should be used.107- * By default done by using feature detection108- */109-export function setUseProxies(useProxies: boolean): void110-111-export function applyPatches<S>(state: S, patches: Patch[]): S112-113-export function original<T>(value: T): T | void114-115-export function isDraft(value: any): booleanmodified:src/immer.js+156 added-65 removed
1-export {2- setAutoFreeze,3- setUseProxies,4- original,5- isProxy as isDraft1+import * as legacyProxy from "./es5"2+import * as modernProxy from "./proxy"3+import {generatePatches} from "./patches"4+import {5+ assign,6+ each,7+ has,8+ is,9+ isDraft,10+ isDraftable,11+ shallowCopy,12+ DRAFT_STATE,13+ NOTHING14 } from "./common"15 8-import {applyPatches as applyPatchesImpl} from "./patches"9-import {isProxy, isProxyable, getUseProxies, NOTHING} from "./common"10-import {produceProxy} from "./proxy"11-import {produceEs5} from "./es5"16+function verifyMinified() {}17 13-/**14- * produce takes a state, and runs a function against it.15- * That function can freely mutate the state, as it will create copies-on-write.16- * This means that the original state will stay unchanged, and once the function finishes, the modified state is returned17- *18- * @export19- * @param {any} baseState - the state to start with20- * @param {Function} producer - function that receives a proxy of the base state as first argument and which can be freely modified21- * @param {Function} patchListener - optional function that will be called with all the patches produced here22- * @returns {any} a new state, or the base state if nothing was modified23- */24-export function produce(baseState, producer, patchListener) {25- // prettier-ignore26- if (arguments.length < 1 || arguments.length > 3) throw new Error("produce expects 1 to 3 arguments, got " + arguments.length)18+const configDefaults = {19+ useProxies: typeof Proxy !== "undefined" && typeof Reflect !== "undefined",20+ autoFreeze:21+ typeof process !== "undefined"22+ ? process.env.NODE_ENV !== "production"23+ : verifyMinified.name === "verifyMinified"24+}25 28- // curried invocation29- if (typeof baseState === "function" && typeof producer !== "function") {30- const initialState = producer31- const recipe = baseState26+export class Immer {27+ constructor(config) {28+ assign(this, configDefaults, config)29+ this.setUseProxies(this.useProxies)30+ this.produce = this.produce.bind(this)31+ }32+ produce(base, recipe, patchListener) {33+ // curried invocation34+ if (typeof base === "function" && typeof recipe !== "function") {35+ const defaultBase = recipe36+ recipe = base37 33- return function(currentState = initialState, ...args) {34- return produce(currentState, draft =>35- recipe.call(draft, draft, ...args)36- )38+ // prettier-ignore39+ return (base = defaultBase, ...args) =>40+ this.produce(base, draft => recipe.call(draft, draft, ...args))41 }38- }42 40- // prettier-ignore41- {42- if (typeof producer !== "function") throw new Error("if first argument is not a function, the second argument to produce should be a function")43- if (patchListener !== undefined && typeof patchListener !== "function") throw new Error("the third argument of a producer should not be set or a function")44- }43+ // prettier-ignore44+ {45+ if (typeof recipe !== "function") throw new Error("if first argument is not a function, the second argument to produce should be a function")46+ if (patchListener !== undefined && typeof patchListener !== "function") throw new Error("the third argument of a producer should not be set or a function")47+ }48 46- // avoid proxying anything except plain objects and arrays47- if (!isProxyable(baseState)) {48- const returnValue = producer(baseState)49- return returnValue === undefined50- ? baseState51- : normalizeResult(returnValue)52- }49+ let result50+ // Only create proxies for plain objects/arrays.51+ if (!isDraftable(base)) {52+ result = recipe(base)53+ if (result === undefined) return base54+ }55+ // See #100, don't nest producers56+ else if (isDraft(base)) {57+ result = recipe.call(base, base)58+ if (result === undefined) return base59+ }60+ // The given value must be proxied.61+ else {62+ this.scopes.push([])63+ const baseDraft = this.createDraft(base)64+ try {65+ result = recipe.call(baseDraft, baseDraft)66+ this.willFinalize(result, baseDraft, !!patchListener)67 54- // See #100, don't nest producers55- if (isProxy(baseState)) {56- const returnValue = producer.call(baseState, baseState)57- return returnValue === undefined58- ? baseState59- : normalizeResult(returnValue)60- }68+ // Never generate patches when no listener exists.69+ var patches = patchListener && [],70+ inversePatches = patchListener && []71 62- return normalizeResult(63- getUseProxies()64- ? produceProxy(baseState, producer, patchListener)65- : produceEs5(baseState, producer, patchListener)66- )67-}72+ // Finalize the modified draft...73+ if (result === undefined || result === baseDraft) {74+ result = this.finalize(75+ baseDraft,76+ [],77+ patches,78+ inversePatches79+ )80+ }81+ // ...or use a replacement value.82+ else {83+ // Users must never modify the draft _and_ return something else.84+ if (baseDraft[DRAFT_STATE].modified)85+ throw new Error("An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.") // prettier-ignore86 69-function normalizeResult(result) {70- return result === NOTHING ? undefined : result71-}87+ // Finalize the replacement in case it contains (or is) a subset of the draft.88+ if (isDraftable(result)) result = this.finalize(result)89 73-export default produce74-75-export const applyPatches = produce(applyPatchesImpl)76-77-export const nothing = NOTHING90+ if (patchListener) {91+ patches.push({92+ op: "replace",93+ path: [],94+ value: result95+ })96+ inversePatches.push({97+ op: "replace",98+ path: [],99+ value: base100+ })101+ }102+ }103+ } finally {104+ this.currentScope().forEach(state => state.revoke())105+ this.scopes.pop()106+ }107+ patchListener && patchListener(patches, inversePatches)108+ }109+ // Normalize the result.110+ return result === NOTHING ? undefined : result111+ }112+ setAutoFreeze(value) {113+ this.autoFreeze = value114+ }115+ setUseProxies(value) {116+ this.useProxies = value117+ assign(this, value ? modernProxy : legacyProxy)118+ }119+ /**120+ * @internal121+ * Finalize a draft, returning either the unmodified base state or a modified122+ * copy of the base state.123+ */124+ finalize(draft, path, patches, inversePatches) {125+ const state = draft[DRAFT_STATE]126+ if (!state) {127+ if (Object.isFrozen(draft)) return draft128+ return this.finalizeTree(draft)129+ }130+ if (!state.modified) return state.base131+ if (!state.finalized) {132+ state.finalized = true133+ this.finalizeTree(state.draft, path, patches, inversePatches)134+ if (this.autoFreeze) Object.freeze(state.copy)135+ if (patches) generatePatches(state, path, patches, inversePatches)136+ }137+ return state.copy138+ }139+ /**140+ * @internal141+ * Finalize all drafts in the given state tree.142+ */143+ finalizeTree(root, path, patches, inversePatches) {144+ const state = root[DRAFT_STATE]145+ if (state) {146+ root = this.useProxies147+ ? state.copy148+ : (state.copy = shallowCopy(state.draft))149+ }150+ const finalizeProperty = (prop, value, parent) => {151+ // Skip unchanged properties in draft objects.152+ if (state && parent === root && is(value, state.base[prop])) return153+ if (!isDraftable(value)) return154+ if (!isDraft(value)) {155+ // Frozen values are already finalized.156+ return Object.isFrozen(value) || each(value, finalizeProperty)157+ }158+ // prettier-ignore159+ parent[prop] =160+ // Patches are never generated for assigned properties.161+ patches && parent === root && !(state && has(state.assigned, prop))162+ ? this.finalize(value, path.concat(prop), patches, inversePatches)163+ : this.finalize(value)164+ }165+ each(root, finalizeProperty)166+ return root167+ }168+}deleted:src/immer.js.flow-92 removed
1-// @flow2-3-export interface Patch {4- op: "replace" | "remove" | "add",5- path: (string|number)[],6- value?: any7-}8-9-export type PatchListener = (patches: Patch[], inversePatches: Patch[]) => void10-11-interface IProduce {12- /**13- * Immer takes a state, and runs a function against it.14- * That function can freely mutate the state, as it will create copies-on-write.15- * This means that the original state will stay unchanged, and once the function finishes, the modified state is returned.16- *17- * If the first argument is a function, this is interpreted as the recipe, and will create a curried function that will execute the recipe18- * any time it is called with the current state.19- *20- * @param currentState - the state to start with21- * @param recipe - function that receives a proxy of the current state as first argument and which can be freely modified22- * @param initialState - if a curried function is created and this argument was given, it will be used as fallback if the curried function is called with a state of undefined23- * @returns The next state: a new state, or the current state if nothing was modified24- */25- <S>(26- currentState: S,27- recipe: (draftState: S) => S | void,28- patchListener?: PatchListener29- ): S;30- // curried invocations with inital state31- <S, A, B, C>(32- recipe: (draftState: S, a: A, b: B, c: C) => S | void,33- initialState: S34- ): (currentState: S | void, a: A, b: B, c: C) => S;35- <S, A, B>(36- recipe: (draftState: S, a: A, b: B) => S | void,37- initialState: S38- ): (currentState: S | void, a: A, b: B) => S;39- <S, A>(40- recipe: (draftState: S, a: A) => S | void,41- initialState: S42- ): (currentState: S | void, a: A) => S;43- <S>(44- recipe: (draftState: S) => S | void,45- initialState: S46- ): (currentState: S | void) => S;47- <S>(48- recipe: (draftState: S, ...extraArgs: any[]) => S | void,49- initialState: S50- ): (currentState: S | void, ...extraArgs: any[]) => S;51- // curried invocations without inital state52- <S, A, B, C>(53- recipe: (draftState: S, a: A, b: B, c: C) => S | void54- ): (currentState: S, a: A, b: B, c: C) => S;55- <S, A, B>(56- recipe: (draftState: S, a: A, b: B) => S | void57- ): (currentState: S, a: A, b: B) => S;58- <S, A>(59- recipe: (draftState: S, a: A) => S | void60- ): (currentState: S, a: A) => S;61- <S>(62- recipe: (draftState: S) => S | void63- ): (currentState: S) => S;64- <S>(65- recipe: (draftState: S, ...extraArgs: any[]) => S | void66- ): (currentState: S, ...extraArgs: any[]) => S;67-}68-69-declare export var produce: IProduce70-declare export default IProduce71-72-declare export var nothing: typeof undefined73-74-/**75- * Automatically freezes any state trees generated by immer.76- * This protects against accidental modifications of the state tree outside of an immer function.77- * This comes with a performance impact, so it is recommended to disable this option in production.78- * By default it is turned on during local development, and turned off in production.79- */80-declare export function setAutoFreeze(autoFreeze: boolean): void81-82-/**83- * Manually override whether proxies should be used.84- * By default done by using feature detection85- */86-declare export function setUseProxies(useProxies: boolean): void87-88-declare export function applyPatches<S>(state: S, patches: Patch[]): S89-90-declare export function original<S>(value: S): ?S91-92-declare export function isDraft(value: any): booleanadded:src/index.d.ts+115 added
1+/** Object types that should never be mapped */2+type AtomicObject =3+ | Function4+ | Map<any, any>5+ | WeakMap<any, any>6+ | Set<any>7+ | WeakSet<any>8+ | Promise<any>9+ | Date10+ | RegExp11+ | Boolean12+ | Number13+ | String14+15+/** Use type inference to know when an array is finite */16+type IsFinite<T extends any[]> = T extends never[]17+ ? true18+ : T extends ReadonlyArray<infer U>19+ ? (U[] extends T ? false : true)20+ : true21+22+export type DraftObject<T> = T extends object23+ ? T extends AtomicObject24+ ? T25+ : {-readonly [P in keyof T]: Draft<T[P]>}26+ : T27+28+export type DraftArray<T> = Array<29+ T extends ReadonlyArray<any>30+ ? {[P in keyof T]: Draft<T>}[keyof T]31+ : DraftObject<T>32+>33+34+export type DraftTuple<T extends any[]> = {35+ [P in keyof T]: T[P] extends T[number] ? Draft<T[P]> : never36+}37+38+export type Draft<T> = T extends any[]39+ ? IsFinite<T> extends true40+ ? DraftTuple<T>41+ : DraftArray<T[number]>42+ : T extends ReadonlyArray<any>43+ ? DraftArray<T[number]>44+ : T extends object45+ ? DraftObject<T>46+ : T47+48+export interface Patch {49+ op: "replace" | "remove" | "add"50+ path: (string | number)[]51+ value?: any52+}53+54+export type PatchListener = (patches: Patch[], inversePatches: Patch[]) => void55+56+export interface IProduce {57+ /**58+ * Immer takes a state, and runs a function against it.59+ * That function can freely mutate the state, as it will create copies-on-write.60+ * This means that the original state will stay unchanged, and once the function finishes, the modified state is returned.61+ *62+ * If the first argument is a function, this is interpreted as the recipe, and will create a curried function that will execute the recipe63+ * any time it is called with the current state.64+ *65+ * @param currentState - the state to start with66+ * @param recipe - function that receives a proxy of the current state as first argument and which can be freely modified67+ * @param initialState - if a curried function is created and this argument was given, it will be used as fallback if the curried function is called with a state of undefined68+ * @returns The next state: a new state, or the current state if nothing was modified69+ */70+ <S = any, R = never>(71+ currentState: S,72+ recipe: (this: Draft<S>, draftState: Draft<S>) => void | R,73+ listener?: PatchListener74+ ): R75+76+ /** Curried producer with an initial state */77+ <S = any, R = never>(78+ recipe: (this: Draft<S>, draftState: Draft<S>) => void | R,79+ initialState: S80+ ): (currentState: S | undefined) => R81+82+ /** Curried producer with no initial state */83+ <S = any, R = never, Args extends any[] = any[]>(84+ recipe: (85+ this: Draft<S>,86+ draftState: Draft<S>,87+ ...extraArgs: Args88+ ) => void | R89+ ): (currentState: S, ...extraArgs: Args) => R90+}91+92+export const produce: IProduce93+export default produce94+95+export const nothing: undefined96+97+/**98+ * Automatically freezes any state trees generated by immer.99+ * This protects against accidental modifications of the state tree outside of an immer function.100+ * This comes with a performance impact, so it is recommended to disable this option in production.101+ * It is by default enabled.102+ */103+export function setAutoFreeze(autoFreeze: boolean): void104+105+/**106+ * Manually override whether proxies should be used.107+ * By default done by using feature detection108+ */109+export function setUseProxies(useProxies: boolean): void110+111+export function applyPatches<S>(state: S, patches: Patch[]): S112+113+export function original<T>(value: T): T | void114+115+export function isDraft(value: any): booleanadded:src/index.js+52 added
1+import {applyPatches as applyPatchesImpl} from "./patches"2+import {Immer} from "./immer"3+4+const immer = new Immer()5+6+/**7+ * The `produce` function takes a value and a "recipe function" (whose8+ * return value often depends on the base state). The recipe function is9+ * free to mutate its first argument however it wants. All mutations are10+ * only ever applied to a __copy__ of the base state.11+ *12+ * Pass only a function to create a "curried producer" which relieves you13+ * from passing the recipe function every time.14+ *15+ * Only plain objects and arrays are made mutable. All other objects are16+ * considered uncopyable.17+ *18+ * Note: This function is __bound__ to its `Immer` instance.19+ *20+ * @param {any} base - the initial state21+ * @param {Function} producer - function that receives a proxy of the base state as first argument and which can be freely modified22+ * @param {Function} patchListener - optional function that will be called with all the patches produced here23+ * @returns {any} a new state, or the initial state if nothing was modified24+ */25+export const produce = immer.produce26+export default produce27+28+/**29+ * Pass true to automatically freeze all copies created by Immer.30+ *31+ * By default, auto-freezing is disabled in production.32+ */33+export const setAutoFreeze = value => immer.setAutoFreeze(value)34+35+/**36+ * Pass true to use the ES2015 `Proxy` class when creating drafts, which is37+ * always faster than using ES5 proxies.38+ *39+ * By default, feature detection is used, so calling this is rarely necessary.40+ */41+export const setUseProxies = value => immer.setUseProxies(value)42+43+/**44+ * Apply an array of Immer patches to the first argument.45+ *46+ * This function is a producer, which means copy-on-write is in effect.47+ */48+export const applyPatches = produce(applyPatchesImpl)49+50+export {original, isDraft, NOTHING as nothing} from "./common"51+52+export {Immer}added:src/index.js.flow+92 added
1+// @flow2+3+export interface Patch {4+ op: "replace" | "remove" | "add",5+ path: (string|number)[],6+ value?: any7+}8+9+export type PatchListener = (patches: Patch[], inversePatches: Patch[]) => void10+11+interface IProduce {12+ /**13+ * Immer takes a state, and runs a function against it.14+ * That function can freely mutate the state, as it will create copies-on-write.15+ * This means that the original state will stay unchanged, and once the function finishes, the modified state is returned.16+ *17+ * If the first argument is a function, this is interpreted as the recipe, and will create a curried function that will execute the recipe18+ * any time it is called with the current state.19+ *20+ * @param currentState - the state to start with21+ * @param recipe - function that receives a proxy of the current state as first argument and which can be freely modified22+ * @param initialState - if a curried function is created and this argument was given, it will be used as fallback if the curried function is called with a state of undefined23+ * @returns The next state: a new state, or the current state if nothing was modified24+ */25+ <S>(26+ currentState: S,27+ recipe: (draftState: S) => S | void,28+ patchListener?: PatchListener29+ ): S;30+ // curried invocations with inital state31+ <S, A, B, C>(32+ recipe: (draftState: S, a: A, b: B, c: C) => S | void,33+ initialState: S34+ ): (currentState: S | void, a: A, b: B, c: C) => S;35+ <S, A, B>(36+ recipe: (draftState: S, a: A, b: B) => S | void,37+ initialState: S38+ ): (currentState: S | void, a: A, b: B) => S;39+ <S, A>(40+ recipe: (draftState: S, a: A) => S | void,41+ initialState: S42+ ): (currentState: S | void, a: A) => S;43+ <S>(44+ recipe: (draftState: S) => S | void,45+ initialState: S46+ ): (currentState: S | void) => S;47+ <S>(48+ recipe: (draftState: S, ...extraArgs: any[]) => S | void,49+ initialState: S50+ ): (currentState: S | void, ...extraArgs: any[]) => S;51+ // curried invocations without inital state52+ <S, A, B, C>(53+ recipe: (draftState: S, a: A, b: B, c: C) => S | void54+ ): (currentState: S, a: A, b: B, c: C) => S;55+ <S, A, B>(56+ recipe: (draftState: S, a: A, b: B) => S | void57+ ): (currentState: S, a: A, b: B) => S;58+ <S, A>(59+ recipe: (draftState: S, a: A) => S | void60+ ): (currentState: S, a: A) => S;61+ <S>(62+ recipe: (draftState: S) => S | void63+ ): (currentState: S) => S;64+ <S>(65+ recipe: (draftState: S, ...extraArgs: any[]) => S | void66+ ): (currentState: S, ...extraArgs: any[]) => S;67+}68+69+declare export var produce: IProduce70+declare export default IProduce71+72+declare export var nothing: typeof undefined73+74+/**75+ * Automatically freezes any state trees generated by immer.76+ * This protects against accidental modifications of the state tree outside of an immer function.77+ * This comes with a performance impact, so it is recommended to disable this option in production.78+ * By default it is turned on during local development, and turned off in production.79+ */80+declare export function setAutoFreeze(autoFreeze: boolean): void81+82+/**83+ * Manually override whether proxies should be used.84+ * By default done by using feature detection85+ */86+declare export function setUseProxies(useProxies: boolean): void87+88+declare export function applyPatches<S>(state: S, patches: Patch[]): S89+90+declare export function original<S>(value: S): ?S91+92+declare export function isDraft(value: any): booleanmodified:src/patches.js+53 added-86 removed
1 import {each} from "./common"2 3-export function generatePatches(4- state,5- basepath,6- patches,7- inversePatches,8- baseValue,9- resultValue10-) {11- if (patches)12- if (Array.isArray(baseValue))13- generateArrayPatches(14- state,15- basepath,16- patches,17- inversePatches,18- baseValue,19- resultValue20- )21- else22- generateObjectPatches(23- state,24- basepath,25- patches,26- inversePatches,27- baseValue,28- resultValue29- )3+export function generatePatches(state, basePath, patches, inversePatches) {4+ Array.isArray(state.base)5+ ? generateArrayPatches(state, basePath, patches, inversePatches)6+ : generateObjectPatches(state, basePath, patches, inversePatches)7 }8 32-export function generateArrayPatches(33- state,34- basepath,35- patches,36- inversePatches,37- baseValue,38- resultValue39-) {40- const shared = Math.min(baseValue.length, resultValue.length)41- for (let i = 0; i < shared; i++) {42- if (state.assigned[i] && baseValue[i] !== resultValue[i]) {43- const path = basepath.concat(i)44- patches.push({op: "replace", path, value: resultValue[i]})45- inversePatches.push({op: "replace", path, value: baseValue[i]})9+export function generateArrayPatches(state, basePath, patches, inversePatches) {10+ const {base, copy, assigned} = state11+ const minLength = Math.min(base.length, copy.length)12+13+ // Look for replaced indices.14+ for (let i = 0; i < minLength; i++) {15+ if (assigned[i] && base[i] !== copy[i]) {16+ const path = basePath.concat(i)17+ patches.push({op: "replace", path, value: copy[i]})18+ inversePatches.push({op: "replace", path, value: base[i]})19 }20 }48- if (shared < resultValue.length) {49- // stuff was added50- for (let i = shared; i < resultValue.length; i++) {51- const path = basepath.concat(i)52- patches.push({op: "add", path, value: resultValue[i]})21+22+ // Did the array expand?23+ if (minLength < copy.length) {24+ for (let i = minLength; i < copy.length; i++) {25+ patches.push({26+ op: "add",27+ path: basePath.concat(i),28+ value: copy[i]29+ })30 }31 inversePatches.push({32 op: "replace",56- path: basepath.concat("length"),57- value: baseValue.length33+ path: basePath.concat("length"),34+ value: base.length35 })59- } else if (shared < baseValue.length) {60- // stuff was removed36+ }37+38+ // ...or did it shrink?39+ else if (minLength < base.length) {40 patches.push({41 op: "replace",63- path: basepath.concat("length"),64- value: resultValue.length42+ path: basePath.concat("length"),43+ value: copy.length44 })66- for (let i = shared; i < baseValue.length; i++) {67- const path = basepath.concat(i)68- inversePatches.push({op: "add", path, value: baseValue[i]})45+ for (let i = minLength; i < base.length; i++) {46+ inversePatches.push({47+ op: "add",48+ path: basePath.concat(i),49+ value: base[i]50+ })51 }52 }53 }54 73-function generateObjectPatches(74- state,75- basepath,76- patches,77- inversePatches,78- baseValue,79- resultValue80-) {55+function generateObjectPatches(state, basePath, patches, inversePatches) {56+ const {base, copy} = state57 each(state.assigned, (key, assignedValue) => {82- const origValue = baseValue[key]83- const value = resultValue[key]84- const op = !assignedValue85- ? "remove"86- : key in baseValue87- ? "replace"88- : "add"89- if (origValue === baseValue && op === "replace") return90- const path = basepath.concat(key)58+ const origValue = base[key]59+ const value = copy[key]60+ const op = !assignedValue ? "remove" : key in base ? "replace" : "add"61+ if (origValue === base && op === "replace") return62+ const path = basePath.concat(key)63 patches.push(op === "remove" ? {op, path} : {op, path, value})64 inversePatches.push(65 op === "add"66 ? {op: "remove", path}67 : op === "remove"96- ? {op: "add", path, value: origValue}97- : {op: "replace", path, value: origValue}68+ ? {op: "add", path, value: origValue}69+ : {op: "replace", path, value: origValue}70 )71 })72 }73 7 unmodified lines81 let base = draft82 for (let i = 0; i < path.length - 1; i++) {83 base = base[path[i]]84 if (!base || typeof base !== "object")113- throw new Error(114- "Cannot apply patch, path doesn't resolve: " +115- path.join("/")116- )85+ throw new Error("Cannot apply patch, path doesn't resolve: " + path.join("/")) // prettier-ignore86 }87 const key = path[path.length - 1]88 switch (patch.op) {89 case "replace":2 unmodified lines92 base[key] = patch.value93 break94 case "remove":95 if (Array.isArray(base)) {127- if (key === base.length - 1) base.length -= 1128- else129- throw new Error(130- `Remove can only remove the last key of an array, index: ${key}, length: ${131- base.length132- }`133- )134- } else delete base[key]96+ if (key !== base.length - 1)97+ throw new Error(`Only the last index of an array can be removed, index: ${key}, length: ${base.length}`) // prettier-ignore98+ base.length -= 199+ } else {100+ delete base[key]101+ }102 break103 default:104 throw new Error("Unsupported patch operation: " + patch.op)105 }4 unmodified linesmodified:src/proxy.js+47 added-77 removed
4 unmodified lines5 assign,6 each,7 has,8 is,9- isProxyable,10- isProxy,11- finalize,9+ isDraftable,10+ isDraft,11 shallowCopy,13- PROXY_STATE,14- RETURNED_AND_MODIFIED_ERROR12+ DRAFT_STATE13 } from "./common"14 17-let proxies = null15+// For nested produce calls:16+export const scopes = []17+export const currentScope = () => scopes[scopes.length - 1]18 19+// Do nothing before being finalized.20+export function willFinalize() {}21+22+export function createDraft(base, parent) {23+ if (isDraft(base)) throw new Error("This should never happen. Please report: https://github.com/mweststrate/immer/issues/new") // prettier-ignore24+25+ const state = {26+ modified: false, // this tree is modified (either this object or one of it's children)27+ assigned: {}, // true: value was assigned to these props, false: was removed28+ parent,29+ base,30+ draft: null, // the root proxy31+ drafts: {}, // proxied properties32+ copy: null,33+ revoke: null,34+ finalized: false35+ }36+37+ const {revoke, proxy} = Array.isArray(base)38+ ? Proxy.revocable([state], arrayTraps)39+ : Proxy.revocable(state, objectTraps)40+41+ state.draft = proxy42+ state.revoke = revoke43+44+ currentScope().push(state)45+ return proxy46+}47+48 const objectTraps = {49 get,50 has(target, prop) {51 return prop in source(target)32 unmodified lines84 )85 return objectTraps.set.call(this, state[0], prop, value)86 }87 59-function createState(parent, base) {60- return {61- modified: false, // this tree is modified (either this object or one of it's children)62- assigned: {}, // true: value was assigned to these props, false: was removed63- finalized: false,64- parent,65- base,66- copy: undefined,67- proxies: {}68- }69-}70-88 function source(state) {89 return state.modified === true ? state.copy : state.base90 }91 92 function get(state, prop) {76- if (prop === PROXY_STATE) return state93+ if (prop === DRAFT_STATE) return state94 if (state.modified) {95 const value = state.copy[prop]79- if (value === state.base[prop] && isProxyable(value))96+ if (value === state.base[prop] && isDraftable(value))97 // only create proxy if it is not yet a proxy, and not a new object98 // (new objects don't need proxying, they will be processed in finalize anyway)82- return (state.copy[prop] = createProxy(state, value))99+ return (state.copy[prop] = createDraft(value, state))100 return value101 } else {85- if (has(state.proxies, prop)) return state.proxies[prop]102+ if (has(state.drafts, prop)) return state.drafts[prop]103 const value = state.base[prop]87- if (!isProxy(value) && isProxyable(value))88- return (state.proxies[prop] = createProxy(state, value))104+ if (!isDraft(value) && isDraftable(value))105+ return (state.drafts[prop] = createDraft(value, state))106 return value107 }108 }109 110 function set(state, prop, value) {111 if (!state.modified) {112 // Optimize based on value's truthiness. Truthy values are guaranteed to113 // never be undefined, so we can avoid the `in` operator. Lastly, truthy97- // values may be proxies, but falsy values are never proxies.114+ // values may be drafts, but falsy values are never drafts.115 const isUnchanged = value99- ? is(state.base[prop], value) || value === state.proxies[prop]116+ ? is(state.base[prop], value) || value === state.drafts[prop]117 : is(state.base[prop], value) && prop in state.base118 if (isUnchanged) return true119 markChanged(state)120 }14 unmodified lines135 136 function getOwnPropertyDescriptor(state, prop) {137 const owner = state.modified138 ? state.copy122- : has(state.proxies, prop)123- ? state.proxies139+ : has(state.drafts, prop)140+ ? state.drafts141 : state.base142 const descriptor = Reflect.getOwnPropertyDescriptor(owner, prop)143 if (descriptor && !(Array.isArray(owner) && prop === "length"))144 descriptor.configurable = true9 unmodified lines154 function markChanged(state) {155 if (!state.modified) {156 state.modified = true157 state.copy = shallowCopy(state.base)141- // copy the proxies over the base-copy142- assign(state.copy, state.proxies) // yup that works for arrays as well158+ // copy the drafts over the base-copy159+ assign(state.copy, state.drafts) // yup that works for arrays as well160 if (state.parent) markChanged(state.parent)161 }162 }146-147-// creates a proxy for plain objects / arrays148-function createProxy(parentState, base) {149- if (isProxy(base)) throw new Error("Immer bug. Plz report.")150- const state = createState(parentState, base)151- const proxy = Array.isArray(base)152- ? Proxy.revocable([state], arrayTraps)153- : Proxy.revocable(state, objectTraps)154- proxies.push(proxy)155- return proxy.proxy156-}157-158-export function produceProxy(baseState, producer, patchListener) {159- const previousProxies = proxies160- proxies = []161- const patches = patchListener && []162- const inversePatches = patchListener && []163- try {164- // create proxy for root165- const rootProxy = createProxy(undefined, baseState)166- // execute the producer function167- const returnValue = producer.call(rootProxy, rootProxy)168- // and finalize the modified proxy169- let result170- // check whether the draft was modified and/or a value was returned171- if (returnValue !== undefined && returnValue !== rootProxy) {172- // something was returned, and it wasn't the proxy itself173- if (rootProxy[PROXY_STATE].modified)174- throw new Error(RETURNED_AND_MODIFIED_ERROR)175-176- // we need to finalize the return value in case it's a subset of the draft177- result = finalize(returnValue)178- if (patches) {179- patches.push({op: "replace", path: [], value: result})180- inversePatches.push({op: "replace", path: [], value: baseState})181- }182- } else {183- result = finalize(rootProxy, [], patches, inversePatches)184- }185- // revoke all proxies186- each(proxies, (_, p) => p.revoke())187- patchListener && patchListener(patches, inversePatches)188- return result189- } finally {190- proxies = previousProxies191- }192-}modified:rollup.config.js+1 added-1 removed
5 unmodified lines6 import babel from "rollup-plugin-babel"7 8 function getConfig(dest, format, ugly) {9 const conf = {10- input: "src/immer.js",10+ input: "src/index.js",11 output: {12 exports: "named",13 file: dest,14 format,55 unmodified lines