Skip to content
Myr

proxy.ts

This file

Path

src/proxy.ts

429 lines · 10.7 KiB · TypeScript

Last changed by

Making mosts tests passMichel Weststratebefore adoptionf8d4056

History of this file

Take it

converted everything, 0 errorsMichel Weststratebefore adoptionb4c6e59

lines 1–25why, one step back
1"use strict"
2import {3 assign,4 each,5 has,6 is,7 isDraftable,8 isDraft,9 isMap,10 isSet,11 hasSymbol,12 shallowCopy,13 makeIterable,14 DRAFT_STATE,15 assignMap,16 assignSet,17 original,18 iterateMapValues,19 makeIterateSetValues20} from "./common"21import {ImmerScope} from "./scope"2223// Do nothing before being finalized.24export function willFinalize() {}25

Making mosts tests passMichel Weststratebefore adoptionf8d4056

line 26why, one step back
26interface ES6Draft {}

converted everything, 0 errorsMichel Weststratebefore adoptionb4c6e59

line 27why, one step back
27

Making mosts tests passMichel Weststratebefore adoptionf8d4056

lines 28–38why, one step back
28interface ES6State<T = any> {
29 scope: ImmerScope30 modified: boolean31 finalized: boolean32 assigned:33 | {34 [property: string]: boolean35 }36 | Map<string, boolean> // TODO: always use a Map?37 parent: ES6State38 base: T

converted everything, 0 errorsMichel Weststratebefore adoptionb4c6e59

line 39why, one step back
39 draft: ES6Draft | null

Making mosts tests passMichel Weststratebefore adoptionf8d4056

lines 40–44why, one step back
40 drafts:
41 | {42 [property: string]: ES6Draft43 }44 | Map<string, ES6Draft> // TODO: always use a Map?

converted everything, 0 errorsMichel Weststratebefore adoptionb4c6e59

line 45why, one step back
45 copy: T | null

Making mosts tests passMichel Weststratebefore adoptionf8d4056

line 46why, one step back
46 revoke: null | (() => void)

converted everything, 0 errorsMichel Weststratebefore adoptionb4c6e59

lines 47–53why, one step back
47}
4849/**50 * Returns a new draft of the `base` object.51 *52 * The second argument is the parent draft-state (used internally).53 */

Making mosts tests passMichel Weststratebefore adoptionf8d4056

lines 54–57why, one step back
54export function createProxy<T extends object>(
55 base: T,56 parent: ES6State57): ES6Draft {

converted everything, 0 errorsMichel Weststratebefore adoptionb4c6e59

lines 58–88why, one step back
58 const scope = parent ? parent.scope : ImmerScope.current!
59 const state: ES6State<T> = {60 // Track which produce call this is associated with.61 scope,62 // True for both shallow and deep changes.63 modified: false,64 // Used during finalization.65 finalized: false,66 // Track which properties have been assigned (true) or deleted (false).67 assigned: {},68 // The parent draft state.69 parent,70 // The base state.71 base,72 // The base proxy.73 draft: null,74 // Any property proxies.75 drafts: {},76 // The base copy with any updated values.77 copy: null,78 // Called by the `produce` function.79 revoke: null80 }8182 // the traps must target something, a bit like the 'real' base.83 // but also, we need to be able to determine from the target what the relevant state is84 // (to avoid creating traps per instance to capture the state in closure,85 // and to avoid creating weird hidden properties as well)86 // So the trick is to use 'state' as the actual 'target'! (and make sure we intercept everything)87 // Note that in the case of an array, we put the state in an array to have better Reflect defaults ootb88 let target: T = state as any

Making mosts tests passMichel Weststratebefore adoptionf8d4056

line 89why, one step back
89 let traps: ProxyHandler<object | Array<any>> = objectTraps

converted everything, 0 errorsMichel Weststratebefore adoptionb4c6e59

lines 90–214why, one step back
90 if (Array.isArray(base)) {
91 target = [state] as any92 traps = arrayTraps93 }94 // Map drafts must support object keys, so we use Map objects to track changes.95 else if (isMap(base)) {96 traps = mapTraps97 state.drafts = new Map()98 state.assigned = new Map()99 }100 // Set drafts use a Map object to track which of its values are drafted.101 // And we don't need the "assigned" property, because Set objects have no keys.102 else if (isSet(base)) {103 traps = setTraps104 state.drafts = new Map()105 }106107 const {revoke, proxy} = Proxy.revocable(target, traps)108109 state.draft = proxy110 state.revoke = revoke111112 scope.drafts!.push(proxy)113 return proxy114}115116/**117 * Object drafts118 */119const objectTraps: ProxyHandler<ES6State> = {120 get(state, prop) {121 if (prop === DRAFT_STATE) return state122 let {drafts} = state123124 // Check for existing draft in unmodified state.125 if (!state.modified && has(drafts, prop)) {126 return drafts[prop]127 }128129 const value = latest(state)[prop]130 if (state.finalized || !isDraftable(value)) {131 return value132 }133134 // Check for existing draft in modified state.135 if (state.modified) {136 // Assigned values are never drafted. This catches any drafts we created, too.137 if (value !== peek(state.base, prop)) return value138 // Store drafts on the copy (when one exists).139 drafts = state.copy140 }141142 return (drafts[prop] = createProxy(value, state))143 },144 has(state, prop) {145 return prop in latest(state)146 },147 ownKeys(state) {148 return Reflect.ownKeys(latest(state))149 },150 set(state, prop, value) {151 if (!state.modified) {152 const baseValue = peek(state.base, prop)153 // Optimize based on value's truthiness. Truthy values are guaranteed to154 // never be undefined, so we can avoid the `in` operator. Lastly, truthy155 // values may be drafts, but falsy values are never drafts.156 const isUnchanged = value157 ? is(baseValue, value) || value === state.drafts[prop]158 : is(baseValue, value) && prop in state.base159 if (isUnchanged) return true160 markChanged(state)161 }162 state.assigned[prop] = true163 state.copy[prop] = value164 return true165 },166 deleteProperty(state, prop) {167 // The `undefined` check is a fast path for pre-existing keys.168 if (peek(state.base, prop) !== undefined || prop in state.base) {169 state.assigned[prop] = false170 markChanged(state)171 } else if (state.assigned[prop]) {172 // if an originally not assigned property was deleted173 delete state.assigned[prop]174 }175 if (state.copy) delete state.copy[prop]176 return true177 },178 // Note: We never coerce `desc.value` into an Immer draft, because we can't make179 // the same guarantee in ES5 mode.180 getOwnPropertyDescriptor(state, prop) {181 const owner = latest(state)182 const desc = Reflect.getOwnPropertyDescriptor(owner, prop)183 if (desc) {184 desc.writable = true185 desc.configurable = !Array.isArray(owner) || prop !== "length"186 }187 return desc188 },189 defineProperty() {190 throw new Error("Object.defineProperty() cannot be used on an Immer draft") // prettier-ignore191 },192 getPrototypeOf(state) {193 return Object.getPrototypeOf(state.base)194 },195 setPrototypeOf() {196 throw new Error("Object.setPrototypeOf() cannot be used on an Immer draft") // prettier-ignore197 }198}199200/**201 * Array drafts202 */203204const arrayTraps: ProxyHandler<[ES6State]> = {}205each(objectTraps, (key, fn) => {206 arrayTraps[key] = function() {207 arguments[0] = arguments[0][0]208 return fn.apply(this, arguments)209 }210})211arrayTraps.deleteProperty = function(state, prop) {212 if (isNaN(parseInt(prop as any))) {213 throw new Error("Immer only supports deleting array indices") // prettier-ignore214 }

Making mosts tests passMichel Weststratebefore adoptionf8d4056

line 215why, one step back
215 return objectTraps.deleteProperty!.call(this, state[0], prop)

converted everything, 0 errorsMichel Weststratebefore adoptionb4c6e59

lines 216–220why, one step back
216}
217arrayTraps.set = function(state, prop, value) {218 if (prop !== "length" && isNaN(parseInt(prop as any))) {219 throw new Error("Immer only supports setting array indices and the 'length' property") // prettier-ignore220 }

Making mosts tests passMichel Weststratebefore adoptionf8d4056

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

converted everything, 0 errorsMichel Weststratebefore adoptionb4c6e59

lines 222–398why, one step back
222}
223224// Used by Map and Set drafts225const reflectTraps = makeReflectTraps([226 "ownKeys",227 "has",228 "set",229 "deleteProperty",230 "defineProperty",231 "getOwnPropertyDescriptor",232 "preventExtensions",233 "isExtensible",234 "getPrototypeOf"235])236237/**238 * Map drafts239 */240241const mapTraps = makeTrapsForGetters<Map<any, any>>({242 [DRAFT_STATE]: state => state,243 size: state => latest(state).size,244 has: state => key => latest(state).has(key),245 set: state => (key, value) => {246 const values = latest(state)247 if (!values.has(key) || values.get(key) !== value) {248 markChanged(state)249 // @ts-ignore250 state.assigned.set(key, true)251 state.copy!.set(key, value)252 }253 return state.draft254 },255 delete: state => key => {256 if (latest(state).has(key)) {257 markChanged(state)258 // @ts-ignore259 state.assigned.set(key, false)260 return state.copy!.delete(key)261 }262 return false263 },264 clear: state => () => {265 markChanged(state)266 state.assigned = new Map()267 for (const key of latest(state).keys()) {268 state.assigned.set(key, false)269 }270 return state.copy!.clear()271 },272 // @ts-ignore273 forEach: (state, _, receiver) => (cb, thisArg) =>274 latest(state).forEach((_, key, map) => {275 const value = receiver.get(key)276 cb.call(thisArg, value, key, map)277 }),278 get: state => key => {279 const drafts = state.modified ? state.copy : state.drafts280281 // @ts-ignore TODO: ...or fix by using different ES6Draft types (but better just unify to maps)282 if (drafts!.has(key)) {283 // @ts-ignore284 const value = drafts.get(key)285286 if (isDraft(value) || !isDraftable(value)) return value287288 const draft = createProxy(value, state)289 // @ts-ignore290 drafts.set(key, draft)291 return draft292 }293294 const value = latest(state).get(key)295 if (state.finalized || !isDraftable(value)) {296 return value297 }298299 const draft = createProxy(value, state)300 //@ts-ignore301 drafts.set(key, draft)302 return draft303 },304 keys: state => () => latest(state).keys(),305 //@ts-ignore306 values: iterateMapValues,307 //@ts-ignore308 entries: iterateMapValues,309 [hasSymbol ? Symbol.iterator : "@@iterator"]: iterateMapValues310})311312const iterateSetValues = makeIterateSetValues(createProxy)313/**314 * Set drafts315 */316317const setTraps = makeTrapsForGetters<Set<any>>({318 //@ts-ignore319 [DRAFT_STATE]: state => state,320 size: state => latest(state).size,321 has: state => key => latest(state).has(key),322 add: state => value => {323 if (!latest(state).has(value)) {324 markChanged(state)325 //@ts-ignore326 state.copy.add(value)327 }328 return state.draft329 },330 delete: state => value => {331 markChanged(state)332 //@ts-ignore333 return state.copy.delete(value)334 },335 clear: state => () => {336 markChanged(state)337 //@ts-ignore338 return state.copy.clear()339 },340 forEach: state => (cb, thisArg) => {341 const iterator = iterateSetValues(state)()342 let result = iterator.next()343 while (!result.done) {344 cb.call(thisArg, result.value, result.value, state.draft)345 result = iterator.next()346 }347 },348 keys: iterateSetValues,349 values: iterateSetValues,350 entries: iterateSetValues,351 [hasSymbol ? Symbol.iterator : "@@iterator"]: iterateSetValues352})353354/**355 * Helpers356 */357358// Retrieve the latest values of the draft.359function latest(state) {360 return state.copy || state.base361}362363// Access a property without creating an Immer draft.364function peek(draft, prop) {365 const state = draft[DRAFT_STATE]366 const desc = Reflect.getOwnPropertyDescriptor(367 state ? latest(state) : draft,368 prop369 )370 return desc && desc.value371}372373function markChanged(state) {374 if (!state.modified) {375 state.modified = true376377 const {base, drafts, parent} = state378 const copy = shallowCopy(base)379380 if (isSet(base)) {381 // Note: The `drafts` property is preserved for Set objects, since382 // we need to keep track of which values are drafted.383 assignSet(copy, drafts)384 } else {385 // Merge nested drafts into the copy.386 if (isMap(base)) assignMap(copy, drafts)387 else assign(copy, drafts)388 state.drafts = null389 }390391 state.copy = copy392 if (parent) {393 markChanged(parent)394 }395 }396}397398/** Create traps that all use the `Reflect` API on the `latest(state)` */

Making mosts tests passMichel Weststratebefore adoptionf8d4056

lines 399–409why, one step back
399function makeReflectTraps<T extends object>(
400 names: (keyof typeof Reflect)[]401): ProxyHandler<T> {402 return names.reduce(403 (traps, name) => {404 // @ts-ignore405 traps[name] = (state, ...args) => Reflect[name](latest(state), ...args)406 return traps407 },408 {} as any409 )

converted everything, 0 errorsMichel Weststratebefore adoptionb4c6e59

lines 410–411why, one step back
410}
411

Making mosts tests passMichel Weststratebefore adoptionf8d4056

lines 412–418why, one step back
412function makeTrapsForGetters<T extends object>(
413 getters: {414 [K in keyof T]: (415 state: ES6State<T>416 ) => /* Skip first arg of: ProxyHandler<T>[K] */ any417 }418): ProxyHandler<T> {

converted everything, 0 errorsMichel Weststratebefore adoptionb4c6e59

lines 419–429why, one step back
419 return assign({}, reflectTraps, {
420 get(state, prop, receiver) {421 return getters.hasOwnProperty(prop)422 ? getters[prop](state, prop, receiver)423 : Reflect.get(state, prop, receiver)424 },425 setPrototypeOf(state) {426 throw new Error("Object.setPrototypeOf() cannot be used on an Immer draft") // prettier-ignore427 }428 })429}