Skip to content
Myr

proxy.js

This file

Path

src/proxy.js

427 lines · 11.7 KiB · JavaScript

Last changed by

refactor: makeTrapsForGetters functionAlec Larsonbefore adoption5093fd0

History of this file

Take it

The walk stopped after 200 commits: lines older than 1f93af2 point at it.

fix: use proxies only if Reflect exists (#227)Alec Larsonbefore adoption1f93af2

lines 1–2why, one step back
1"use strict"
2import {

fix: always use `assign` polyfillaleclarsonbefore adoption241a648

lines 3–4why, one step back
3 assign,
4 each,

fix: use proxies only if Reflect exists (#227)Alec Larsonbefore adoption1f93af2

line 5why, one step back
5 has,

fix: always use `assign` polyfillaleclarsonbefore adoption241a648

line 6why, one step back
6 is,

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

lines 7–8why, one step back
7 isDraftable,
8 isDraft,

feat: `Map` drafts and patcheskeenondrumsbefore adoption30db0f3

line 9why, one step back
9 isMap,

feat: `Set` draftsAndrey Goncharovbefore adoption4355b63

line 10why, one step back
10 isSet,

fix: use proxies only if Reflect exists (#227)Alec Larsonbefore adoption1f93af2

line 11why, one step back
11 shallowCopy,

feat: `Set` draftsAndrey Goncharovbefore adoption4355b63

lines 12–15why, one step back
12 DRAFT_STATE,
13 assignMap,14 assignSet,15 original

fix: use proxies only if Reflect exists (#227)Alec Larsonbefore adoption1f93af2

line 16why, one step back
16} from "./common"

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

line 17why, one step back
17import {ImmerScope} from "./scope"

fix: use proxies only if Reflect exists (#227)Alec Larsonbefore adoption1f93af2

line 18why, one step back
18

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

lines 19–21why, one step back
19// Do nothing before being finalized.
20export function willFinalize() {}21

chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d

lines 22–26why, one step back
22/**
23 * Returns a new draft of the `base` object.24 *25 * The second argument is the parent draft-state (used internally).26 */

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

lines 27–28why, one step back
27export function createProxy(base, parent) {
28 const scope = parent ? parent.scope : ImmerScope.current

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

line 29why, one step back
29 const state = {

feat: passing drafts to producealeclarsonbefore adoption9c53415

line 30why, one step back
30 // Track which produce call this is associated with.

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

line 31why, one step back
31 scope,

feat: passing drafts to producealeclarsonbefore adoption9c53415

lines 32–38why, one step back
32 // True for both shallow and deep changes.
33 modified: false,34 // Used during finalization.35 finalized: false,36 // Track which properties have been assigned (true) or deleted (false).37 assigned: {},38 // The parent draft state.

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

line 39why, one step back
39 parent,

feat: passing drafts to producealeclarsonbefore adoption9c53415

line 40why, one step back
40 // The base state.

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

line 41why, one step back
41 base,

feat: passing drafts to producealeclarsonbefore adoption9c53415

lines 42–46why, one step back
42 // The base proxy.
43 draft: null,44 // Any property proxies.45 drafts: {},46 // The base copy with any updated values.

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

line 47why, one step back
47 copy: null,

feat: passing drafts to producealeclarsonbefore adoption9c53415

lines 48–49why, one step back
48 // Called by the `produce` function.
49 revoke: null

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

lines 50–51why, one step back
50 }
51

feat: `Map` drafts and patcheskeenondrumsbefore adoption30db0f3

lines 52–58why, one step back
52 let proxyTarget = state
53 let traps = objectTraps54 if (Array.isArray(base)) {55 proxyTarget = [state]56 traps = arrayTraps57 } else if (isMap(base)) {58 traps = mapTraps

feat: `Set` draftsAndrey Goncharovbefore adoption4355b63

lines 59–62why, one step back
59 } else if (isSet(base)) {
60 traps = setTraps61 // We use values of a Set as keys and objects do not support other objects as keys62 state.drafts = new Map()

feat: `Map` drafts and patcheskeenondrumsbefore adoption30db0f3

line 63why, one step back
63 }

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

line 64why, one step back
64

feat: `Map` drafts and patcheskeenondrumsbefore adoption30db0f3

lines 65–66why, one step back
65 const {revoke, proxy} = Proxy.revocable(proxyTarget, traps)
66

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

lines 67–69why, one step back
67 state.draft = proxy
68 state.revoke = revoke69

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

line 70why, one step back
70 scope.drafts.push(proxy)

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

lines 71–73why, one step back
71 return proxy
72}73

chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d

lines 74–77why, one step back
74/**
75 * Object drafts76 */77

fix: use proxies only if Reflect exists (#227)Alec Larsonbefore adoption1f93af2

line 78why, one step back
78const objectTraps = {

chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d

lines 79–102why, one step back
79 get(state, prop) {
80 if (prop === DRAFT_STATE) return state81 let {drafts} = state8283 // Check for existing draft in unmodified state.84 if (!state.modified && has(drafts, prop)) {85 return drafts[prop]86 }8788 const value = source(state)[prop]89 if (state.finalized || !isDraftable(value)) {90 return value91 }9293 // Check for existing draft in modified state.94 if (state.modified) {95 // Assigned values are never drafted. This catches any drafts we created, too.96 if (value !== peek(state.base, prop)) return value97 // Store drafts on the copy (when one exists).98 drafts = state.copy99 }100101 return (drafts[prop] = createProxy(value, state))102 },

nit: argument namesAlec Larsonbefore adoptiona674a78

lines 103–104why, one step back
103 has(state, prop) {
104 return prop in source(state)

chore: reorganize src/proxy.jsAlec Larsonbefore adoptione809ffc

line 105why, one step back
105 },

nit: argument namesAlec Larsonbefore adoptiona674a78

lines 106–107why, one step back
106 ownKeys(state) {
107 return Reflect.ownKeys(source(state))

fix: use proxies only if Reflect exists (#227)Alec Larsonbefore adoption1f93af2

line 108why, one step back
108 },

chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d

lines 109–144why, one step back
109 set(state, prop, value) {
110 if (!state.modified) {111 const baseValue = peek(state.base, prop)112 // Optimize based on value's truthiness. Truthy values are guaranteed to113 // never be undefined, so we can avoid the `in` operator. Lastly, truthy114 // values may be drafts, but falsy values are never drafts.115 const isUnchanged = value116 ? is(baseValue, value) || value === state.drafts[prop]117 : is(baseValue, value) && prop in state.base118 if (isUnchanged) return true119 markChanged(state)120 }121 state.assigned[prop] = true122 state.copy[prop] = value123 return true124 },125 deleteProperty(state, prop) {126 // The `undefined` check is a fast path for pre-existing keys.127 if (peek(state.base, prop) !== undefined || prop in state.base) {128 state.assigned[prop] = false129 markChanged(state)130 }131 if (state.copy) delete state.copy[prop]132 return true133 },134 // Note: We never coerce `desc.value` into an Immer draft, because we can't make135 // the same guarantee in ES5 mode.136 getOwnPropertyDescriptor(state, prop) {137 const owner = source(state)138 const desc = Reflect.getOwnPropertyDescriptor(owner, prop)139 if (desc) {140 desc.writable = true141 desc.configurable = !Array.isArray(owner) || prop !== "length"142 }143 return desc144 },

feat: limited class supportaleclarsonbefore adoption9877d64

lines 145–147why, one step back
145 defineProperty() {
146 throw new Error("Object.defineProperty() cannot be used on an Immer draft") // prettier-ignore147 },

nit: argument namesAlec Larsonbefore adoptiona674a78

lines 148–149why, one step back
148 getPrototypeOf(state) {
149 return Object.getPrototypeOf(state.base)

fix: Object.getPrototypeOf with a draftaleclarsonbefore adoptiond5d07e8

line 150why, one step back
150 },

fix: use proxies only if Reflect exists (#227)Alec Larsonbefore adoption1f93af2

line 151why, one step back
151 setPrototypeOf() {

feat: limited class supportaleclarsonbefore adoption9877d64

line 152why, one step back
152 throw new Error("Object.setPrototypeOf() cannot be used on an Immer draft") // prettier-ignore

fix: use proxies only if Reflect exists (#227)Alec Larsonbefore adoption1f93af2

lines 153–155why, one step back
153 }
154}155

chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d

lines 156–159why, one step back
156/**
157 * Array drafts158 */159

fix: use proxies only if Reflect exists (#227)Alec Larsonbefore adoption1f93af2

lines 160–167why, one step back
160const arrayTraps = {}
161each(objectTraps, (key, fn) => {162 arrayTraps[key] = function() {163 arguments[0] = arguments[0][0]164 return fn.apply(this, arguments)165 }166})167arrayTraps.deleteProperty = function(state, prop) {

feat: limited class supportaleclarsonbefore adoption9877d64

lines 168–170why, one step back
168 if (isNaN(parseInt(prop))) {
169 throw new Error("Immer only supports deleting array indices") // prettier-ignore170 }

fix: use proxies only if Reflect exists (#227)Alec Larsonbefore adoption1f93af2

lines 171–173why, one step back
171 return objectTraps.deleteProperty.call(this, state[0], prop)
172}173arrayTraps.set = function(state, prop, value) {

feat: limited class supportaleclarsonbefore adoption9877d64

lines 174–176why, one step back
174 if (prop !== "length" && isNaN(parseInt(prop))) {
175 throw new Error("Immer only supports setting array indices and the 'length' property") // prettier-ignore176 }

fix: use proxies only if Reflect exists (#227)Alec Larsonbefore adoption1f93af2

line 177why, one step back
177 return objectTraps.set.call(this, state[0], prop, value)

feat: `Map` drafts and patcheskeenondrumsbefore adoption30db0f3

lines 178–179why, one step back
178}
179

refactor: makeTrapsForGetters functionAlec Larsonbefore adoption5093fd0

lines 180–192why, one step back
180// Used by Map and Set drafts
181const reflectTraps = makeReflectTraps([182 "ownKeys",183 "has",184 "set",185 "deleteProperty",186 "defineProperty",187 "getOwnPropertyDescriptor",188 "preventExtensions",189 "isExtensible",190 "getPrototypeOf"191])192

chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d

lines 193–196why, one step back
193/**
194 * Map drafts195 */196

refactor: makeTrapsForGetters functionAlec Larsonbefore adoption5093fd0

line 197why, one step back
197const mapTraps = makeTrapsForGetters({

fix: add Map getter for DRAFT_STATE, make isEnumerable more resilientkeenondrumsbefore adoption7bbec0a

line 198why, one step back
198 [DRAFT_STATE]: state => state,

chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d

lines 199–204why, one step back
199 size: state => source(state).size,
200 has(state, prop) {201 state = source(state)202 return state.has.bind(state)203 },204 set: state => (key, value) => {

feat: `Set` draftsAndrey Goncharovbefore adoption4355b63

lines 205–210why, one step back
205 const stateSource = source(state)
206 if (!stateSource.has(key) || stateSource.get(key) !== value) {207 markChanged(state)208 state.assigned[key] = true209 state.copy.set(key, value)210 }

fix: Map.prototype.set should return a draftAndrey Goncharovbefore adoption7001201

line 211why, one step back
211 return state.draft

chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d

lines 212–222why, one step back
212 },
213 delete: state => key => {214 markChanged(state)215 state.assigned[key] = false216 return state.copy.delete(key)217 },218 clear: state => () => {219 markChanged(state)220 state.assigned = {}221 for (const key of source(state).keys()) {222 state.assigned[key] = false

feat: `Map` drafts and patcheskeenondrumsbefore adoption30db0f3

line 223why, one step back
223 }

chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d

lines 224–233why, one step back
224 return state.copy.clear()
225 },226 forEach: (state, _, receiver) => (cb, thisArg) =>227 source(state).forEach((_, key, map) => {228 const value = receiver.get(key)229 cb.call(thisArg, value, key, map)230 }),231 get: state => key => {232 if (!state.modified && has(state.drafts, key)) {233 return state.drafts[key]

feat: `Map` drafts and patcheskeenondrumsbefore adoption30db0f3

line 234why, one step back
234 }

chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d

lines 235–237why, one step back
235
236 if (state.modified && state.copy.has(key)) {237 return state.copy.get(key)

feat: `Map` drafts and patcheskeenondrumsbefore adoption30db0f3

line 238why, one step back
238 }

chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d

lines 239–243why, one step back
239
240 const value = source(state).get(key)241242 if (state.finalized || !isDraftable(value)) {243 return value

feat: `Map` drafts and patcheskeenondrumsbefore adoption30db0f3

lines 244–245why, one step back
244 }
245

chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d

line 246why, one step back
246 const draft = createProxy(value, state)

feat: `Map` drafts and patcheskeenondrumsbefore adoption30db0f3

line 247why, one step back
247

chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d

lines 248–252why, one step back
248 if (!state.modified) {
249 state.drafts[key] = draft250 } else {251 state.copy.set(key, draft)252 }

feat: `Map` drafts and patcheskeenondrumsbefore adoption30db0f3

line 253why, one step back
253

chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d

lines 254–255why, one step back
254 return draft
255 },

refactor: simplify mapGetters.keysAlec Larsonbefore adoption3298a77

line 256why, one step back
256 keys: state => () => source(state).keys(),

chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d

lines 257–259why, one step back
257 values: iterateMapValues,
258 entries: iterateMapValues,259 [Symbol.iterator]: iterateMapValues

refactor: makeTrapsForGetters functionAlec Larsonbefore adoption5093fd0

line 260why, one step back
260})

feat: `Map` drafts and patcheskeenondrumsbefore adoption30db0f3

line 261why, one step back
261

chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d

lines 262–266why, one step back
262/** Map.prototype.values _-or-_ Map.prototype.entries */
263function iterateMapValues(state, prop, receiver) {264 const getYieldable =265 prop === "values" ? (key, value) => value : (key, value) => [key, value]266

fix: remove "function*" syntaxAlec Larsonbefore adoption08d88b8

line 267why, one step back
267 return () => {

chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d

line 268why, one step back
268 const iterator = source(state)[Symbol.iterator]()

fix: remove "function*" syntaxAlec Larsonbefore adoption08d88b8

lines 269–277why, one step back
269 return makeIterable(() => {
270 const result = iterator.next()271 if (!result.done) {272 const [key] = result.value273 const value = receiver.get(key)274 result.value = getYieldable(key, value)275 }276 return result277 })

feat: `Map` drafts and patcheskeenondrumsbefore adoption30db0f3

line 278why, one step back
278 }

feat: `Map` supportkeenondrumsbefore adoption8276a6c

lines 279–280why, one step back
279}
280

chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d

line 281why, one step back
281/**

feat: `Set` draftsAndrey Goncharovbefore adoption4355b63

lines 282–284why, one step back
282 * Set drafts
283 */284

refactor: makeTrapsForGetters functionAlec Larsonbefore adoption5093fd0

line 285why, one step back
285const setTraps = makeTrapsForGetters({

feat: `Set` draftsAndrey Goncharovbefore adoption4355b63

lines 286–318why, one step back
286 [DRAFT_STATE]: state => state,
287 size: state => source(state).size,288 has(state, prop) {289 state = source(state)290 return state.has.bind(state)291 },292 add: state => value => {293 if (!source(state).has(value)) {294 markChanged(state)295 state.copy.add(value)296 }297 return state.draft298 },299 delete: state => value => {300 markChanged(state)301 return state.copy.delete(value)302 },303 clear: state => () => {304 markChanged(state)305 return state.copy.clear()306 },307 forEach: state => (cb, thisArg) => {308 const iterator = iterateSetValues(state)()309 let result = iterator.next()310 while (!result.done) {311 cb.call(thisArg, result.value, result.value, state.draft)312 result = iterator.next()313 }314 },315 keys: iterateSetValues,316 values: iterateSetValues,317 entries: iterateSetValues,318 [Symbol.iterator]: iterateSetValues

refactor: makeTrapsForGetters functionAlec Larsonbefore adoption5093fd0

line 319why, one step back
319})

feat: `Set` draftsAndrey Goncharovbefore adoption4355b63

lines 320–355why, one step back
320
321function iterateSetValues(state, prop) {322 return () => {323 const iterator = source(state)[Symbol.iterator]()324325 return makeIterable(() => {326 const result = iterator.next()327 if (!result.done) {328 const valueWrapped = wrapSetValue(state, result.value)329 result.value = valueWrapped330 if (prop === "entries") {331 result.value = [valueWrapped, valueWrapped]332 }333 }334 return result335 })336 }337}338339function wrapSetValue(state, value) {340 const key = original(value) || value341 let draft = state.drafts.get(key)342 if (!draft) {343 if (state.finalized || !isDraftable(value)) {344 return value345 }346 draft = createProxy(value, state)347 state.drafts.set(key, draft)348 if (state.modified) {349 state.copy.add(draft)350 }351 }352 return draft353}354355/**

chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d

lines 356–358why, one step back
356 * Helpers
357 */358

fix: revert Map supportAlec Larsonbefore adoption47529d3

lines 359–362why, one step back
359// returns the object we should be reading the current value from, which is base, until some change has been made
360function source(state) {361 return state.copy || state.base362}

chore: reorganize src/proxy.jsAlec Larsonbefore adoptione809ffc

line 363why, one step back
363

fix: revert Map supportAlec Larsonbefore adoption47529d3

lines 364–371why, one step back
364// Access a property without creating an Immer draft.
365function peek(draft, prop) {366 const state = draft[DRAFT_STATE]367 const desc = Reflect.getOwnPropertyDescriptor(368 state ? source(state) : draft,369 prop370 )371 return desc && desc.value

fix: use proxies only if Reflect exists (#227)Alec Larsonbefore adoption1f93af2

lines 372–376why, one step back
372}
373374function markChanged(state) {375 if (!state.modified) {376 state.modified = true

refactor: markChanged functionAlec Larsonbefore adoption5857d63

lines 377–388why, one step back
377
378 const {base, drafts, parent} = state379 const copy = shallowCopy(base)380381 if (isSet(base)) {382 // Note: The `drafts` property is preserved for Set objects, since383 // we need to keep track of which values are drafted.384 assignSet(copy, drafts)385 } else {386 // Merge nested drafts into the copy.387 if (isMap(base)) assignMap(copy, drafts)388 else assign(copy, drafts)

feat: `Set` draftsAndrey Goncharovbefore adoption4355b63

lines 389–390why, one step back
389 state.drafts = null
390 }

refactor: markChanged functionAlec Larsonbefore adoption5857d63

lines 391–395why, one step back
391
392 state.copy = copy393 if (parent) {394 markChanged(parent)395 }

fix: use proxies only if Reflect exists (#227)Alec Larsonbefore adoption1f93af2

line 396why, one step back
396 }

fix: remove "function*" syntaxAlec Larsonbefore adoption08d88b8

lines 397–404why, one step back
397}
398399function makeIterable(next) {400 let self401 return (self = {402 [Symbol.iterator]: () => self,403 next404 })

refactor: traps for Maps and Setskeenondrumsbefore adoptiondd82d89

lines 405–406why, one step back
405}
406

refactor: makeTrapsForGetters functionAlec Larsonbefore adoption5093fd0

lines 407–414why, one step back
407/** Create traps that all use the `Reflect` API on the `source(state)` */
408function makeReflectTraps(names) {409 return names.reduce((traps, name) => {410 traps[name] = (state, ...args) => Reflect[name](source(state), ...args)411 return traps412 }, {})413}414

refactor: traps for Maps and Setskeenondrumsbefore adoptiondd82d89

lines 415–416why, one step back
415function makeTrapsForGetters(getters) {
416 return {

refactor: makeTrapsForGetters functionAlec Larsonbefore adoption5093fd0

line 417why, one step back
417 ...reflectTraps,

refactor: traps for Maps and Setskeenondrumsbefore adoptiondd82d89

lines 418–421why, one step back
418 get(state, prop, receiver) {
419 return getters.hasOwnProperty(prop)420 ? getters[prop](state, prop, receiver)421 : Reflect.get(state, prop, receiver)

fix: add more traps for Maps and SetsAndrey Goncharovbefore adoption930b4ab

lines 422–424why, one step back
422 },
423 setPrototypeOf(state) {424 throw new Error("Object.setPrototypeOf() cannot be used on an Immer draft") // prettier-ignore

refactor: traps for Maps and Setskeenondrumsbefore adoptiondd82d89

lines 425–426why, one step back
425 }
426 }

fix: use proxies only if Reflect exists (#227)Alec Larsonbefore adoption1f93af2

line 427why, one step back
427}