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 fileTake 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 back1import {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 back14 getPrototypeOf,chore(test): fix production build unit testsMichel Weststratebefore adoption07f5cc9
lines 15–17why, one step back15 DRAFT_STATE,16 die,17 createProxy,Merge pull request #1028 from immerjs/immer-10Michel Weststratebefore adoption2ef9a42
line 18why, one step back18 ArchType,perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202
lines 19–23why, one step back19 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 back24 isArray,25 isArrayIndexchore(test): fix production build unit testsMichel Weststratebefore adoption07f5cc9
lines 26–33why, one step back26} 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 back34 type_: ArchType.Objectchore(test): fix production build unit testsMichel Weststratebefore adoption07f5cc9
lines 35–40why, one step back35 base_: any36 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 back41 type_: ArchType.Arraychore(test): fix production build unit testsMichel Weststratebefore adoption07f5cc9
lines 42–44why, one step back42 base_: AnyArray43 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 back45 operationMethod?: string46 allIndicesReassigned_?: booleanfix: draft relocated base refs after reverse/sort in array-methods plugin (#1255)spokodevbefore adoptiona73672a
line 47why, one step back47 baseRefs_?: Set<any>chore(test): fix production build unit testsMichel Weststratebefore adoption07f5cc9
lines 48–59why, one step back48}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?: ImmerStateperf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202
lines 60–61why, one step back60): [Drafted<T, ProxyState>, ProxyState] {61 const baseIsArray = isArray(base)chore(test): fix production build unit testsMichel Weststratebefore adoption07f5cc9
line 62why, one step back62 const state: ProxyState = {perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202
line 63why, one step back63 type_: baseIsArray ? ArchType.Array : (ArchType.Object as any),chore(test): fix production build unit testsMichel Weststratebefore adoption07f5cc9
lines 64–70why, one step back64 // 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 back71 // actually instantiated in `prepareCopy()`72 assigned_: undefined,chore(test): fix production build unit testsMichel Weststratebefore adoption07f5cc9
lines 73–82why, one step back73 // 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 back83 isManual_: false,84 // `callbacks` actually gets assigned in `createProxy`85 callbacks_: undefined as anychore(test): fix production build unit testsMichel Weststratebefore adoption07f5cc9
lines 86–95why, one step back86 }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>> = objectTrapsperf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202
line 96why, one step back96 if (baseIsArray) {chore(test): fix production build unit testsMichel Weststratebefore adoption07f5cc9
lines 97–103why, one step back97 target = [state] as any98 traps = arrayTraps99 }100101 const {revoke, proxy} = Proxy.revocable(target, traps)102 state.draft_ = proxy as any103 state.revoke_ = revokeperf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202
line 104why, one step back104 return [proxy as any, state]chore(test): fix production build unit testsMichel Weststratebefore adoption07f5cc9
lines 105–113why, one step back105}106107/**108 * Object drafts109 */110export const objectTraps: ProxyHandler<ProxyState> = {111 get(state, prop) {112 if (prop === DRAFT_STATE) return state113feat: Override array methods to avoid proxy creation while iterating and updating (#1184)Mark Eriksonbefore adoptiond38a9d0
lines 114–124why, one step back114 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 }124chore(test): fix production build unit testsMichel Weststratebefore adoption07f5cc9
line 125why, one step back125 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 back126 if (!has(source, prop, state.type_)) {chore(test): fix production build unit testsMichel Weststratebefore adoption07f5cc9
lines 127–131why, one step back127 // 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 back132 return value133 }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 modifiedchore(test): fix production build unit testsMichel Weststratebefore adoption07f5cc9
lines 146–149why, one step back146 return value147 }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 back150 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 back154 prepareCopy(state)perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202
lines 155–159why, one step back155 // Ensure array keys are always numbers156 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 back160 }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] = valuefix: do not record a deletion when a base value is written back (#1295)Bao Nguyenbefore adoption02e87e7
lines 189–191why, one step back189 // The property still holds its base value, so nothing was assigned190 // 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 back192 return true193 }perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202
lines 194–197why, one step back194 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 back198 return true199 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 back206 (value !== undefined || has(state.copy_, prop, state.type_))) ||chore(test): fix production build unit testsMichel Weststratebefore adoption07f5cc9
lines 207–213why, one step back207 // special case: NaN208 (Number.isNaN(value) && Number.isNaN(state.copy_![prop]))209 )210 return true211212 // @ts-ignore213 state.copy_![prop] = valueperf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202
lines 214–216why, one step back214 state.assigned_!.set(prop, true)215216 handleCrossReference(state, prop, value)chore(test): fix production build unit testsMichel Weststratebefore adoption07f5cc9
lines 217–219why, one step back217 return true218 },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 back220 prepareCopy(state)chore(test): fix production build unit testsMichel Weststratebefore adoption07f5cc9
lines 221–222why, one step back221 // 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 back223 state.assigned_!.set(prop, false)chore(test): fix production build unit testsMichel Weststratebefore adoption07f5cc9
lines 224–226why, one step back224 markChanged(state)225 } else {226 // if an originally not assigned property was deletedperf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202
line 227why, one step back227 state.assigned_!.delete(prop)chore(test): fix production build unit testsMichel Weststratebefore adoption07f5cc9
line 228why, one step back228 }Merge pull request #1028 from immerjs/immer-10Michel Weststratebefore adoption2ef9a42
lines 229–231why, one step back229 if (state.copy_) {230 delete state.copy_[prop]231 }chore(test): fix production build unit testsMichel Weststratebefore adoption07f5cc9
lines 232–240why, one step back232 return true233 },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 back241 [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 back245 }246 },247 defineProperty() {248 die(11)249 },250 getPrototypeOf(state) {Merge pull request #1028 from immerjs/immer-10Michel Weststratebefore adoption2ef9a42
line 251why, one step back251 return getPrototypeOf(state.base_)chore(test): fix production build unit testsMichel Weststratebefore adoption07f5cc9
lines 252–262why, one step back252 },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 back263// Use `for..in` instead of `each` to work around a weird264// prod test suite issue265for (let key in objectTraps) {266 let fn = objectTraps[key as keyof typeof objectTraps] as Functionchore(test): fix production build unit testsMichel Weststratebefore adoption07f5cc9
line 267why, one step back267 // @ts-ignorechore: Merge branch 'unional-prettier'Michel Weststratebefore adoption37eaf8f
line 268why, one step back268 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 back269 const args = arguments270 args[0] = args[0][0]271 return fn.apply(this, args)chore(test): fix production build unit testsMichel Weststratebefore adoption07f5cc9
line 272why, one step back272 }fix: Fix broken array patching and ensure all values in draft Maps/Sets are finalized (#1201)Mark Eriksonbefore adoptionb208d58
line 273why, one step back273}chore: Merge branch 'unional-prettier'Michel Weststratebefore adoption37eaf8f
line 274why, one step back274arrayTraps.deleteProperty = function (state, prop) {Merge pull request #1028 from immerjs/immer-10Michel Weststratebefore adoption2ef9a42
lines 275–276why, one step back275 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 back277 // @ts-ignore278 return arrayTraps.set!.call(this, state, prop, undefined)279}chore: Merge branch 'unional-prettier'Michel Weststratebefore adoption37eaf8f
line 280why, one step back280arrayTraps.set = function (state, prop, value) {Merge pull request #1028 from immerjs/immer-10Michel Weststratebefore adoption2ef9a42
lines 281–286why, one step back281 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 back287 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 back295}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 back314}315316function readPropFromProto(state: ImmerState, source: any, prop: PropertyKey) {317 const desc = getDescriptorFromProto(source, prop)318 return descperf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202
lines 319–320why, one step back319 ? VALUE in desc320 ? desc[VALUE]chore(test): fix production build unit testsMichel Weststratebefore adoption07f5cc9
line 321why, one step back321 : // This is a very special case, if the prop is a getter defined by thechore: Merge branch 'unional-prettier'Michel Weststratebefore adoption37eaf8f
lines 322–323why, one step back322 // 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 back324 : undefined325}326327function getDescriptorFromProto(328 source: any,329 prop: PropertyKey330): PropertyDescriptor | undefined {331 // 'in' checks proto!332 if (!(prop in source)) return undefinedMerge pull request #1028 from immerjs/immer-10Michel Weststratebefore adoption2ef9a42
line 333why, one step back333 let proto = getPrototypeOf(source)chore(test): fix production build unit testsMichel Weststratebefore adoption07f5cc9
lines 334–336why, one step back334 while (proto) {335 const desc = Object.getOwnPropertyDescriptor(proto, prop)336 if (desc) return descMerge pull request #1028 from immerjs/immer-10Michel Weststratebefore adoption2ef9a42
line 337why, one step back337 proto = getPrototypeOf(proto)chore(test): fix production build unit testsMichel Weststratebefore adoption07f5cc9
lines 338–350why, one step back338 }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}350perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202
line 351why, one step back351export function prepareCopy(state: ImmerState) {chore(test): fix production build unit testsMichel Weststratebefore adoption07f5cc9
line 352why, one step back352 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 back353 // Actually create the `assigned_` map now that we354 // 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 back356 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 back360 }361}