Skip to content
Myr

proxy.ts

This file

Path

src/core/proxy.ts

336 lines · 9.2 KiB · TypeScript

Last changed by

fix: Fix broken array patching and ensure all values in draft Maps/Sets are finalized (#1201)Mark Eriksonbefore adoptionb208d58

History of this file

Take it

The walk stopped after 200 commits: lines older than 3f9a94e point at it.

chore: let's test before publishMichel Weststratebefore adoption3f9a94e

lines 1–13why, one step back
1import {
2 has,3 is,4 isDraftable,5 shallowCopy,6 latest,7 ImmerBaseState,8 ImmerState,9 Drafted,10 AnyObject,11 AnyArray,12 Objectish,13 getCurrentScope,

Merge pull request #1028 from immerjs/immer-10Michel Weststratebefore adoption2ef9a42

line 14why, one step back
14 getPrototypeOf,

chore: let's test before publishMichel Weststratebefore adoption3f9a94e

lines 15–17why, one step back
15 DRAFT_STATE,
16 die,17 createProxy,

Merge pull request #1028 from immerjs/immer-10Michel Weststratebefore adoption2ef9a42

line 18why, one step back
18 ArchType,

perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202

lines 19–23why, one step back
19 handleCrossReference,
20 WRITABLE,21 CONFIGURABLE,22 ENUMERABLE,23 VALUE,

feat: Override array methods to avoid proxy creation while iterating and updating (#1184)Mark Eriksonbefore adoptiond38a9d0

lines 24–25why, one step back
24 isArray,
25 isArrayIndex

chore: let's test before publishMichel Weststratebefore adoption3f9a94e

lines 26–33why, one step back
26} from "../internal"
2728interface ProxyBaseState extends ImmerBaseState {29 parent_?: ImmerState30 revoke_(): void31}3233export interface ProxyObjectState extends ProxyBaseState {

Merge pull request #1028 from immerjs/immer-10Michel Weststratebefore adoption2ef9a42

line 34why, one step back
34 type_: ArchType.Object

chore: let's test before publishMichel Weststratebefore adoption3f9a94e

lines 35–40why, one step back
35 base_: any
36 copy_: any37 draft_: Drafted<AnyObject, ProxyObjectState>38}3940export interface ProxyArrayState extends ProxyBaseState {

Merge pull request #1028 from immerjs/immer-10Michel Weststratebefore adoption2ef9a42

line 41why, one step back
41 type_: ArchType.Array

chore: let's test before publishMichel Weststratebefore adoption3f9a94e

lines 42–44why, one step back
42 base_: AnyArray
43 copy_: AnyArray | null44 draft_: Drafted<AnyArray, ProxyArrayState>

feat: Override array methods to avoid proxy creation while iterating and updating (#1184)Mark Eriksonbefore adoptiond38a9d0

lines 45–46why, one step back
45 operationMethod?: string
46 allIndicesReassigned_?: boolean

chore: let's test before publishMichel Weststratebefore adoption3f9a94e

lines 47–58why, one step back
47}
4849type ProxyState = ProxyObjectState | ProxyArrayState5051/**52 * Returns a new draft of the `base` object.53 *54 * The second argument is the parent draft-state (used internally).55 */56export function createProxyProxy<T extends Objectish>(57 base: T,58 parent?: ImmerState

perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202

lines 59–60why, one step back
59): [Drafted<T, ProxyState>, ProxyState] {
60 const baseIsArray = isArray(base)

chore: let's test before publishMichel Weststratebefore adoption3f9a94e

line 61why, one step back
61 const state: ProxyState = {

perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202

line 62why, one step back
62 type_: baseIsArray ? ArchType.Array : (ArchType.Object as any),

chore: let's test before publishMichel Weststratebefore adoption3f9a94e

lines 63–69why, one step back
63 // Track which produce call this is associated with.
64 scope_: parent ? parent.scope_ : getCurrentScope()!,65 // True for both shallow and deep changes.66 modified_: false,67 // Used during finalization.68 finalized_: false,69 // Track which properties have been assigned (true) or deleted (false).

perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202

lines 70–71why, one step back
70 // actually instantiated in `prepareCopy()`
71 assigned_: undefined,

chore: let's test before publishMichel Weststratebefore adoption3f9a94e

lines 72–81why, one step back
72 // The parent draft state.
73 parent_: parent,74 // The base state.75 base_: base,76 // The base proxy.77 draft_: null as any, // set below78 // The base copy with any updated values.79 copy_: null,80 // Called by the `produce` function.81 revoke_: null as any,

perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202

lines 82–84why, one step back
82 isManual_: false,
83 // `callbacks` actually gets assigned in `createProxy`84 callbacks_: undefined as any

chore: let's test before publishMichel Weststratebefore adoption3f9a94e

lines 85–94why, one step back
85 }
8687 // the traps must target something, a bit like the 'real' base.88 // but also, we need to be able to determine from the target what the relevant state is89 // (to avoid creating traps per instance to capture the state in closure,90 // and to avoid creating weird hidden properties as well)91 // So the trick is to use 'state' as the actual 'target'! (and make sure we intercept everything)92 // Note that in the case of an array, we put the state in an array to have better Reflect defaults ootb93 let target: T = state as any94 let traps: ProxyHandler<object | Array<any>> = objectTraps

perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202

line 95why, one step back
95 if (baseIsArray) {

chore: let's test before publishMichel Weststratebefore adoption3f9a94e

lines 96–102why, one step back
96 target = [state] as any
97 traps = arrayTraps98 }99100 const {revoke, proxy} = Proxy.revocable(target, traps)101 state.draft_ = proxy as any102 state.revoke_ = revoke

perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202

line 103why, one step back
103 return [proxy as any, state]

chore: let's test before publishMichel Weststratebefore adoption3f9a94e

lines 104–112why, one step back
104}
105106/**107 * Object drafts108 */109export const objectTraps: ProxyHandler<ProxyState> = {110 get(state, prop) {111 if (prop === DRAFT_STATE) return state112

feat: Override array methods to avoid proxy creation while iterating and updating (#1184)Mark Eriksonbefore adoptiond38a9d0

lines 113–123why, one step back
113 let arrayPlugin = state.scope_.arrayMethodsPlugin_
114 const isArrayWithStringProp =115 state.type_ === ArchType.Array && typeof prop === "string"116 // Intercept array methods so that we can override117 // behavior and skip proxy creation for perf118 if (isArrayWithStringProp) {119 if (arrayPlugin?.isArrayOperationMethod(prop)) {120 return arrayPlugin.createMethodInterceptor(state, prop)121 }122 }123

chore: let's test before publishMichel Weststratebefore adoption3f9a94e

line 124why, one step back
124 const source = latest(state)

perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202

line 125why, one step back
125 if (!has(source, prop, state.type_)) {

chore: let's test before publishMichel Weststratebefore adoption3f9a94e

lines 126–130why, one step back
126 // non-existing or non-own property...
127 return readPropFromProto(state, source, prop)128 }129 const value = source[prop]130 if (state.finalized_ || !isDraftable(value)) {

feat: Override array methods to avoid proxy creation while iterating and updating (#1184)Mark Eriksonbefore adoptiond38a9d0

lines 131–144why, one step back
131 return value
132 }133134 // During mutating array operations, defer proxy creation for array elements135 // This optimization avoids creating unnecessary proxies during sort/reverse136 if (137 isArrayWithStringProp &&138 (state as ProxyArrayState).operationMethod &&139 arrayPlugin?.isMutatingArrayMethod(140 (state as ProxyArrayState).operationMethod!141 ) &&142 isArrayIndex(prop)143 ) {144 // Return raw value during mutating operations, create proxy only if modified

chore: let's test before publishMichel Weststratebefore adoption3f9a94e

lines 145–150why, one step back
145 return value
146 }147 // Check for existing draft in modified state.148 // Assigned values are never drafted. This catches any drafts we created, too.149 if (value === peek(state.base_, prop)) {150 prepareCopy(state)

perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202

lines 151–155why, one step back
151 // Ensure array keys are always numbers
152 const childKey = state.type_ === ArchType.Array ? +(prop as string) : prop153 const childDraft = createProxy(state.scope_, value, state, childKey)154155 return (state.copy_![childKey] = childDraft)

chore: let's test before publishMichel Weststratebefore adoption3f9a94e

lines 156–184why, one step back
156 }
157 return value158 },159 has(state, prop) {160 return prop in latest(state)161 },162 ownKeys(state) {163 return Reflect.ownKeys(latest(state))164 },165 set(166 state: ProxyObjectState,167 prop: string /* strictly not, but helps TS */,168 value169 ) {170 const desc = getDescriptorFromProto(latest(state), prop)171 if (desc?.set) {172 // special case: if this write is captured by a setter, we have173 // to trigger it with the correct context174 desc.set.call(state.draft_, value)175 return true176 }177 if (!state.modified_) {178 // the last check is because we need to be able to distinguish setting a non-existing to undefined (which is a change)179 // from setting an existing property with value undefined to undefined (which is not a change)180 const current = peek(latest(state), prop)181 // special case, if we assigning the original value to a draft, we can ignore the assignment182 const currentState: ProxyObjectState = current?.[DRAFT_STATE]183 if (currentState && currentState.base_ === value) {184 state.copy_![prop] = value

perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202

line 185why, one step back
185 state.assigned_!.set(prop, false)

chore: let's test before publishMichel Weststratebefore adoption3f9a94e

lines 186–187why, one step back
186 return true
187 }

perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202

lines 188–191why, one step back
188 if (
189 is(value, current) &&190 (value !== undefined || has(state.base_, prop, state.type_))191 )

chore: let's test before publishMichel Weststratebefore adoption3f9a94e

lines 192–197why, one step back
192 return true
193 prepareCopy(state)194 markChanged(state)195 }196197 if (

fix: special case NaN in setter (#912)Raybefore adoption5721bb7

lines 198–200why, one step back
198 (state.copy_![prop] === value &&
199 // special case: handle new props with value 'undefined'200 (value !== undefined || prop in state.copy_)) ||

chore: let's test before publishMichel Weststratebefore adoption3f9a94e

line 201why, one step back
201 // special case: NaN

fix: special case NaN in setter (#912)Raybefore adoption5721bb7

line 202why, one step back
202 (Number.isNaN(value) && Number.isNaN(state.copy_![prop]))

chore: let's test before publishMichel Weststratebefore adoption3f9a94e

lines 203–207why, one step back
203 )
204 return true205206 // @ts-ignore207 state.copy_![prop] = value

perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202

lines 208–210why, one step back
208 state.assigned_!.set(prop, true)
209210 handleCrossReference(state, prop, value)

chore: let's test before publishMichel Weststratebefore adoption3f9a94e

lines 211–213why, one step back
211 return true
212 },213 deleteProperty(state, prop: string) {

perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202

line 214why, one step back
214 prepareCopy(state)

chore: let's test before publishMichel Weststratebefore adoption3f9a94e

lines 215–216why, one step back
215 // The `undefined` check is a fast path for pre-existing keys.
216 if (peek(state.base_, prop) !== undefined || prop in state.base_) {

perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202

line 217why, one step back
217 state.assigned_!.set(prop, false)

chore: let's test before publishMichel Weststratebefore adoption3f9a94e

lines 218–220why, one step back
218 markChanged(state)
219 } else {220 // if an originally not assigned property was deleted

perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202

line 221why, one step back
221 state.assigned_!.delete(prop)

chore: let's test before publishMichel Weststratebefore adoption3f9a94e

line 222why, one step back
222 }

Merge pull request #1028 from immerjs/immer-10Michel Weststratebefore adoption2ef9a42

lines 223–225why, one step back
223 if (state.copy_) {
224 delete state.copy_[prop]225 }

chore: let's test before publishMichel Weststratebefore adoption3f9a94e

lines 226–234why, one step back
226 return true
227 },228 // Note: We never coerce `desc.value` into an Immer draft, because we can't make229 // the same guarantee in ES5 mode.230 getOwnPropertyDescriptor(state, prop) {231 const owner = latest(state)232 const desc = Reflect.getOwnPropertyDescriptor(owner, prop)233 if (!desc) return desc234 return {

perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202

lines 235–238why, one step back
235 [WRITABLE]: true,
236 [CONFIGURABLE]: state.type_ !== ArchType.Array || prop !== "length",237 [ENUMERABLE]: desc[ENUMERABLE],238 [VALUE]: owner[prop]

chore: let's test before publishMichel Weststratebefore adoption3f9a94e

lines 239–244why, one step back
239 }
240 },241 defineProperty() {242 die(11)243 },244 getPrototypeOf(state) {

Merge pull request #1028 from immerjs/immer-10Michel Weststratebefore adoption2ef9a42

line 245why, one step back
245 return getPrototypeOf(state.base_)

chore: let's test before publishMichel Weststratebefore adoption3f9a94e

lines 246–256why, one step back
246 },
247 setPrototypeOf() {248 die(12)249 }250}251252/**253 * Array drafts254 */255256const arrayTraps: ProxyHandler<[ProxyArrayState]> = {}

fix: Fix broken array patching and ensure all values in draft Maps/Sets are finalized (#1201)Mark Eriksonbefore adoptionb208d58

lines 257–260why, one step back
257// Use `for..in` instead of `each` to work around a weird
258// prod test suite issue259for (let key in objectTraps) {260 let fn = objectTraps[key as keyof typeof objectTraps] as Function

chore: let's test before publishMichel Weststratebefore adoption3f9a94e

lines 261–262why, one step back
261 // @ts-ignore
262 arrayTraps[key] = function() {

perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202

lines 263–265why, one step back
263 const args = arguments
264 args[0] = args[0][0]265 return fn.apply(this, args)

chore: let's test before publishMichel Weststratebefore adoption3f9a94e

line 266why, one step back
266 }

fix: Fix broken array patching and ensure all values in draft Maps/Sets are finalized (#1201)Mark Eriksonbefore adoptionb208d58

line 267why, one step back
267}

chore: let's test before publishMichel Weststratebefore adoption3f9a94e

line 268why, one step back
268arrayTraps.deleteProperty = function(state, prop) {

Merge pull request #1028 from immerjs/immer-10Michel Weststratebefore adoption2ef9a42

lines 269–270why, one step back
269 if (process.env.NODE_ENV !== "production" && isNaN(parseInt(prop as any)))
270 die(13)

fix: incorrect patches for `delete` on arrays. Fixes #879Michel Weststratebefore adoptiond91a659

lines 271–272why, one step back
271 // @ts-ignore
272 return arrayTraps.set!.call(this, state, prop, undefined)

chore: let's test before publishMichel Weststratebefore adoption3f9a94e

lines 273–274why, one step back
273}
274arrayTraps.set = function(state, prop, value) {

Merge pull request #1028 from immerjs/immer-10Michel Weststratebefore adoption2ef9a42

lines 275–280why, one step back
275 if (
276 process.env.NODE_ENV !== "production" &&277 prop !== "length" &&278 isNaN(parseInt(prop as any))279 )280 die(14)

chore: let's test before publishMichel Weststratebefore adoption3f9a94e

lines 281–293why, one step back
281 return objectTraps.set!.call(this, state[0], prop, value, state[0])
282}283284// Access a property without creating an Immer draft.285function peek(draft: Drafted, prop: PropertyKey) {286 const state = draft[DRAFT_STATE]287 const source = state ? latest(state) : draft288 return source[prop]289}290291function readPropFromProto(state: ImmerState, source: any, prop: PropertyKey) {292 const desc = getDescriptorFromProto(source, prop)293 return desc

perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202

lines 294–295why, one step back
294 ? VALUE in desc
295 ? desc[VALUE]

chore: let's test before publishMichel Weststratebefore adoption3f9a94e

lines 296–307why, one step back
296 : // This is a very special case, if the prop is a getter defined by the
297 // prototype, we should invoke it with the draft as context!298 desc.get?.call(state.draft_)299 : undefined300}301302function getDescriptorFromProto(303 source: any,304 prop: PropertyKey305): PropertyDescriptor | undefined {306 // 'in' checks proto!307 if (!(prop in source)) return undefined

Merge pull request #1028 from immerjs/immer-10Michel Weststratebefore adoption2ef9a42

line 308why, one step back
308 let proto = getPrototypeOf(source)

chore: let's test before publishMichel Weststratebefore adoption3f9a94e

lines 309–311why, one step back
309 while (proto) {
310 const desc = Object.getOwnPropertyDescriptor(proto, prop)311 if (desc) return desc

Merge pull request #1028 from immerjs/immer-10Michel Weststratebefore adoption2ef9a42

line 312why, one step back
312 proto = getPrototypeOf(proto)

chore: let's test before publishMichel Weststratebefore adoption3f9a94e

lines 313–325why, one step back
313 }
314 return undefined315}316317export function markChanged(state: ImmerState) {318 if (!state.modified_) {319 state.modified_ = true320 if (state.parent_) {321 markChanged(state.parent_)322 }323 }324}325

perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202

line 326why, one step back
326export function prepareCopy(state: ImmerState) {

chore: let's test before publishMichel Weststratebefore adoption3f9a94e

line 327why, one step back
327 if (!state.copy_) {

perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202

lines 328–330why, one step back
328 // Actually create the `assigned_` map now that we
329 // know this is a modified draft.330 state.assigned_ = new Map()

Merge pull request #1028 from immerjs/immer-10Michel Weststratebefore adoption2ef9a42

lines 331–334why, one step back
331 state.copy_ = shallowCopy(
332 state.base_,333 state.scope_.immer_.useStrictShallowCopy_334 )

chore: let's test before publishMichel Weststratebefore adoption3f9a94e

lines 335–336why, one step back
335 }
336}