Skip to content
Myr

immer.js

This file

Path

src/immer.js

292 lines · 9.1 KiB · JavaScript

Last changed by

extracted class methods from Proxy implMichel Weststratebefore adoptiond20adea

History of this file

Take it

transpile es5 codeMichel Weststratebefore adoptionf012154

lines 1–8why, one step back
1"use strict"
2// @ts-check34if (typeof Proxy === "undefined")5 throw new Error(6 "Immer requires `Proxy` to be available, but it seems to be not available on your platform. Consider requiring immer '\"immer/es5\"' instead."7 )8

Making several improvements at onceMichel Weststratebefore adoption1116ccf

line 9why, one step back
9const PROXY_STATE = Symbol("immer-proxy-state")

transpile es5 codeMichel Weststratebefore adoptionf012154

line 10why, one step back
10let autoFreeze = true

extracted class methods from Proxy implMichel Weststratebefore adoptiond20adea

line 11why, one step back
11let revocableProxies = null

transpile es5 codeMichel Weststratebefore adoptionf012154

lines 12–15why, one step back
12
13const objectTraps = {14 get(target, prop) {15 if (prop === PROXY_STATE) return target

extracted class methods from Proxy implMichel Weststratebefore adoptiond20adea

line 16why, one step back
16 return get(target, prop)

transpile es5 codeMichel Weststratebefore adoptionf012154

lines 17–18why, one step back
17 },
18 has(target, prop) {

extracted class methods from Proxy implMichel Weststratebefore adoptiond20adea

line 19why, one step back
19 return prop in source(target)

transpile es5 codeMichel Weststratebefore adoptionf012154

lines 20–21why, one step back
20 },
21 ownKeys(target) {

extracted class methods from Proxy implMichel Weststratebefore adoptiond20adea

line 22why, one step back
22 return Reflect.ownKeys(source(target))

transpile es5 codeMichel Weststratebefore adoptionf012154

lines 23–24why, one step back
23 },
24 set(target, prop, value) {

extracted class methods from Proxy implMichel Weststratebefore adoptiond20adea

line 25why, one step back
25 set(target, prop, value) // TODO: eliminate these closures

transpile es5 codeMichel Weststratebefore adoptionf012154

lines 26–28why, one step back
26 return true
27 },28 deleteProperty(target, prop) {

extracted class methods from Proxy implMichel Weststratebefore adoptiond20adea

line 29why, one step back
29 deleteProp(target, prop) // TODO: eliminate these closures

transpile es5 codeMichel Weststratebefore adoptionf012154

lines 30–32why, one step back
30 return true
31 },32 getOwnPropertyDescriptor(target, prop) {

extracted class methods from Proxy implMichel Weststratebefore adoptiond20adea

line 33why, one step back
33 return getOwnPropertyDescriptor(target, prop)

transpile es5 codeMichel Weststratebefore adoptionf012154

lines 34–35why, one step back
34 },
35 defineProperty(target, property, descriptor) {

extracted class methods from Proxy implMichel Weststratebefore adoptiond20adea

line 36why, one step back
36 defineProperty(target, property, descriptor)

transpile es5 codeMichel Weststratebefore adoptionf012154

lines 37–45why, one step back
37 },
38 setPrototypeOf() {39 throw new Error("Don't even try this...")40 }41}4243const arrayTraps = {44 get(target, prop) {45 if (prop === PROXY_STATE) return target[0]

extracted class methods from Proxy implMichel Weststratebefore adoptiond20adea

line 46why, one step back
46 return get(target[0], prop)

transpile es5 codeMichel Weststratebefore adoptionf012154

lines 47–48why, one step back
47 },
48 has(target, prop) {

extracted class methods from Proxy implMichel Weststratebefore adoptiond20adea

line 49why, one step back
49 return prop === PROXY_STATE || prop in source(target[0])

transpile es5 codeMichel Weststratebefore adoptionf012154

lines 50–51why, one step back
50 },
51 ownKeys(target) {

extracted class methods from Proxy implMichel Weststratebefore adoptiond20adea

line 52why, one step back
52 return Reflect.ownKeys(source(target[0]))

transpile es5 codeMichel Weststratebefore adoptionf012154

lines 53–54why, one step back
53 },
54 set(target, prop, value) {

extracted class methods from Proxy implMichel Weststratebefore adoptiond20adea

line 55why, one step back
55 set(target[0], prop, value)

transpile es5 codeMichel Weststratebefore adoptionf012154

lines 56–58why, one step back
56 return true
57 },58 deleteProperty(target, prop) {

extracted class methods from Proxy implMichel Weststratebefore adoptiond20adea

line 59why, one step back
59 deleteProp(target[0], prop)

transpile es5 codeMichel Weststratebefore adoptionf012154

lines 60–62why, one step back
60 return true
61 },62 getOwnPropertyDescriptor(target, prop) {

extracted class methods from Proxy implMichel Weststratebefore adoptiond20adea

line 63why, one step back
63 return getOwnPropertyDescriptor(target[0], prop)

transpile es5 codeMichel Weststratebefore adoptionf012154

lines 64–65why, one step back
64 },
65 defineProperty(target, property, descriptor) {

extracted class methods from Proxy implMichel Weststratebefore adoptiond20adea

line 66why, one step back
66 defineProperty(target[0], property, descriptor)

transpile es5 codeMichel Weststratebefore adoptionf012154

lines 67–72why, one step back
67 },
68 setPrototypeOf() {69 throw new Error("Don't even try this...")70 }71}72

extracted class methods from Proxy implMichel Weststratebefore adoptiond20adea

lines 73–204why, one step back
73class State {
74 constructor(parent, base) {75 this.modified = false76 this.finalized = false77 this.parent = parent78 this.base = base79 this.copy = undefined80 this.proxies = {}81 }82}8384function source(state) {85 return state.modified === true ? state.copy : state.base86}8788function get(state, prop) {89 if (state.modified) {90 const value = state.copy[prop]91 if (!isProxy(value) && isProxyable(value))92 return (state.copy[prop] = createProxy(state, value))93 return value94 } else {95 if (prop in state.proxies) return state.proxies[prop]96 const value = state.base[prop]97 if (!isProxy(value) && isProxyable(value))98 return (state.proxies[prop] = createProxy(state, value))99 return value100 }101}102103function set(state, prop, value) {104 if (!state.modified) {105 if (106 (prop in state.base && Object.is(state.base[prop], value)) ||107 (prop in state.proxies && state.proxies[prop] === value)108 )109 return110 markChanged(state)111 }112 state.copy[prop] = value113}114115function deleteProp(state, prop) {116 markChanged(state)117 delete state.copy[prop]118}119120function getOwnPropertyDescriptor(state, prop) {121 const owner = state.modified122 ? state.copy123 : prop in state.proxies ? state.proxies : state.base124 const descriptor = Reflect.getOwnPropertyDescriptor(owner, prop)125 if (descriptor && !(Array.isArray(owner) && prop === "length"))126 descriptor.configurable = true127 return descriptor128}129130function defineProperty() {131 throw new Error(132 "Immer does currently not support defining properties on draft objects"133 )134}135136function markChanged(state) {137 if (!state.modified) {138 state.modified = true139 state.copy = Array.isArray(state.base)140 ? state.base.slice()141 : Object.assign({}, state.base) // TODO: eliminate those isArray checks?142 Object.assign(state.copy, state.proxies) // yup that works for arrays as well143 if (state.parent) markChanged(state.parent)144 }145}146147// creates a proxy for plain objects / arrays148function createProxy(parentState, base) {149 const state = new State(parentState, base)150 let proxy151 if (Array.isArray(base)) {152 proxy = Proxy.revocable([state], arrayTraps)153 } else {154 proxy = Proxy.revocable(state, objectTraps)155 }156 revocableProxies.push(proxy)157 return proxy.proxy158}159160// given a base object, returns it if unmodified, or return the changed cloned if modified161function finalize(base) {162 if (isProxy(base)) {163 const state = base[PROXY_STATE]164 if (state.modified === true) {165 if (state.finalized === true) return state.copy166 state.finalized = true167 if (Array.isArray(state.base)) return finalizeArray(state)168 return finalizeObject(state)169 } else return state.base170 } else if (base !== null && typeof base === "object") {171 // 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 original172 // tree and it could contain proxies at arbitrarily places. Let's find and finalize them as well173 // TODO: optimize this; walk the tree without writing to find proxies174 if (Array.isArray(base)) {175 for (let i = 0; i < base.length; i++) base[i] = finalize(base[i])176 return freeze(base)177 }178 const proto = Object.getPrototypeOf(base)179 if (proto === null || proto === Object.prototype) {180 for (let key in base) base[key] = finalize(base[key])181 return freeze(base)182 }183 }184 return base185}186187function finalizeObject(state) {188 const copy = state.copy189 const base = state.base190 for (var prop in copy) {191 if (copy[prop] !== base[prop]) copy[prop] = finalize(copy[prop])192 }193 return freeze(copy)194}195196function finalizeArray(state) {197 const copy = state.copy198 const base = state.base199 for (let i = 0; i < copy.length; i++) {200 if (copy[i] !== base[i]) copy[i] = finalize(copy[i])201 }202 return freeze(copy)203}204

transpile es5 codeMichel Weststratebefore adoptionf012154

lines 205–214why, one step back
205/**
206 * produce takes a state, and runs a function against it.207 * That function can freely mutate the state, as it will create copies-on-write.208 * This means that the original state will stay unchanged, and once the function finishes, the modified state is returned209 *210 * @export211 * @param {any} baseState - the state to start with212 * @param {Function} producer - function that receives a proxy of the base state as first argument and which can be freely modified213 * @returns {any} a new state, or the base state if nothing was modified214 */

Default build includes both Proxy and ES5 implementationMichel Weststratebefore adoptionbd9c47b

line 215why, one step back
215export default function produce(baseState, producer) {

transpile es5 codeMichel Weststratebefore adoptionf012154

lines 216–236why, one step back
216 // curried invocation
217 if (arguments.length === 1) {218 const producer = baseState219 // prettier-ignore220 if (typeof producer !== "function") throw new Error("if produce is called with 1 argument, the first argument should be a function")221 return function() {222 const args = arguments223 return produce(args[0], draft => {224 args[0] = draft // blegh!225 baseState.apply(null, args)226 })227 }228 }229230 // prettier-ignore231 {232 if (arguments.length !== 2) throw new Error("produce expects 1 or 2 arguments, got " + arguments.length)233 if (!isProxyable(baseState)) throw new Error("the first argument to produce should be a plain object or array, got " + (typeof baseState))234 if (typeof producer !== "function") throw new Error("the second argument to produce should be a function")235 }236

extracted class methods from Proxy implMichel Weststratebefore adoptiond20adea

lines 237–247why, one step back
237 const previousProxies = revocableProxies
238 revocableProxies = []239 try {240 // create proxy for root241 const rootClone = createProxy(undefined, baseState)242 // execute the thunk243 const maybeVoidReturn = producer(rootClone)244 //values either than undefined will trigger warning;245 !Object.is(maybeVoidReturn, undefined) &&246 console.warn(247 `Immer callback expects no return value. However ${typeof maybeVoidReturn} was returned`

transpile es5 codeMichel Weststratebefore adoptionf012154

line 248why, one step back
248 )

extracted class methods from Proxy implMichel Weststratebefore adoptiond20adea

lines 249–255why, one step back
249 // and finalize the modified proxy
250 const res = finalize(rootClone)251 // revoke all proxies252 revocableProxies.forEach(p => p.revoke())253 return res254 } finally {255 revocableProxies = previousProxies

transpile es5 codeMichel Weststratebefore adoptionf012154

lines 256–267why, one step back
256 }
257}258259function isProxy(value) {260 return !!value && !!value[PROXY_STATE]261}262263function isProxyable(value) {264 if (!value) return false265 if (typeof value !== "object") return false266 if (Array.isArray(value)) return true267 const proto = Object.getPrototypeOf(value)

initial solutionMichel Weststratebefore adoptiond618d28

line 268why, one step back
268 return proto === null || proto === Object.prototype

transpile es5 codeMichel Weststratebefore adoptionf012154

lines 269–289why, one step back
269}
270271function freeze(value) {272 // short circuit to achieve 100% code coverage instead of 98%273 /*274 if(autoFreeze) {275 Object.freeze(value)276 }277 * */278 autoFreeze && Object.freeze(value)279 return value280}281282/**283 * Automatically freezes any state trees generated by immer.284 * This protects against accidental modifications of the state tree outside of an immer function.285 * This comes with a performance impact, so it is recommended to disable this option in production.286 * It is by default enabled.287 *288 * @returns {void}289 */

Default build includes both Proxy and ES5 implementationMichel Weststratebefore adoptionbd9c47b

line 290why, one step back
290export function setAutoFreeze(enableAutoFreeze) {

transpile es5 codeMichel Weststratebefore adoptionf012154

lines 291–292why, one step back
291 autoFreeze = enableAutoFreeze
292}