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 fileTake 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 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: let's test before publishMichel Weststratebefore adoption3f9a94e
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: let's test before publishMichel Weststratebefore adoption3f9a94e
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: let's test before publishMichel Weststratebefore adoption3f9a94e
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: let's test before publishMichel Weststratebefore adoption3f9a94e
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_?: booleanchore: let's test before publishMichel Weststratebefore adoption3f9a94e
lines 47–58why, one step back47}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?: ImmerStateperf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202
lines 59–60why, one step back59): [Drafted<T, ProxyState>, ProxyState] {60 const baseIsArray = isArray(base)chore: let's test before publishMichel Weststratebefore adoption3f9a94e
line 61why, one step back61 const state: ProxyState = {perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202
line 62why, one step back62 type_: baseIsArray ? ArchType.Array : (ArchType.Object as any),chore: let's test before publishMichel Weststratebefore adoption3f9a94e
lines 63–69why, one step back63 // 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 back70 // actually instantiated in `prepareCopy()`71 assigned_: undefined,chore: let's test before publishMichel Weststratebefore adoption3f9a94e
lines 72–81why, one step back72 // 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 back82 isManual_: false,83 // `callbacks` actually gets assigned in `createProxy`84 callbacks_: undefined as anychore: let's test before publishMichel Weststratebefore adoption3f9a94e
lines 85–94why, one step back85 }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>> = objectTrapsperf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202
line 95why, one step back95 if (baseIsArray) {chore: let's test before publishMichel Weststratebefore adoption3f9a94e
lines 96–102why, one step back96 target = [state] as any97 traps = arrayTraps98 }99100 const {revoke, proxy} = Proxy.revocable(target, traps)101 state.draft_ = proxy as any102 state.revoke_ = revokeperf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202
line 103why, one step back103 return [proxy as any, state]chore: let's test before publishMichel Weststratebefore adoption3f9a94e
lines 104–112why, one step back104}105106/**107 * Object drafts108 */109export const objectTraps: ProxyHandler<ProxyState> = {110 get(state, prop) {111 if (prop === DRAFT_STATE) return state112feat: Override array methods to avoid proxy creation while iterating and updating (#1184)Mark Eriksonbefore adoptiond38a9d0
lines 113–123why, one step back113 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 }123chore: let's test before publishMichel Weststratebefore adoption3f9a94e
line 124why, one step back124 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 back125 if (!has(source, prop, state.type_)) {chore: let's test before publishMichel Weststratebefore adoption3f9a94e
lines 126–130why, one step back126 // 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 back131 return value132 }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 modifiedchore: let's test before publishMichel Weststratebefore adoption3f9a94e
lines 145–150why, one step back145 return value146 }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 back151 // Ensure array keys are always numbers152 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 back156 }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] = valueperf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202
line 185why, one step back185 state.assigned_!.set(prop, false)chore: let's test before publishMichel Weststratebefore adoption3f9a94e
lines 186–187why, one step back186 return true187 }perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202
lines 188–191why, one step back188 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 back192 return true193 prepareCopy(state)194 markChanged(state)195 }196197 if (fix: special case NaN in setter (#912)Raybefore adoption5721bb7
lines 198–200why, one step back198 (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 back201 // special case: NaNfix: special case NaN in setter (#912)Raybefore adoption5721bb7
line 202why, one step back202 (Number.isNaN(value) && Number.isNaN(state.copy_![prop]))chore: let's test before publishMichel Weststratebefore adoption3f9a94e
lines 203–207why, one step back203 )204 return true205206 // @ts-ignore207 state.copy_![prop] = valueperf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202
lines 208–210why, one step back208 state.assigned_!.set(prop, true)209210 handleCrossReference(state, prop, value)chore: let's test before publishMichel Weststratebefore adoption3f9a94e
lines 211–213why, one step back211 return true212 },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 back214 prepareCopy(state)chore: let's test before publishMichel Weststratebefore adoption3f9a94e
lines 215–216why, one step back215 // 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 back217 state.assigned_!.set(prop, false)chore: let's test before publishMichel Weststratebefore adoption3f9a94e
lines 218–220why, one step back218 markChanged(state)219 } else {220 // 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 221why, one step back221 state.assigned_!.delete(prop)chore: let's test before publishMichel Weststratebefore adoption3f9a94e
line 222why, one step back222 }Merge pull request #1028 from immerjs/immer-10Michel Weststratebefore adoption2ef9a42
lines 223–225why, one step back223 if (state.copy_) {224 delete state.copy_[prop]225 }chore: let's test before publishMichel Weststratebefore adoption3f9a94e
lines 226–234why, one step back226 return true227 },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 back235 [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 back239 }240 },241 defineProperty() {242 die(11)243 },244 getPrototypeOf(state) {Merge pull request #1028 from immerjs/immer-10Michel Weststratebefore adoption2ef9a42
line 245why, one step back245 return getPrototypeOf(state.base_)chore: let's test before publishMichel Weststratebefore adoption3f9a94e
lines 246–256why, one step back246 },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 back257// Use `for..in` instead of `each` to work around a weird258// prod test suite issue259for (let key in objectTraps) {260 let fn = objectTraps[key as keyof typeof objectTraps] as Functionchore: let's test before publishMichel Weststratebefore adoption3f9a94e
lines 261–262why, one step back261 // @ts-ignore262 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 back263 const args = arguments264 args[0] = args[0][0]265 return fn.apply(this, args)chore: let's test before publishMichel Weststratebefore adoption3f9a94e
line 266why, one step back266 }fix: Fix broken array patching and ensure all values in draft Maps/Sets are finalized (#1201)Mark Eriksonbefore adoptionb208d58
line 267why, one step back267}chore: let's test before publishMichel Weststratebefore adoption3f9a94e
line 268why, one step back268arrayTraps.deleteProperty = function(state, prop) {Merge pull request #1028 from immerjs/immer-10Michel Weststratebefore adoption2ef9a42
lines 269–270why, one step back269 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 back271 // @ts-ignore272 return arrayTraps.set!.call(this, state, prop, undefined)chore: let's test before publishMichel Weststratebefore adoption3f9a94e
lines 273–274why, one step back273}274arrayTraps.set = function(state, prop, value) {Merge pull request #1028 from immerjs/immer-10Michel Weststratebefore adoption2ef9a42
lines 275–280why, one step back275 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 back281 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 descperf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202
lines 294–295why, one step back294 ? VALUE in desc295 ? desc[VALUE]chore: let's test before publishMichel Weststratebefore adoption3f9a94e
lines 296–307why, one step back296 : // This is a very special case, if the prop is a getter defined by the297 // 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 undefinedMerge pull request #1028 from immerjs/immer-10Michel Weststratebefore adoption2ef9a42
line 308why, one step back308 let proto = getPrototypeOf(source)chore: let's test before publishMichel Weststratebefore adoption3f9a94e
lines 309–311why, one step back309 while (proto) {310 const desc = Object.getOwnPropertyDescriptor(proto, prop)311 if (desc) return descMerge pull request #1028 from immerjs/immer-10Michel Weststratebefore adoption2ef9a42
line 312why, one step back312 proto = getPrototypeOf(proto)chore: let's test before publishMichel Weststratebefore adoption3f9a94e
lines 313–325why, one step back313 }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}325perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202
line 326why, one step back326export function prepareCopy(state: ImmerState) {chore: let's test before publishMichel Weststratebefore adoption3f9a94e
line 327why, one step back327 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 back328 // Actually create the `assigned_` map now that we329 // 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 back331 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 back335 }336}