Skip to content
Myr

proxy.ts

This file

Path

src/core/proxy.ts

361 lines · 10.2 KiB · TypeScript

Last changed by

fix: do not record a deletion when a base value is written back (#1295)Bao Nguyenbefore adoption02e87e7

History of this file

Take it

The walk stopped after 200 commits: lines older than 07f5cc9 point at it.

chore(test): fix production build unit testsMichel Weststratebefore adoption07f5cc9

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(test): fix production build unit testsMichel Weststratebefore adoption07f5cc9

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(test): fix production build unit testsMichel Weststratebefore adoption07f5cc9

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(test): fix production build unit testsMichel Weststratebefore adoption07f5cc9

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(test): fix production build unit testsMichel Weststratebefore adoption07f5cc9

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

fix: draft relocated base refs after reverse/sort in array-methods plugin (#1255)spokodevbefore adoptiona73672a

line 47why, one step back
47 baseRefs_?: Set<any>

chore(test): fix production build unit testsMichel Weststratebefore adoption07f5cc9

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

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

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

chore(test): fix production build unit testsMichel Weststratebefore adoption07f5cc9

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

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

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

chore(test): fix production build unit testsMichel Weststratebefore adoption07f5cc9

lines 64–70why, one step back
64 // Track which produce call this is associated with.
65 scope_: parent ? parent.scope_ : getCurrentScope()!,66 // True for both shallow and deep changes.67 modified_: false,68 // Used during finalization.69 finalized_: false,70 // 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 71–72why, one step back
71 // actually instantiated in `prepareCopy()`
72 assigned_: undefined,

chore(test): fix production build unit testsMichel Weststratebefore adoption07f5cc9

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

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

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

chore(test): fix production build unit testsMichel Weststratebefore adoption07f5cc9

lines 86–95why, one step back
86 }
8788 // the traps must target something, a bit like the 'real' base.89 // but also, we need to be able to determine from the target what the relevant state is90 // (to avoid creating traps per instance to capture the state in closure,91 // and to avoid creating weird hidden properties as well)92 // So the trick is to use 'state' as the actual 'target'! (and make sure we intercept everything)93 // Note that in the case of an array, we put the state in an array to have better Reflect defaults ootb94 let target: T = state as any95 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 96why, one step back
96 if (baseIsArray) {

chore(test): fix production build unit testsMichel Weststratebefore adoption07f5cc9

lines 97–103why, one step back
97 target = [state] as any
98 traps = arrayTraps99 }100101 const {revoke, proxy} = Proxy.revocable(target, traps)102 state.draft_ = proxy as any103 state.revoke_ = revoke

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

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

chore(test): fix production build unit testsMichel Weststratebefore adoption07f5cc9

lines 105–113why, one step back
105}
106107/**108 * Object drafts109 */110export const objectTraps: ProxyHandler<ProxyState> = {111 get(state, prop) {112 if (prop === DRAFT_STATE) return state113

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

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

chore(test): fix production build unit testsMichel Weststratebefore adoption07f5cc9

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

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

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

chore(test): fix production build unit testsMichel Weststratebefore adoption07f5cc9

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

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

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

chore(test): fix production build unit testsMichel Weststratebefore adoption07f5cc9

lines 146–149why, one step back
146 return value
147 }148 // Check for existing draft in modified state.149 // Assigned values are never drafted. This catches any drafts we created, too.

fix: draft relocated base refs after reverse/sort in array-methods plugin (#1255)spokodevbefore adoptiona73672a

lines 150–153why, one step back
150 if (
151 value === peek(state.base_, prop) ||152 isRelocatedBaseRef(state, prop, value)153 ) {

chore(test): fix production build unit testsMichel Weststratebefore adoption07f5cc9

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

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

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

chore(test): fix production build unit testsMichel Weststratebefore adoption07f5cc9

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

fix: do not record a deletion when a base value is written back (#1295)Bao Nguyenbefore adoption02e87e7

lines 189–191why, one step back
189 // The property still holds its base value, so nothing was assigned
190 // and nothing was deleted. `false` here reads as a deletion later.191 state.assigned_!.delete(prop)

chore(test): fix production build unit testsMichel Weststratebefore adoption07f5cc9

lines 192–193why, one step back
192 return true
193 }

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

lines 194–197why, one step back
194 if (
195 is(value, current) &&196 (value !== undefined || has(state.base_, prop, state.type_))197 )

chore(test): fix production build unit testsMichel Weststratebefore adoption07f5cc9

lines 198–205why, one step back
198 return true
199 prepareCopy(state)200 markChanged(state)201 }202203 if (204 (state.copy_![prop] === value &&205 // special case: handle new props with value 'undefined'

fix: undefined assigned to a prototype-inherited key gets dropped (#1262)Alexander Kireyevbefore adoption16e225b

line 206why, one step back
206 (value !== undefined || has(state.copy_, prop, state.type_))) ||

chore(test): fix production build unit testsMichel Weststratebefore adoption07f5cc9

lines 207–213why, one step back
207 // special case: NaN
208 (Number.isNaN(value) && Number.isNaN(state.copy_![prop]))209 )210 return true211212 // @ts-ignore213 state.copy_![prop] = value

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

lines 214–216why, one step back
214 state.assigned_!.set(prop, true)
215216 handleCrossReference(state, prop, value)

chore(test): fix production build unit testsMichel Weststratebefore adoption07f5cc9

lines 217–219why, one step back
217 return true
218 },219 deleteProperty(state, prop: string) {

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

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

chore(test): fix production build unit testsMichel Weststratebefore adoption07f5cc9

lines 221–222why, one step back
221 // The `undefined` check is a fast path for pre-existing keys.
222 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 223why, one step back
223 state.assigned_!.set(prop, false)

chore(test): fix production build unit testsMichel Weststratebefore adoption07f5cc9

lines 224–226why, one step back
224 markChanged(state)
225 } else {226 // 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 227why, one step back
227 state.assigned_!.delete(prop)

chore(test): fix production build unit testsMichel Weststratebefore adoption07f5cc9

line 228why, one step back
228 }

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

lines 229–231why, one step back
229 if (state.copy_) {
230 delete state.copy_[prop]231 }

chore(test): fix production build unit testsMichel Weststratebefore adoption07f5cc9

lines 232–240why, one step back
232 return true
233 },234 // Note: We never coerce `desc.value` into an Immer draft, because we can't make235 // the same guarantee in ES5 mode.236 getOwnPropertyDescriptor(state, prop) {237 const owner = latest(state)238 const desc = Reflect.getOwnPropertyDescriptor(owner, prop)239 if (!desc) return desc240 return {

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

lines 241–244why, one step back
241 [WRITABLE]: true,
242 [CONFIGURABLE]: state.type_ !== ArchType.Array || prop !== "length",243 [ENUMERABLE]: desc[ENUMERABLE],244 [VALUE]: owner[prop]

chore(test): fix production build unit testsMichel Weststratebefore adoption07f5cc9

lines 245–250why, one step back
245 }
246 },247 defineProperty() {248 die(11)249 },250 getPrototypeOf(state) {

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

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

chore(test): fix production build unit testsMichel Weststratebefore adoption07f5cc9

lines 252–262why, one step back
252 },
253 setPrototypeOf() {254 die(12)255 }256}257258/**259 * Array drafts260 */261262const arrayTraps: ProxyHandler<[ProxyArrayState]> = {}

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

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

chore(test): fix production build unit testsMichel Weststratebefore adoption07f5cc9

line 267why, one step back
267 // @ts-ignore

chore: Merge branch 'unional-prettier'Michel Weststratebefore adoption37eaf8f

line 268why, one step back
268 arrayTraps[key] = function () {

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

lines 269–271why, one step back
269 const args = arguments
270 args[0] = args[0][0]271 return fn.apply(this, args)

chore(test): fix production build unit testsMichel Weststratebefore adoption07f5cc9

line 272why, one step back
272 }

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

line 273why, one step back
273}

chore: Merge branch 'unional-prettier'Michel Weststratebefore adoption37eaf8f

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

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

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

chore(test): fix production build unit testsMichel Weststratebefore adoption07f5cc9

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

chore: Merge branch 'unional-prettier'Michel Weststratebefore adoption37eaf8f

line 280why, one step back
280arrayTraps.set = function (state, prop, value) {

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

lines 281–286why, one step back
281 if (
282 process.env.NODE_ENV !== "production" &&283 prop !== "length" &&284 isNaN(parseInt(prop as any))285 )286 die(14)

chore(test): fix production build unit testsMichel Weststratebefore adoption07f5cc9

lines 287–294why, one step back
287 return objectTraps.set!.call(this, state[0], prop, value, state[0])
288}289290// Access a property without creating an Immer draft.291function peek(draft: Drafted, prop: PropertyKey) {292 const state = draft[DRAFT_STATE]293 const source = state ? latest(state) : draft294 return source[prop]

fix: draft relocated base refs after reverse/sort in array-methods plugin (#1255)spokodevbefore adoptiona73672a

lines 295–313why, one step back
295}
296297// Reordering array methods (reverse, sort) from the array-methods plugin run298// natively on `copy_`, which still holds raw base references. This relocates an299// un-drafted base object to a position where it no longer matches `base_[prop]`,300// so the normal positional check above misses it and the get trap would hand back301// the raw base object, breaking the guarantee that the base state is never mutated.302// Detect such a relocated base reference so it is drafted before being exposed.303function isRelocatedBaseRef(state: ImmerState, prop: PropertyKey, value: any) {304 if (305 state.type_ !== ArchType.Array ||306 !(state as ProxyArrayState).allIndicesReassigned_ ||307 state.assigned_?.get(prop) ||308 !isDraftable(value) ||309 value[DRAFT_STATE]310 ) {311 return false312 }313 return (state as ProxyArrayState).baseRefs_!.has(value)

chore(test): fix production build unit testsMichel Weststratebefore adoption07f5cc9

lines 314–318why, one step back
314}
315316function readPropFromProto(state: ImmerState, source: any, prop: PropertyKey) {317 const desc = getDescriptorFromProto(source, prop)318 return desc

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

lines 319–320why, one step back
319 ? VALUE in desc
320 ? desc[VALUE]

chore(test): fix production build unit testsMichel Weststratebefore adoption07f5cc9

line 321why, one step back
321 : // This is a very special case, if the prop is a getter defined by the

chore: Merge branch 'unional-prettier'Michel Weststratebefore adoption37eaf8f

lines 322–323why, one step back
322 // prototype, we should invoke it with the draft as context!
323 desc.get?.call(state.draft_)

chore(test): fix production build unit testsMichel Weststratebefore adoption07f5cc9

lines 324–332why, one step back
324 : undefined
325}326327function getDescriptorFromProto(328 source: any,329 prop: PropertyKey330): PropertyDescriptor | undefined {331 // 'in' checks proto!332 if (!(prop in source)) return undefined

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

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

chore(test): fix production build unit testsMichel Weststratebefore adoption07f5cc9

lines 334–336why, one step back
334 while (proto) {
335 const desc = Object.getOwnPropertyDescriptor(proto, prop)336 if (desc) return desc

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

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

chore(test): fix production build unit testsMichel Weststratebefore adoption07f5cc9

lines 338–350why, one step back
338 }
339 return undefined340}341342export function markChanged(state: ImmerState) {343 if (!state.modified_) {344 state.modified_ = true345 if (state.parent_) {346 markChanged(state.parent_)347 }348 }349}350

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

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

chore(test): fix production build unit testsMichel Weststratebefore adoption07f5cc9

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

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

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

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

lines 356–359why, one step back
356 state.copy_ = shallowCopy(
357 state.base_,358 state.scope_.immer_.useStrictShallowCopy_359 )

chore(test): fix production build unit testsMichel Weststratebefore adoption07f5cc9

lines 360–361why, one step back
360 }
361}