proxy.ts
This file
Path
src/core/proxy.ts
335 lines · 9.0 KiB · TypeScript
Last changed by
feat: Override array methods to avoid proxy creation while iterating and updating (#1184)Mark Eriksonbefore adoptiond38a9d0
History of this fileTake it
The walk stopped after 200 commits: lines older than 6555173 point at it.
fix: #785 fix type inference for produce incorrectly inferring promise (#786)hardfistbefore adoption6555173
lines 1–14why, one step back1import {2 each,3 has,4 is,5 isDraftable,6 shallowCopy,7 latest,8 ImmerBaseState,9 ImmerState,10 Drafted,11 AnyObject,12 AnyArray,13 Objectish,14 getCurrentScope,Merge pull request #1028 from immerjs/immer-10Michel Weststratebefore adoption2ef9a42
line 15why, one step back15 getPrototypeOf,fix: #785 fix type inference for produce incorrectly inferring promise (#786)hardfistbefore adoption6555173
lines 16–18why, one step back16 DRAFT_STATE,17 die,18 createProxy,Merge pull request #1028 from immerjs/immer-10Michel Weststratebefore adoption2ef9a42
line 19why, one step back19 ArchType,perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202
lines 20–25why, one step back20 ImmerScope,21 handleCrossReference,22 WRITABLE,23 CONFIGURABLE,24 ENUMERABLE,25 VALUE,feat: Override array methods to avoid proxy creation while iterating and updating (#1184)Mark Eriksonbefore adoptiond38a9d0
lines 26–27why, one step back26 isArray,27 isArrayIndexfix: #785 fix type inference for produce incorrectly inferring promise (#786)hardfistbefore adoption6555173
lines 28–35why, one step back28} from "../internal"2930interface ProxyBaseState extends ImmerBaseState {31 parent_?: ImmerState32 revoke_(): void33}3435export interface ProxyObjectState extends ProxyBaseState {Merge pull request #1028 from immerjs/immer-10Michel Weststratebefore adoption2ef9a42
line 36why, one step back36 type_: ArchType.Objectfix: #785 fix type inference for produce incorrectly inferring promise (#786)hardfistbefore adoption6555173
lines 37–42why, one step back37 base_: any38 copy_: any39 draft_: Drafted<AnyObject, ProxyObjectState>40}4142export interface ProxyArrayState extends ProxyBaseState {Merge pull request #1028 from immerjs/immer-10Michel Weststratebefore adoption2ef9a42
line 43why, one step back43 type_: ArchType.Arrayfix: #785 fix type inference for produce incorrectly inferring promise (#786)hardfistbefore adoption6555173
lines 44–46why, one step back44 base_: AnyArray45 copy_: AnyArray | null46 draft_: Drafted<AnyArray, ProxyArrayState>feat: Override array methods to avoid proxy creation while iterating and updating (#1184)Mark Eriksonbefore adoptiond38a9d0
lines 47–48why, one step back47 operationMethod?: string48 allIndicesReassigned_?: booleanfix: #785 fix type inference for produce incorrectly inferring promise (#786)hardfistbefore adoption6555173
lines 49–60why, one step back49}5051type ProxyState = ProxyObjectState | ProxyArrayState5253/**54 * Returns a new draft of the `base` object.55 *56 * The second argument is the parent draft-state (used internally).57 */58export function createProxyProxy<T extends Objectish>(59 base: T,60 parent?: ImmerStateperf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202
lines 61–62why, one step back61): [Drafted<T, ProxyState>, ProxyState] {62 const baseIsArray = isArray(base)fix: #785 fix type inference for produce incorrectly inferring promise (#786)hardfistbefore adoption6555173
line 63why, one step back63 const state: ProxyState = {perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202
line 64why, one step back64 type_: baseIsArray ? ArchType.Array : (ArchType.Object as any),fix: #785 fix type inference for produce incorrectly inferring promise (#786)hardfistbefore adoption6555173
lines 65–71why, one step back65 // Track which produce call this is associated with.66 scope_: parent ? parent.scope_ : getCurrentScope()!,67 // True for both shallow and deep changes.68 modified_: false,69 // Used during finalization.70 finalized_: false,71 // 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 72–73why, one step back72 // actually instantiated in `prepareCopy()`73 assigned_: undefined,fix: #785 fix type inference for produce incorrectly inferring promise (#786)hardfistbefore adoption6555173
lines 74–83why, one step back74 // The parent draft state.75 parent_: parent,76 // The base state.77 base_: base,78 // The base proxy.79 draft_: null as any, // set below80 // The base copy with any updated values.81 copy_: null,82 // Called by the `produce` function.83 revoke_: null as any,perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202
lines 84–86why, one step back84 isManual_: false,85 // `callbacks` actually gets assigned in `createProxy`86 callbacks_: undefined as anyfix: #785 fix type inference for produce incorrectly inferring promise (#786)hardfistbefore adoption6555173
lines 87–96why, one step back87 }8889 // the traps must target something, a bit like the 'real' base.90 // but also, we need to be able to determine from the target what the relevant state is91 // (to avoid creating traps per instance to capture the state in closure,92 // and to avoid creating weird hidden properties as well)93 // So the trick is to use 'state' as the actual 'target'! (and make sure we intercept everything)94 // Note that in the case of an array, we put the state in an array to have better Reflect defaults ootb95 let target: T = state as any96 let traps: ProxyHandler<object | Array<any>> = objectTrapsperf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202
line 97why, one step back97 if (baseIsArray) {fix: #785 fix type inference for produce incorrectly inferring promise (#786)hardfistbefore adoption6555173
lines 98–104why, one step back98 target = [state] as any99 traps = arrayTraps100 }101102 const {revoke, proxy} = Proxy.revocable(target, traps)103 state.draft_ = proxy as any104 state.revoke_ = revokeperf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202
line 105why, one step back105 return [proxy as any, state]fix: #785 fix type inference for produce incorrectly inferring promise (#786)hardfistbefore adoption6555173
lines 106–114why, one step back106}107108/**109 * Object drafts110 */111export const objectTraps: ProxyHandler<ProxyState> = {112 get(state, prop) {113 if (prop === DRAFT_STATE) return state114feat: Override array methods to avoid proxy creation while iterating and updating (#1184)Mark Eriksonbefore adoptiond38a9d0
lines 115–125why, one step back115 let arrayPlugin = state.scope_.arrayMethodsPlugin_116 const isArrayWithStringProp =117 state.type_ === ArchType.Array && typeof prop === "string"118 // Intercept array methods so that we can override119 // behavior and skip proxy creation for perf120 if (isArrayWithStringProp) {121 if (arrayPlugin?.isArrayOperationMethod(prop)) {122 return arrayPlugin.createMethodInterceptor(state, prop)123 }124 }125fix: #785 fix type inference for produce incorrectly inferring promise (#786)hardfistbefore adoption6555173
line 126why, one step back126 const source = latest(state)perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202
line 127why, one step back127 if (!has(source, prop, state.type_)) {fix: #785 fix type inference for produce incorrectly inferring promise (#786)hardfistbefore adoption6555173
lines 128–132why, one step back128 // non-existing or non-own property...129 return readPropFromProto(state, source, prop)130 }131 const value = source[prop]132 if (state.finalized_ || !isDraftable(value)) {feat: Override array methods to avoid proxy creation while iterating and updating (#1184)Mark Eriksonbefore adoptiond38a9d0
lines 133–146why, one step back133 return value134 }135136 // During mutating array operations, defer proxy creation for array elements137 // This optimization avoids creating unnecessary proxies during sort/reverse138 if (139 isArrayWithStringProp &&140 (state as ProxyArrayState).operationMethod &&141 arrayPlugin?.isMutatingArrayMethod(142 (state as ProxyArrayState).operationMethod!143 ) &&144 isArrayIndex(prop)145 ) {146 // Return raw value during mutating operations, create proxy only if modifiedfix: #785 fix type inference for produce incorrectly inferring promise (#786)hardfistbefore adoption6555173
lines 147–152why, one step back147 return value148 }149 // Check for existing draft in modified state.150 // Assigned values are never drafted. This catches any drafts we created, too.151 if (value === peek(state.base_, prop)) {152 prepareCopy(state)perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202
lines 153–157why, one step back153 // Ensure array keys are always numbers154 const childKey = state.type_ === ArchType.Array ? +(prop as string) : prop155 const childDraft = createProxy(state.scope_, value, state, childKey)156157 return (state.copy_![childKey] = childDraft)fix: #785 fix type inference for produce incorrectly inferring promise (#786)hardfistbefore adoption6555173
lines 158–186why, one step back158 }159 return value160 },161 has(state, prop) {162 return prop in latest(state)163 },164 ownKeys(state) {165 return Reflect.ownKeys(latest(state))166 },167 set(168 state: ProxyObjectState,169 prop: string /* strictly not, but helps TS */,170 value171 ) {172 const desc = getDescriptorFromProto(latest(state), prop)173 if (desc?.set) {174 // special case: if this write is captured by a setter, we have175 // to trigger it with the correct context176 desc.set.call(state.draft_, value)177 return true178 }179 if (!state.modified_) {180 // the last check is because we need to be able to distinguish setting a non-existing to undefined (which is a change)181 // from setting an existing property with value undefined to undefined (which is not a change)182 const current = peek(latest(state), prop)183 // special case, if we assigning the original value to a draft, we can ignore the assignment184 const currentState: ProxyObjectState = current?.[DRAFT_STATE]185 if (currentState && currentState.base_ === value) {186 state.copy_![prop] = valueperf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202
line 187why, one step back187 state.assigned_!.set(prop, false)fix: #785 fix type inference for produce incorrectly inferring promise (#786)hardfistbefore adoption6555173
lines 188–189why, one step back188 return true189 }perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202
lines 190–193why, one step back190 if (191 is(value, current) &&192 (value !== undefined || has(state.base_, prop, state.type_))193 )fix: #785 fix type inference for produce incorrectly inferring promise (#786)hardfistbefore adoption6555173
lines 194–198why, one step back194 return true195 prepareCopy(state)196 markChanged(state)197 }198fix: #807 new undefined properties should end up in result objectMichel Weststratebefore adoptiondc3f66c
line 199why, one step back199 if (fix: special case NaN in setter (#912)Raybefore adoption5721bb7
lines 200–202why, one step back200 (state.copy_![prop] === value &&201 // special case: handle new props with value 'undefined'202 (value !== undefined || prop in state.copy_)) ||fix: #807 new undefined properties should end up in result objectMichel Weststratebefore adoptiondc3f66c
line 203why, one step back203 // special case: NaNfix: special case NaN in setter (#912)Raybefore adoption5721bb7
line 204why, one step back204 (Number.isNaN(value) && Number.isNaN(state.copy_![prop]))fix: #807 new undefined properties should end up in result objectMichel Weststratebefore adoptiondc3f66c
lines 205–206why, one step back205 )206 return truefix: #785 fix type inference for produce incorrectly inferring promise (#786)hardfistbefore adoption6555173
lines 207–209why, one step back207208 // @ts-ignore209 state.copy_![prop] = valueperf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202
lines 210–212why, one step back210 state.assigned_!.set(prop, true)211212 handleCrossReference(state, prop, value)fix: #785 fix type inference for produce incorrectly inferring promise (#786)hardfistbefore adoption6555173
lines 213–215why, one step back213 return true214 },215 deleteProperty(state, prop: string) {perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202
line 216why, one step back216 prepareCopy(state)fix: #785 fix type inference for produce incorrectly inferring promise (#786)hardfistbefore adoption6555173
lines 217–218why, one step back217 // The `undefined` check is a fast path for pre-existing keys.218 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 219why, one step back219 state.assigned_!.set(prop, false)fix: #785 fix type inference for produce incorrectly inferring promise (#786)hardfistbefore adoption6555173
lines 220–222why, one step back220 markChanged(state)221 } else {222 // 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 223why, one step back223 state.assigned_!.delete(prop)fix: #785 fix type inference for produce incorrectly inferring promise (#786)hardfistbefore adoption6555173
line 224why, one step back224 }Merge pull request #1028 from immerjs/immer-10Michel Weststratebefore adoption2ef9a42
lines 225–227why, one step back225 if (state.copy_) {226 delete state.copy_[prop]227 }fix: #785 fix type inference for produce incorrectly inferring promise (#786)hardfistbefore adoption6555173
lines 228–236why, one step back228 return true229 },230 // Note: We never coerce `desc.value` into an Immer draft, because we can't make231 // the same guarantee in ES5 mode.232 getOwnPropertyDescriptor(state, prop) {233 const owner = latest(state)234 const desc = Reflect.getOwnPropertyDescriptor(owner, prop)235 if (!desc) return desc236 return {perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202
lines 237–240why, one step back237 [WRITABLE]: true,238 [CONFIGURABLE]: state.type_ !== ArchType.Array || prop !== "length",239 [ENUMERABLE]: desc[ENUMERABLE],240 [VALUE]: owner[prop]fix: #785 fix type inference for produce incorrectly inferring promise (#786)hardfistbefore adoption6555173
lines 241–246why, one step back241 }242 },243 defineProperty() {244 die(11)245 },246 getPrototypeOf(state) {Merge pull request #1028 from immerjs/immer-10Michel Weststratebefore adoption2ef9a42
line 247why, one step back247 return getPrototypeOf(state.base_)fix: #785 fix type inference for produce incorrectly inferring promise (#786)hardfistbefore adoption6555173
lines 248–261why, one step back248 },249 setPrototypeOf() {250 die(12)251 }252}253254/**255 * Array drafts256 */257258const arrayTraps: ProxyHandler<[ProxyArrayState]> = {}259each(objectTraps, (key, fn) => {260 // @ts-ignore261 arrayTraps[key] = function() {perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202
lines 262–264why, one step back262 const args = arguments263 args[0] = args[0][0]264 return fn.apply(this, args)fix: #785 fix type inference for produce incorrectly inferring promise (#786)hardfistbefore adoption6555173
lines 265–267why, one step back265 }266})267arrayTraps.deleteProperty = function(state, prop) {Merge pull request #1028 from immerjs/immer-10Michel Weststratebefore adoption2ef9a42
lines 268–269why, one step back268 if (process.env.NODE_ENV !== "production" && isNaN(parseInt(prop as any)))269 die(13)fix: incorrect patches for `delete` on arrays. Fixes #879Michel Weststratebefore adoptiond91a659
lines 270–271why, one step back270 // @ts-ignore271 return arrayTraps.set!.call(this, state, prop, undefined)fix: #785 fix type inference for produce incorrectly inferring promise (#786)hardfistbefore adoption6555173
lines 272–273why, one step back272}273arrayTraps.set = function(state, prop, value) {Merge pull request #1028 from immerjs/immer-10Michel Weststratebefore adoption2ef9a42
lines 274–279why, one step back274 if (275 process.env.NODE_ENV !== "production" &&276 prop !== "length" &&277 isNaN(parseInt(prop as any))278 )279 die(14)fix: #785 fix type inference for produce incorrectly inferring promise (#786)hardfistbefore adoption6555173
lines 280–292why, one step back280 return objectTraps.set!.call(this, state[0], prop, value, state[0])281}282283// Access a property without creating an Immer draft.284function peek(draft: Drafted, prop: PropertyKey) {285 const state = draft[DRAFT_STATE]286 const source = state ? latest(state) : draft287 return source[prop]288}289290function readPropFromProto(state: ImmerState, source: any, prop: PropertyKey) {291 const desc = getDescriptorFromProto(source, prop)292 return descperf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202
lines 293–294why, one step back293 ? VALUE in desc294 ? desc[VALUE]fix: #785 fix type inference for produce incorrectly inferring promise (#786)hardfistbefore adoption6555173
lines 295–306why, one step back295 : // This is a very special case, if the prop is a getter defined by the296 // prototype, we should invoke it with the draft as context!297 desc.get?.call(state.draft_)298 : undefined299}300301function getDescriptorFromProto(302 source: any,303 prop: PropertyKey304): PropertyDescriptor | undefined {305 // 'in' checks proto!306 if (!(prop in source)) return undefinedMerge pull request #1028 from immerjs/immer-10Michel Weststratebefore adoption2ef9a42
line 307why, one step back307 let proto = getPrototypeOf(source)fix: #785 fix type inference for produce incorrectly inferring promise (#786)hardfistbefore adoption6555173
lines 308–310why, one step back308 while (proto) {309 const desc = Object.getOwnPropertyDescriptor(proto, prop)310 if (desc) return descMerge pull request #1028 from immerjs/immer-10Michel Weststratebefore adoption2ef9a42
line 311why, one step back311 proto = getPrototypeOf(proto)fix: #785 fix type inference for produce incorrectly inferring promise (#786)hardfistbefore adoption6555173
lines 312–324why, one step back312 }313 return undefined314}315316export function markChanged(state: ImmerState) {317 if (!state.modified_) {318 state.modified_ = true319 if (state.parent_) {320 markChanged(state.parent_)321 }322 }323}324perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202
line 325why, one step back325export function prepareCopy(state: ImmerState) {fix: #785 fix type inference for produce incorrectly inferring promise (#786)hardfistbefore adoption6555173
line 326why, one step back326 if (!state.copy_) {perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202
lines 327–329why, one step back327 // Actually create the `assigned_` map now that we328 // know this is a modified draft.329 state.assigned_ = new Map()Merge pull request #1028 from immerjs/immer-10Michel Weststratebefore adoption2ef9a42
lines 330–333why, one step back330 state.copy_ = shallowCopy(331 state.base_,332 state.scope_.immer_.useStrictShallowCopy_333 )fix: #785 fix type inference for produce incorrectly inferring promise (#786)hardfistbefore adoption6555173
lines 334–335why, one step back334 }335}